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.

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 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)
  });
 
  //...
}