Pages Router API Routes
To support gradual adoption of the latest Next.js features, next-firebase-auth-edge
offers the getApiRequestTokens
function. This function is designed to work with getServerSideProps and API Routes (opens in a new tab).
The getApiRequestTokens
function works similarly to getTokens
, but it's specifically for extracting cookie information from the req
object.
import { NextApiRequest, NextApiResponse } from "next";
import { getApiRequestTokens } from "next-firebase-auth-edge";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const tokens = await getApiRequestTokens(req, {
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'
}
});
if (!tokens) {
throw new Error('Unauthenticated');
}
return res.status(200).json({ tokens });
}