Skip to content
Docs
Getting started
Usage with Firebase Auth

Using Firebase Auth

Follow the official firebase/auth guide (opens in a new tab) to handle different operations like signInWithEmailAndPassword or signOut.

Check out the starter example for more complete examples, including login, registration, and password reset flows.

Example LoginPage

Here’s a simple login page client component that lets users sign in with their email and password:

page.tsx
'use client';
 
import * as React from 'react';
import {getAuth, signInWithEmailAndPassword} from 'firebase/auth';
import {useRouter} from 'next/navigation';
 
export default function LoginPage() {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const router = useRouter();
 
  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    event.stopPropagation();
 
    const credential = await signInWithEmailAndPassword(
      getAuth(),
      email,
      password
    );
    const idToken = await credential.user.getIdToken();
 
    // Sets authenticated browser cookies
    await fetch('/api/login', {
      headers: {
        Authorization: `Bearer ${idToken}`
      }
    });
 
    // Refresh page after updating browser cookies
    router.refresh();
  }
 
  return (
    <div>
      <h1>Login</h1>
      <form onSubmit={handleSubmit}>
        <input
          required
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          name="email"
          type="email"
          placeholder="Email address"
        />
        <br />
        <input
          required
          name="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          type="password"
          placeholder="Password"
          minLength={8}
        />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

Let's focus on the form submission handler:

async function handleSubmit(event: React.FormEvent) {
  event.preventDefault();
  event.stopPropagation();
 
  const credential = await signInWithEmailAndPassword(
    getAuth(),
    email,
    password
  );
  const idToken = await credential.user.getIdToken();
 
  // Sets authenticated browser cookies
  await fetch('/api/login', {
    headers: {
      Authorization: `Bearer ${idToken}`
    }
  });
 
  // Refresh page after updating browser cookies
  router.refresh();
}

It can be broken down to following actions:

  1. We sign user in using email and password using signInWithEmailAndPassword from Firebase Client SDK
  2. We extract idToken using credential returned by signInWithEmailAndPassword
  3. We call /api/login endpoint exposed by the middleware to update browser cookies with authentication token
  4. We call router.refresh() to re-render server components with updated credentials