Skip to content
Docs
Getting started
Layout

Layout

We can use the getTokens function from next-firebase-auth-edge to pull user information from request cookies.

Once we have the token details, we can map them to a User object and pass it to the AuthProvider we created in the previous step.

You can use getTokens in any React Server Component, whether it's page.tsx or layout.tsx.

Learn more about the Next.js App Router in the official docs (opens in a new tab).

Example RootLayout

Here’s an example of how to implement the RootLayout React Server Component. It uses the getTokens function to create a user object from cookies and passes it to the AuthProvider client component.

app/layout.tsx
import { filterStandardClaims } from "next-firebase-auth-edge/lib/auth/claims";
import { Tokens, getTokens } from "next-firebase-auth-edge";
import { cookies } from "next/headers";
import { User } from "./AuthContext";
import { AuthProvider } from "./AuthProvider";
 
const toUser = ({ decodedToken }: Tokens): User => {
  const {
    uid,
    email,
    picture: photoURL,
    email_verified: emailVerified,
    phone_number: phoneNumber,
    name: displayName,
    source_sign_in_provider: signInProvider,
  } = decodedToken;
 
  const customClaims = filterStandardClaims(decodedToken);
 
  return {
    uid,
    email: email ?? null,
    displayName: displayName ?? null,
    photoURL: photoURL ?? null,
    phoneNumber: phoneNumber ?? null,
    emailVerified: emailVerified ?? false,
    providerId: signInProvider,
    customClaims,
  };
};
 
export default async function RootLayout({
  children,
}: {
  children: JSX.Element
}) {
  // Since Next.js 15, `cookies` function returns a Promise, so we need to precede it with `await`.
  const tokens = await getTokens(await cookies(), {
    apiKey: 'XXxxXxXXXxXxxxxx_XxxxXxxxxxXxxxXXXxxXxX',
    cookieName: 'AuthToken',
    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'
    }
  });
  const user = tokens ? toUser(tokens) : null;
 
  return (
    <html lang="en">
      <head />
      <body>
        <main>
          <AuthProvider user={user}>{children}</AuthProvider>
        </main>
      </body>
    </html>
  );
}