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'
},
tenantId: 'your-tenant-id'
});
if (!tokens) {
return notFound();
}
const {token, decodedToken, customToken, metadata} = 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}
<br />
Metadata:
<pre>
{JSON.stringify(metadata, undefined, 2)}
</pre>
</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 |
---|---|
tenantId | Optional string . Specify this if your project supports multi-tenancy (opens in a new tab). |
Metadata
getTokens
can return metadata
property, which is a custom data that can be saved within the cookies using getMetadata
property passed to Authentication Middleware.
getMetadata
is called when user logs in or the credential are refreshed. The resulting object is then saved within user cookies.