Usage in Server Components
The library provides a getTokens
function to extract and validate user credentials. This function can only be used in Server Components
or API Route Handlers. It returns null
if there are no authentication cookies or if the credentials have expired. If the request contains valid credentials, the function returns an object with token
, decodedToken
. The object can contain customToken
, if you passed enableCustomToken
flag to authMiddleware
. The token
is a JWT-encoded string, while decodedToken
is the decoded object representation of that token.
getTokens
Here’s an example of how to use the getTokens
function from next-firebase-auth-edge
:
import {getTokens} from 'next-firebase-auth-edge';
import {cookies, headers} from 'next/headers';
import {notFound} from 'next/navigation';
export default async function ServerComponentExample() {
// 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'
},
// Optional
headers: headers(),
tenantId: 'your-tenant-id'
});
if (!tokens) {
return notFound();
}
const {token, decodedToken, customToken} = tokens;
return (
<div style={{wordBreak: 'break-word', width: '600px'}}>
<p>
Valid token: {token}
<br />
User email: {decodedToken.email}
<br />
Custom token, if you enabled custom token support by passing `enableCustomToken` flag to `authMiddleware`: {customToken}
</p>
</div>
);
}
Required Options
Name | Description |
---|---|
apiKey | Required. The Firebase Web API Key, which you can find on the Firebase Project settings overview page. Keep in mind, this API key will only be visible once you enable Firebase Authentication. |
serviceAccount | Optional in authenticated Google Cloud Run (opens in a new tab) environments. Otherwise, required. This refers to the Firebase Service Account credentials. |
cookieName | Required. The name of the cookie set by the loginPath API route. |
cookieSignatureKeys | Required. These are rotating keys (opens in a new tab) used to validate the cookie. |
Optional Options
Name | Description |
---|---|
headers | Optional. The request Headers . These are used to pass the referer between the request and Google APIs. You can get Headers by calling the headers function from next/headers in Server Components. In Edge and Node.js environments, use NextRequest.headers instead. |
tenantId | Optional string . Specify this if your project supports multi-tenancy (opens in a new tab). |