Skip to content
Docs
Usage guide
Firebase API Key domain restriction

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:

  1. Ensure you pass the headers option with each getTokens 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() {
  const tokens = await getTokens(cookies(), {
    // ...other options
    headers: headers()
  });
 
  return <div>{/* ... */}</div>;
}

See the getTokens options section for more details.

  1. If you're using the deprecated getTokensFromObject method, switch to getApiRequestTokens instead. Refer to the getApiRequestTokens documentation for more information.

  2. If you are using any of the advanced methods like getCustomIdAndRefreshTokens, verifyIdToken, handleTokenRefresh, or verifyAndRefreshExpiredIdToken from the advanced usage section, make sure to pass the referer option. The referer should be the authorized domain, derived from the request headers. You can use the getReferer function (imported from next-firebase-auth-edge/lib/next/utils) to extract the referer from the headers of NextRequest.

import {getFirebaseAuth} from 'next-firebase-auth-edge/lib/auth';
import {getReferer} from 'next-firebase-auth-edge/lib/next/utils';
import {getTokens} from 'next-firebase-auth-edge/lib/next/tokens';
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)
  });
 
  //...
}