Skip to content
Docs
Getting started
Usage with Firebase Auth

Usage with Firebase Auth

Use official firebase/auth guide (opens in a new tab) to perform different operations, such as signInWithEmailAndPassword or signOut.

See starter example for more complete examples, including login, registration and password reset flow.

Example LoginPage

A very basic login page client component that allows users to sign in using 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