Skip to content
Docs
Usage guide
Usage in Firebase Hosting

Usage in Firebase Hosting Environment

By default, the Firebase Hosting environment strips all cookies except for __session. (See this StackOverflow thread (opens in a new tab) for more details.)

To use next-firebase-auth-edge in Firebase Hosting, you need to set a custom cookieName with the value __session, as shown in the examples below:

middleware.ts
import { NextRequest, NextResponse } from "next/server";
import { authMiddleware } from "next-firebase-auth-edge";
 
export async function middleware(request: NextRequest) {
  return authMiddleware(request, {
    cookieName: "__session", // This needs to be "__session" to work inside Firebase Hosting
 
    loginPath: "/api/login",
    logoutPath: "/api/logout",
    apiKey: "XXxxXxXXXxXxxxxx_XxxxXxxxxxXxxxXXXxxXxX",
    cookieSignatureKeys: ["Key-Should-Be-at-least-32-bytes-in-length"],
    cookieSerializeOptions: {
      path: "/",
      httpOnly: true,
      secure: false,
      sameSite: "lax" as const,
      maxAge: 12 * 60 * 60 * 24,
    },
    serviceAccount: {
      projectId: "your-firebase-project-id",
      clientEmail: "firebase-adminsdk-nnw48@your-firebase-project-id.iam.gserviceaccount.com",
      privateKey: "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
    },
  });
}
 
export const config = {
  matcher: ["/api/login", "/api/logout", "/", "/((?!_next|favicon.ico|api|.*\\.).*)"],
};

Example getTokens usage:

import { getTokens } from "next-firebase-auth-edge";
 
const tokens = await getTokens(context.req.cookies, {
  apiKey: 'XXxxXxXXXxXxxxxx_XxxxXxxxxxXxxxXXXxxXxX',
  cookieName: '__session',
  cookieSignatureKeys: ['Key-Should-Be-at-least-32-bytes-in-length'],
  serviceAccount: {
    projectId: "your-firebase-project-id",
    clientEmail: "firebase-adminsdk-nnw48@your-firebase-project-id.iam.gserviceaccount.com",
    privateKey: "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
  },
});