Back

Reading and Writing Data Using the Firebase Auth API

Aug 9, 20246 minute read

Hey there, fellow JavaScript wizards! Ready to dive into the world of Firebase Auth API and master the art of data syncing? Let's get cracking!

Setting Up Firebase Auth

First things first, let's get Firebase Auth up and running. I'm assuming you've already got Firebase set up in your project (if not, what are you waiting for?). Here's a quick refresher on initializing Firebase Auth:

import { initializeApp } from 'firebase/app'; import { getAuth } from 'firebase/auth'; const firebaseConfig = { // Your config here }; const app = initializeApp(firebaseConfig); const auth = getAuth(app);

User Authentication

Now that we're all set up, let's get our users on board. Here's a slick little snippet for email/password authentication:

import { signInWithEmailAndPassword } from 'firebase/auth'; signInWithEmailAndPassword(auth, email, password) .then((userCredential) => { const user = userCredential.user; console.log('Welcome back!', user.email); }) .catch((error) => { console.error('Oops!', error.message); });

Reading User Data

Alright, time to get our hands on some user data. First, let's grab the current user:

const user = auth.currentUser;

Now, let's fetch some user-specific data from Firestore:

import { getFirestore, doc, getDoc } from 'firebase/firestore'; const db = getFirestore(); const userDoc = doc(db, 'users', user.uid); getDoc(userDoc).then((docSnap) => { if (docSnap.exists()) { console.log('User data:', docSnap.data()); } else { console.log('No such document!'); } });

Writing User Data

Time to give our users some control over their data. Here's how we can update their profile and store some custom data:

import { updateProfile } from 'firebase/auth'; import { setDoc } from 'firebase/firestore'; // Update profile updateProfile(user, { displayName: 'Cool Developer', photoURL: 'https://example.com/photo.jpg' }).then(() => { console.log('Profile updated!'); }); // Store custom data setDoc(userDoc, { favoriteLanguage: 'JavaScript', coffeePreference: 'Espresso' }, { merge: true }).then(() => { console.log('Custom data stored!'); });

Real-time Data Syncing

Now for the really cool part - real-time updates! Check this out:

import { onSnapshot } from 'firebase/firestore'; onSnapshot(userDoc, (doc) => { console.log('Current data:', doc.data()); });

Just like that, you're synced up and ready to roll!

Handling Offline/Online States

Let's make our app work seamlessly, even when the internet decides to take a coffee break:

import { enableIndexedDbPersistence } from 'firebase/firestore'; enableIndexedDbPersistence(db).catch((err) => { if (err.code == 'failed-precondition') { console.log('Multiple tabs open, persistence can only be enabled in one tab at a a time.'); } else if (err.code == 'unimplemented') { console.log('The current browser does not support all of the features required to enable persistence'); } });

Security Rules

Don't forget to lock down your Firestore! Here's a quick example of some security rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

Error Handling and Edge Cases

Always be prepared for the unexpected:

try { // Your Firebase operations here } catch (error) { if (error.code === 'permission-denied') { console.log('You don't have permission to perform this action'); } else { console.error('An error occurred:', error.message); } }

Best Practices

Before we wrap up, here are some pro tips:

  • Keep your data structures flat for better performance
  • Use batch writes for multiple operations
  • Implement proper error handling and user feedback

And there you have it! You're now armed with the knowledge to create awesome, real-time, user-centric apps with Firebase Auth API. Remember, practice makes perfect, so get out there and start coding. Happy syncing!