What is Firebase Authentication?
Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook, Twitter, and more.
Firebase Auth integrates tightly with other Firebase services and leverages industry standards like OAuth 2.0 and OpenID Connect, making it easy to integrate with your custom backend.
π Authentication Methods
- π§ Email/Password: Traditional sign-up and sign-in with email.
- π± Phone Number: SMS verification for phone authentication.
- π Social Providers: Google, Facebook, Twitter, GitHub, Apple, Microsoft.
- π Anonymous: Create temporary anonymous accounts.
- π« Custom Auth: Integrate with your own authentication system.
Setting Up Authentication
First, enable authentication methods in the Firebase Console:
- Go to Firebase Console β Authentication
- Click "Get started" if you haven't already
- Go to the "Sign-in method" tab
- Enable the providers you want to use
// Import auth functions
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged,
GoogleAuthProvider,
signInWithPopup
} from 'firebase/auth';
// Get the auth instance
const auth = getAuth();
Email/Password Authentication
The most common authentication method:
Create a New User
async function signUp(email, password) {
try {
const userCredential = await createUserWithEmailAndPassword(
auth,
email,
password
);
const user = userCredential.user;
console.log('User created:', user.uid);
return user;
} catch (error) {
console.error('Error signing up:', error.code, error.message);
throw error;
}
}
// Usage
await signUp('user@example.com', 'securePassword123');
Sign In Existing User
async function signIn(email, password) {
try {
const userCredential = await signInWithEmailAndPassword(
auth,
email,
password
);
const user = userCredential.user;
console.log('Signed in:', user.email);
return user;
} catch (error) {
switch (error.code) {
case 'auth/user-not-found':
console.error('No user found with this email');
break;
case 'auth/wrong-password':
console.error('Invalid password');
break;
default:
console.error('Sign in error:', error.message);
}
throw error;
}
}
Sign Out
async function logOut() {
try {
await signOut(auth);
console.log('User signed out');
} catch (error) {
console.error('Error signing out:', error);
}
}
Google Sign-In
Add Google authentication with just a few lines of code:
import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth';
const googleProvider = new GoogleAuthProvider();
// Optional: Add scopes for additional permissions
googleProvider.addScope('https://www.googleapis.com/auth/contacts.readonly');
async function signInWithGoogle() {
try {
const result = await signInWithPopup(auth, googleProvider);
// This gives you a Google Access Token
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info
const user = result.user;
console.log('Google user:', user.displayName, user.email);
return user;
} catch (error) {
console.error('Google sign-in error:', error);
throw error;
}
}
Listening to Auth State
Track when users sign in or out:
import { onAuthStateChanged } from 'firebase/auth';
// Set up auth state listener
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in
console.log('User is logged in:', user.uid);
console.log('Email:', user.email);
console.log('Display name:', user.displayName);
console.log('Photo URL:', user.photoURL);
console.log('Email verified:', user.emailVerified);
} else {
// User is signed out
console.log('User is logged out');
}
});
// Later, unsubscribe when component unmounts
unsubscribe();
React Hook for Authentication
Create a custom hook to manage auth state in React:
// hooks/useAuth.js
import { useState, useEffect } from 'react';
import { auth } from '../lib/firebase';
import {
onAuthStateChanged,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signOut
} from 'firebase/auth';
export function useAuth() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
setUser(user);
setLoading(false);
});
return unsubscribe;
}, []);
const login = (email, password) => {
return signInWithEmailAndPassword(auth, email, password);
};
const register = (email, password) => {
return createUserWithEmailAndPassword(auth, email, password);
};
const logout = () => {
return signOut(auth);
};
return { user, loading, login, register, logout };
}
// Usage in a component
function Profile() {
const { user, loading, logout } = useAuth();
if (loading) return <div>Loading...</div>;
if (!user) return <div>Please sign in</div>;
return (
<div>
<p>Welcome, {user.email}!</p>
<button onClick={logout}>Sign Out</button>
</div>
);
}
Password Reset
Allow users to reset their password via email:
import { sendPasswordResetEmail } from 'firebase/auth';
async function resetPassword(email) {
try {
await sendPasswordResetEmail(auth, email);
console.log('Password reset email sent');
} catch (error) {
console.error('Error sending reset email:', error);
throw error;
}
}
Email Verification
Send verification emails to confirm user email addresses:
import { sendEmailVerification } from 'firebase/auth';
async function verifyEmail() {
const user = auth.currentUser;
if (user) {
try {
await sendEmailVerification(user);
console.log('Verification email sent');
} catch (error) {
console.error('Error sending verification:', error);
}
}
}
// Check if email is verified
function isEmailVerified() {
const user = auth.currentUser;
return user?.emailVerified ?? false;
}
Update User Profile
Update display name and photo URL:
import { updateProfile, updateEmail } from 'firebase/auth';
async function updateUserProfile(displayName, photoURL) {
const user = auth.currentUser;
if (user) {
try {
await updateProfile(user, {
displayName: displayName,
photoURL: photoURL
});
console.log('Profile updated');
} catch (error) {
console.error('Error updating profile:', error);
}
}
}
async function updateUserEmail(newEmail) {
const user = auth.currentUser;
if (user) {
try {
await updateEmail(user, newEmail);
console.log('Email updated');
} catch (error) {
console.error('Error updating email:', error);
}
}
}
Protected Routes (Next.js Example)
Create protected routes that require authentication:
// components/ProtectedRoute.js
'use client';
import { useAuth } from '../hooks/useAuth';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
export default function ProtectedRoute({ children }) {
const { user, loading } = useAuth();
const router = useRouter();
useEffect(() => {
if (!loading && !user) {
router.push('/login');
}
}, [user, loading, router]);
if (loading) {
return <div>Loading...</div>;
}
if (!user) {
return null;
}
return children;
}
// Usage
export default function DashboardPage() {
return (
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
);
}
π‘ Key Takeaways
- β’ Firebase Auth supports email/password, social logins, and more
- β’ Use onAuthStateChanged to track user authentication state
- β’ Create custom hooks for cleaner React integration
- β’ Handle errors gracefully with specific error codes
- β’ Implement protected routes to secure pages
- β’ Always verify emails for sensitive applications
π Learn More
-
Firebase Authentication Docs β
Complete guide to Firebase Auth features and APIs
-
Get Started with Firebase Auth on Web β
Step-by-step tutorial for web applications
-
Manage Users in Firebase β
Learn about user management and profile updates