Firebase API Key Domain Restriction
In a production-ready application, it's important to restrict your Firebase API key by domain for security purposes.
You can update your API key restrictions in the Google Cloud Console (opens in a new tab).
Enable Referer Validation
To support API key domain restrictions, you need to inform Google APIs about the referer of your requests. To do this, follow these steps for each operation:
- Ensure you pass the
headers
option with eachgetTokens
call. The library will extract the referer from the headers and use it when verifying tokens with Google APIs.
import {getTokens} from 'next-firebase-auth-edge';
import {cookies, headers} from 'next/headers';
export default async function ServerComponentExample() {
// Since Next.js 15, `cookies` and `headers` functions returns a Promise, so we need to precede them with `await`.
const tokens = await getTokens(await cookies(), {
// ...other options
headers: await headers()
});
return <div>{/* ... */}</div>;
}
See the getTokens options section for more details.
-
If you're using the deprecated
getTokensFromObject
method, switch togetApiRequestTokens
instead. Refer to the getApiRequestTokens documentation for more information. -
If you are using any of the advanced methods like
getCustomIdAndRefreshTokens
,verifyIdToken
,handleTokenRefresh
, orverifyAndRefreshExpiredIdToken
from the advanced usage section, make sure to pass thereferer
option. Thereferer
should be the authorized domain, derived from the request headers. You can use thegetReferer
function (imported fromnext-firebase-auth-edge/lib/next/utils
) to extract the referer from the headers ofNextRequest
.
import {getFirebaseAuth} from 'next-firebase-auth-edge/lib/auth';
import {getReferer} from 'next-firebase-auth-edge/lib/next/utils';
import type {NextRequest} from 'next/server';
const {verifyIdToken} = getFirebaseAuth(/*{...}*/);
export async function POST(request: NextRequest) {
const token = request.headers.get('Authorization')?.split(' ')[1] ?? '';
if (!token) {
throw new Error('Unauthenticated');
}
await verifyIdToken(token, {
referer: getReferer(request.headers)
});
//...
}