Coed for beginners

Learn how to implement secure authentication in your web apps using Firebase Auth with email, Google, and social providers.

Mike Johnson
12 min read
0 views
FirebaseAuthenticationSecurityWeb Development

Firebase Authentication: A Complete Guide

Firebase Authentication provides an easy way to add user authentication to your applications with support for multiple auth providers.

Setting Up Firebase

First, install the Firebase SDK:

npm install firebase

Then initialize Firebase in your app:

import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "your-app.firebaseapp.com",
  projectId: "your-project-id"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

Email/Password Authentication

Implement email and password sign-up:

import { createUserWithEmailAndPassword } from 'firebase/auth';

async function signUp(email, password) {
  try {
    const userCredential = await createUserWithEmailAndPassword(
      auth,
      email,
      password
    );
    console.log('User created:', userCredential.user);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

Google Sign-In

Add Google authentication:

import { signInWithPopup, GoogleAuthProvider } from 'firebase/auth';

async function signInWithGoogle() {
  const provider = new GoogleAuthProvider();
  try {
    const result = await signInWithPopup(auth, provider);
    console.log('User:', result.user);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

Protected Routes

Use auth state to protect routes:

import { onAuthStateChanged } from 'firebase/auth';

onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in
    console.log('Logged in:', user.uid);
  } else {
    // User is signed out
    console.log('Please sign in');
  }
});

Conclusion

Firebase Authentication makes it easy to add secure, scalable authentication to your applications with minimal setup!

Share this article:

Recommended Reading