Skip to content
Docs
Usage guide
Server Components

Usage in Server Components

The library provides getTokens function to extract and validate user credentials. The function can be used only in Server Components or API Route Handlers. It returns null if there are no authentication cookies or the credentials have expired. If request contains valid user credentials, the function returns an object with token and decodedToken properties. token is jwt-encoded string, whereas decodedToken is an object representing decoded token.

getTokens

Example usage of getTokens function from next-firebase-auth-edge:

import { getTokens } from "next-firebase-auth-edge";
import { cookies } from "next/headers";
 
export default async function ServerComponentExample() {
  const tokens = await getTokens(cookies(), {
    apiKey: 'XXxxXxXXXxXxxxxx_XxxxXxxxxxXxxxXXXxxXxX',
    cookieName: 'AuthToken',
    cookieSignatureKeys: ['secret1', 'secret2'],
    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'
    }
  });
 
  return (
    <div style={{wordBreak: "break-word", width: "600px"}}>
      {tokens && (
        <p>
            Valid token: <span>{tokens.token}</span><br/>
            <pre>{JSON.stringify(tokens.decodedToken, undefined, 2)}</pre>
        </p>
      ) || <p>No valid user credentials</p>}
    </div>
  );
}

Required options

NameDescription
apiKeyRequiredFirebase Web API Key retrieved from Firebase Project settings overview page. Please note that this API Key will be visible only after you enable Firebase Authentication in your Firebase project
serviceAccountOptional in authenticated Google Cloud Run (opens in a new tab) environment. Otherwise requiredFirebase Service Account credentials
cookieNameRequiredThe name for cookie set by loginPath api route.
cookieSignatureKeysRequiredRotating keys (opens in a new tab) the cookie is validated against