0
0
FirebaseHow-ToBeginner · 4 min read

How to Use Firebase Auth with Next.js: Simple Guide

To use Firebase Auth with Next.js, first install Firebase SDK, initialize Firebase in your project, then use Firebase Auth methods like signInWithEmailAndPassword in your Next.js components. Manage user state with React hooks and protect pages by checking authentication status.
📐

Syntax

Here is the basic syntax to initialize Firebase and use authentication in Next.js:

  • initializeApp(config): Sets up Firebase with your project settings.
  • getAuth(): Gets the Firebase Auth service instance.
  • signInWithEmailAndPassword(auth, email, password): Signs in a user with email and password.
  • onAuthStateChanged(auth, callback): Listens for changes in user sign-in state.
javascript
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword, onAuthStateChanged } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
  // other config values
};

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

// Sign in example
signInWithEmailAndPassword(auth, 'user@example.com', 'password123')
  .then(userCredential => {
    const user = userCredential.user;
    console.log('Signed in:', user.email);
  })
  .catch(error => {
    console.error('Error signing in:', error.message);
  });

// Listen for auth state changes
onAuthStateChanged(auth, user => {
  if (user) {
    console.log('User is signed in:', user.email);
  } else {
    console.log('No user signed in');
  }
});
💻

Example

This example shows a simple Next.js page that lets users sign in with email and password using Firebase Auth. It also displays the current user's email when signed in.

javascript
import { useState, useEffect } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword, onAuthStateChanged, signOut } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID'
};

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

export default function LoginPage() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [user, setUser] = useState(null);
  const [error, setError] = useState('');

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, currentUser => {
      setUser(currentUser);
    });
    return () => unsubscribe();
  }, []);

  const handleLogin = async (e) => {
    e.preventDefault();
    setError('');
    try {
      await signInWithEmailAndPassword(auth, email, password);
    } catch (err) {
      setError(err.message);
    }
  };

  const handleLogout = async () => {
    await signOut(auth);
  };

  if (user) {
    return (
      <div>
        <h1>Welcome, {user.email}</h1>
        <button onClick={handleLogout}>Sign Out</button>
      </div>
    );
  }

  return (
    <form onSubmit={handleLogin}>
      <h1>Sign In</h1>
      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={e => setEmail(e.target.value)}
        required
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={e => setPassword(e.target.value)}
        required
      />
      <button type="submit">Sign In</button>
      {error && <p style={{color: 'red'}}>{error}</p>}
    </form>
  );
}
Output
When running, the page shows a sign-in form. After entering valid credentials, it displays "Welcome, user@example.com" and a sign-out button.
⚠️

Common Pitfalls

Common mistakes when using Firebase Auth with Next.js include:

  • Not initializing Firebase only once, causing errors or multiple instances.
  • Using Firebase Auth methods on the server side instead of client side, which can cause errors because Firebase Auth depends on browser APIs.
  • Not handling asynchronous auth state changes properly, leading to UI flicker or incorrect user state.
  • Exposing Firebase config publicly without restrictions (Firebase config is safe to expose but rules must be secure).
javascript
/* Wrong: Initializing Firebase inside a component causes multiple instances */
import { initializeApp } from 'firebase/app';

export default function Page() {
  const app = initializeApp({ apiKey: 'key', authDomain: 'domain' }); // BAD: runs on every render
  // ...
}

/* Right: Initialize Firebase once in a separate module */
// firebaseClient.js
import { initializeApp, getApps } from 'firebase/app';

const firebaseConfig = { apiKey: 'key', authDomain: 'domain' };

const app = !getApps().length ? initializeApp(firebaseConfig) : getApps()[0];

export default app;
📊

Quick Reference

Tips for using Firebase Auth with Next.js:

  • Initialize Firebase once in a separate file and import it.
  • Use React hooks like useEffect and useState to track auth state.
  • Perform auth actions (sign-in, sign-out) on client side only.
  • Protect pages by checking if user is null and redirect if needed.
  • Secure Firebase rules to protect your data.

Key Takeaways

Initialize Firebase only once and reuse the instance across your Next.js app.
Use Firebase Auth client-side methods inside React components with hooks to manage user state.
Avoid running Firebase Auth code on the server side to prevent errors.
Listen to auth state changes with onAuthStateChanged to update UI reactively.
Secure your Firebase project with proper rules even though config is public.