Skip to content

Authentication with Firebase Auth

This guide connects every Pulze sign-in page to Firebase Authentication. It works in both versions. Next.js gets one extra step at the end: a session cookie, so the server knows who's signed in.

Read Authentication first: it explains the adapter these steps fill in.

Time: about 45 minutes for email, password and Google. Two-step and SSO add about 20 minutes each.

What Firebase covers

Pulze feature Firebase Notes
Email + password ✓
Google, GitHub, Apple ✓ Turn each one on in the console
Magic link ✓ "Email link"
Forgot / reset password ✓ link-based Keep resetWith: "link"
Two-step: app code (TOTP) ✓ with Identity Platform Upgrade the project to Identity Platform (free tier available)
Two-step: text message ✓ with Identity Platform
Two-step: backup codes ✗ The adapter shows "not available"; people use their phone or contact support
SSO (SAML / OIDC) ✓ with Identity Platform One provider per company
Passkey on lock screen ✗ People unlock with their password
Workspaces and invites Your database Example below uses Firestore

1. Create the Firebase project

  1. Open the Firebase console and create a project (or open yours).
  2. Build › Authentication › Get started. Under Sign-in method, turn on Email/Password (and Email link if you keep magic links), then Google, GitHub and Apple to match siteConfig.auth.providers.
  3. Authentication › Settings › Authorized domains: add your live domain (for example app.acme.io). localhost is there already.
  4. Project settings › General › Your apps › Web app (</>): register an app and copy the config values.

2. Install and add your keys

pnpm add firebase

Create .env.local in the app folder:

# Next.js
NEXT_PUBLIC_FIREBASE_API_KEY=AIza...
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=acme-app.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=acme-app
NEXT_PUBLIC_FIREBASE_APP_ID=1:123:web:abc

For Vite, use the same names with VITE_ instead of NEXT_PUBLIC_, and read them with import.meta.env.VITE_FIREBASE_API_KEY.

These keys identify your project; they aren't secrets. What protects your data is your security rules and the server checks in step 6.

3. Write the adapter

Create src/data/auth/firebase.ts. Every method of AuthAdapter is here; delete the parts for features you turned off in siteConfig.auth.

import { getApps, initializeApp } from "firebase/app"
import {
  browserLocalPersistence,
  browserSessionPersistence,
  confirmPasswordReset,
  createUserWithEmailAndPassword,
  EmailAuthProvider,
  getAuth,
  getMultiFactorResolver,
  GithubAuthProvider,
  GoogleAuthProvider,
  isSignInWithEmailLink,
  type MultiFactorError,
  type MultiFactorResolver,
  OAuthProvider,
  PhoneAuthProvider,
  PhoneMultiFactorGenerator,
  reauthenticateWithCredential,
  RecaptchaVerifier,
  SAMLAuthProvider,
  sendPasswordResetEmail,
  sendSignInLinkToEmail,
  setPersistence,
  signInWithEmailAndPassword,
  signInWithEmailLink,
  signInWithPopup,
  signOut,
  TotpMultiFactorGenerator,
  updateProfile,
  type UserCredential,
  verifyPasswordResetCode,
} from "firebase/auth"
import { FirebaseError } from "firebase/app"

import { siteConfig } from "@pulze/config"

import { setPendingEmail } from "./pending"
import { AuthError, type AuthAdapter, type AuthNext } from "./types"

const app =
  getApps()[0] ??
  initializeApp({
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
  })
export const fb = getAuth(app)

/** Company email domain → the SSO provider id you created in step 5. */
const SSO_BY_DOMAIN: Record<string, string> = {
  // "globex.com": "saml.globex",
}

const MAGIC_EMAIL = "pulze-magic-email"

/** Next.js: gives the server a session cookie (step 6). Vite: leave it empty. */
async function syncSession() {}

/** Waiting second step after a password or social sign-in. */
let resolver: MultiFactorResolver | null = null
let smsVerificationId: string | null = null

/** Turns Firebase's error codes into the screens Pulze knows. */
function toAuthError(e: unknown): AuthError {
  if (!(e instanceof FirebaseError))
    return new AuthError("Something went wrong.", "unknown")
  switch (e.code) {
    case "auth/invalid-credential":
    case "auth/wrong-password":
    case "auth/user-not-found":
      return new AuthError("That email and password don't match.", "wrong-password")
    case "auth/email-already-in-use":
      return new AuthError("There's already an account with this email.", "email-taken")
    case "auth/invalid-verification-code":
      return new AuthError("That code isn't right.", "wrong-code")
    case "auth/too-many-requests":
      return new AuthError("Too many tries. Wait a few minutes.", "too-many-tries", 0)
    case "auth/expired-action-code":
    case "auth/invalid-action-code":
      return new AuthError("This link has expired.", "link-expired")
    case "auth/popup-closed-by-user":
      return new AuthError("The sign-in window was closed.", "unknown")
    default:
      return new AuthError(e.message, "unknown")
  }
}

/** After any first step: done, or the second step is needed. */
async function finish(
  run: () => Promise<UserCredential>,
  email: string
): Promise<AuthNext> {
  try {
    await run()
    await syncSession() // Next.js: step 6
    return { next: "done" }
  } catch (e) {
    if (e instanceof FirebaseError && e.code === "auth/multi-factor-auth-required") {
      resolver = getMultiFactorResolver(fb, e as MultiFactorError)
      setPendingEmail(email)
      return { next: "two-step", email }
    }
    throw toAuthError(e)
  }
}

const providers = {
  google: () => new GoogleAuthProvider(),
  github: () => new GithubAuthProvider(),
  apple: () => new OAuthProvider("apple.com"),
}

export const firebaseAuth: AuthAdapter = {
  async currentUser() {
    await fb.authStateReady()
    const u = fb.currentUser
    if (!u) return null
    return {
      id: u.uid,
      name: u.displayName ?? u.email ?? "",
      email: u.email ?? "",
      hue: 262,
    }
  },

  async signIn({ email, password, remember }) {
    await setPersistence(
      fb,
      remember ? browserLocalPersistence : browserSessionPersistence
    )
    return finish(() => signInWithEmailAndPassword(fb, email, password), email)
  },

  signInWithProvider(provider) {
    return finish(() => signInWithPopup(fb, providers[provider]()), "")
  },

  signInWithSso(email) {
    const id = SSO_BY_DOMAIN[email.split("@")[1] ?? ""]
    if (!id)
      throw new AuthError("Your company doesn't use single sign-on here.", "unknown")
    const p = id.startsWith("saml.") ? new SAMLAuthProvider(id) : new OAuthProvider(id)
    return finish(() => signInWithPopup(fb, p), email)
  },

  async sendMagicLink(email) {
    await sendSignInLinkToEmail(fb, email, {
      url: `${window.location.origin}/sign-in`,
      handleCodeInApp: true,
    })
    localStorage.setItem(MAGIC_EMAIL, email)
  },

  /** The magic link lands on /sign-in; this finishes it. */
  async completeSignIn(url) {
    if (!isSignInWithEmailLink(fb, url)) return null
    const email =
      localStorage.getItem(MAGIC_EMAIL) ??
      window.prompt("Which email did you use to sign in?") ??
      ""
    localStorage.removeItem(MAGIC_EMAIL)
    return finish(() => signInWithEmailLink(fb, email, url), email)
  },

  async signUp({ firstName, lastName, email, password }) {
    try {
      const { user } = await createUserWithEmailAndPassword(fb, email, password)
      await updateProfile(user, { displayName: `${firstName} ${lastName}` })
      await syncSession()
    } catch (e) {
      throw toAuthError(e)
    }
  },

  // Workspaces and invites live in your database: Firestore version in step 4.
  async createWorkspace() {},
  async inviteTeam() {},

  async sendPasswordReset(email) {
    try {
      await sendPasswordResetEmail(fb, email)
    } catch (e) {
      // Don't reveal whether an account exists.
      if (!(e instanceof FirebaseError && e.code === "auth/user-not-found"))
        throw toAuthError(e)
    }
  },

  async checkResetToken(token) {
    try {
      return { email: await verifyPasswordResetCode(fb, token) }
    } catch (e) {
      throw toAuthError(e)
    }
  },

  async resetPassword(token, password) {
    try {
      await confirmPasswordReset(fb, token, password)
    } catch (e) {
      throw toAuthError(e)
    }
  },

  async verifyCode(code) {
    if (!resolver) throw new AuthError("Sign in again.", "too-many-tries", 0)
    const assertion = smsVerificationId
      ? PhoneMultiFactorGenerator.assertion(
          PhoneAuthProvider.credential(smsVerificationId, code)
        )
      : TotpMultiFactorGenerator.assertionForSignIn(
          resolver.hints.find((h) => h.factorId === TotpMultiFactorGenerator.FACTOR_ID)!
            .uid,
          code
        )
    try {
      await resolver.resolveSignIn(assertion)
      resolver = null
      smsVerificationId = null
      setPendingEmail(null)
      await syncSession()
    } catch (e) {
      throw toAuthError(e)
    }
  },

  async verifyBackupCode() {
    throw new AuthError(
      `Backup codes aren't available. Contact ${siteConfig.support.email}.`,
      "unknown"
    )
  },

  async sendCodeBySms() {
    if (!resolver) throw new AuthError("Sign in again.", "too-many-tries", 0)
    const hint = resolver.hints.find(
      (h) => h.factorId === PhoneMultiFactorGenerator.FACTOR_ID
    )
    if (!hint)
      throw new AuthError("No phone number is set up for this account.", "unknown")
    const box = document.createElement("div")
    document.body.append(box)
    const recaptcha = new RecaptchaVerifier(fb, box, { size: "invisible" })
    smsVerificationId = await new PhoneAuthProvider(fb).verifyPhoneNumber(
      { multiFactorHint: hint, session: resolver.session },
      recaptcha
    )
    return (hint as { phoneNumber?: string }).phoneNumber ?? "your phone"
  },

  async unlock(password) {
    const u = fb.currentUser
    if (!u?.email) throw new AuthError("Sign in again.", "unknown")
    try {
      await reauthenticateWithCredential(
        u,
        EmailAuthProvider.credential(u.email, password)
      )
    } catch (e) {
      throw toAuthError(e)
    }
  },

  async unlockWithPasskey() {
    throw new AuthError("Use your password to unlock.", "unknown")
  },

  async signOut() {
    await signOut(fb)
    await fetch("/api/session", { method: "DELETE" }) // Next.js only
  },
}

Then switch Pulze to it in src/data/auth/index.ts:

import { firebaseAuth } from "./firebase"
export const auth: AuthAdapter = firebaseAuth

The lock screen only offers a passkey if you keep it in the page; to remove the button, delete the "Use passkey" block in auth/lock.tsx.

4. Workspaces and invites (Firestore)

Sign-up step 2 creates a workspace and step 3 sends invites. Firebase Auth doesn't store either, so save them in Firestore:

// firebase.ts: add the import and db at the top…
import { doc, getFirestore, serverTimestamp, setDoc, writeBatch } from "firebase/firestore"

const db = getFirestore(app)

// …and replace the two empty methods in firebaseAuth:
  async createWorkspace({ name, slug, size }) {
    const uid = fb.currentUser!.uid
    await setDoc(doc(db, "workspaces", slug), {
      name,
      size,
      ownerId: uid,
      members: { [uid]: "admin" },
      createdAt: serverTimestamp(),
    })
  },

  async inviteTeam(emails) {
    const batch = writeBatch(db)
    for (const email of emails)
      batch.set(doc(db, "invites", email), { email, invitedBy: fb.currentUser!.uid })
    await batch.commit()
  },

To email the invites, install the Trigger Email extension (Firebase console › Extensions) and write the invite to its mail collection, or send them from a Cloud Function that listens to invites.

Lock the collections down in your Firestore rules so people can only read workspaces they belong to.

5. Two-step and SSO (Identity Platform)

Both need the project upgraded to Identity Platform: Firebase console › Authentication › Settings › upgrade. It has a free tier.

Two-step with an authenticator app (TOTP):

  1. In Google Cloud console › Identity Platform › MFA, turn on Time-based one-time password.
  2. People enrol from your Settings › Security page. The enrolment code is in Firebase's TOTP guide.
  3. Sign-in now returns { next: "two-step" } for those people, and the two-step page calls verifyCode.

Two-step by text message: turn on SMS in the same MFA page. The "Text me a code instead" link calls sendCodeBySms, which needs reCAPTCHA (handled invisibly above).

SSO: in Identity Platform › Providers, add a SAML or OpenID Connect provider for each company. Its id looks like saml.globex or oidc.globex. Add the company's email domain and that id to SSO_BY_DOMAIN.

If you don't set these up, turn the matching options off: sso: false in siteConfig.auth, and people won't see two-step because Firebase never asks for it.

6. Next.js: tell the server who's signed in

Firebase signs people in inside the browser. The server (and the proxy.ts check from Authentication) needs a cookie. Firebase's Admin SDK turns the browser's ID token into a session cookie.

  1. In Firebase console › Project settings › Service accounts, click Generate new private key. Put its three values in .env.local (never commit this file):

    FIREBASE_PROJECT_ID=acme-app
    FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxx@acme-app.iam.gserviceaccount.com
    FIREBASE_PRIVATE_KEY="<the private_key value from the file, with its \n kept>"
    

    Copy private_key exactly as it appears in the downloaded JSON file, including the BEGIN and END lines and every \n, inside double quotes.

  2. Install the Admin SDK: pnpm add firebase-admin.

  3. Create lib/firebase-admin.ts:

    import "server-only"
    import { cert, getApps, initializeApp } from "firebase-admin/app"
    import { getAuth } from "firebase-admin/auth"
    
    const app =
      getApps()[0] ??
      initializeApp({
        credential: cert({
          projectId: process.env.FIREBASE_PROJECT_ID,
          clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
          privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, "\n"),
        }),
      })
    export const adminAuth = getAuth(app)
    
  4. Create app/api/session/route.ts:

    import { cookies } from "next/headers"
    import { adminAuth } from "@/lib/firebase-admin"
    
    const FIVE_DAYS = 5 * 24 * 60 * 60 * 1000
    
    export async function POST(request: Request) {
      const { idToken } = await request.json()
      const session = await adminAuth.createSessionCookie(idToken, {
        expiresIn: FIVE_DAYS,
      })
      ;(await cookies()).set("session", session, {
        maxAge: FIVE_DAYS / 1000,
        httpOnly: true,
        secure: true,
        sameSite: "lax",
        path: "/",
      })
      return Response.json({ ok: true })
    }
    
    export async function DELETE() {
      ;(await cookies()).delete("session")
      return Response.json({ ok: true })
    }
    
  5. Fill in syncSession in firebase.ts:

    async function syncSession() {
      const idToken = await fb.currentUser?.getIdToken()
      if (!idToken) return
      await fetch("/api/session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ idToken }),
      })
    }
    
  6. Add proxy.ts from Protect the app pages. The cookie is called session, as above.

  7. In route handlers and server actions that return private data, check the cookie for real:

    const cookie = (await cookies()).get("session")?.value
    const user = cookie ? await adminAuth.verifySessionCookie(cookie, true) : null
    if (!user) return new Response("Signed out", { status: 401 })
    

Vite: skip this step. Delete the syncSession() calls and the fetch in signOut, and protect routes with the guard in Authentication. Your API checks the ID token instead: send await fb.currentUser.getIdToken() as a Authorization: Bearer header and verify it with adminAuth.verifyIdToken.

7. Reset emails go to your page

By default Firebase's reset email opens a Firebase-hosted page. To use the Pulze page instead:

  1. Firebase console › Authentication › Templates › Password reset › edit (pencil) › Customize action URL.
  2. Enter https://app.acme.io/reset-password (your domain).

The email link now opens /reset-password?mode=resetPassword&oobCode=…. The Pulze page reads oobCode as the token, so nothing else changes.

The custom action URL is shared by every email action. If you also send "verify your email" emails, they'll arrive at /reset-password with mode=verifyEmail; handle that by calling applyActionCode(fb, oobCode) when mode isn't resetPassword, or keep Firebase's own page for those.

Also in Templates, set the sender name and edit the wording to match the email table.

8. Check it

  • Sign up with a new email, then find the person in Authentication › Users.
  • Sign out, sign in with the wrong password: "That email and password don't match."
  • Sign in with Google (and each provider you kept).
  • Forgot password: the email arrives and opens your /reset-password.
  • Magic link: the email opens /sign-in and you land on the dashboard.
  • Next.js: open a private window at /apps/kanban; you're sent to /sign-in?from=/apps/kanban, and after signing in you're back on Kanban.

Troubleshooting

You see Fix
auth/unauthorized-domain Add your domain under Authentication › Settings › Authorized domains.
auth/operation-not-allowed That sign-in method is off in the console.
Pop-up opens and closes at once The browser blocked it. Social buttons must call signInWithPopup straight from the click, which Pulze does; check extensions.
auth/invalid-api-key .env.local isn't loaded: restart pnpm dev, and check the NEXT_PUBLIC_ / VITE_ prefix.
Signed in, but proxy.ts still redirects The session cookie wasn't set: check /api/session in the browser's Network tab, and the FIREBASE_PRIVATE_KEY line breaks.
Magic link asks "Which email did you use?" The link was opened in another browser. That's expected; Firebase needs the email to finish.