Firebase Auth for Cloudflare Workers

2.0.6 · active · verified Wed Apr 22

firebase-auth-cloudflare-workers is a specialized, zero-dependency library designed to facilitate Firebase ID token (JWT) verification directly within Cloudflare Workers environments. Currently stable at version 2.0.6, it provides a robust solution for authenticating users by leveraging Web Standard APIs, ensuring minimal bundle size and optimized performance at the edge. Key differentiators include its complete independence from external npm dependencies, full support for UTF-8 character encoding, and dedicated integration with the Firebase Auth Emulator for local development and testing. The library enables developers to offload authentication logic to the Cloudflare edge, reducing latency and reliance on origin servers for token validation. While a specific release cadence isn't published, updates typically align with evolving Firebase authentication standards or Cloudflare Workers platform features.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to set up a Cloudflare Worker using the module syntax to verify a Firebase ID token, including KV store initialization for caching public JWKs and basic error handling. This is a complete, runnable example for a worker.

import type { EmulatorEnv } from "firebase-auth-cloudflare-workers";
import { Auth, WorkersKVStoreSingle } from "firebase-auth-cloudflare-workers";

interface Bindings extends EmulatorEnv {
  PROJECT_ID: string;
  PUBLIC_JWK_CACHE_KEY: string;
  PUBLIC_JWK_CACHE_KV: KVNamespace;
  FIREBASE_AUTH_EMULATOR_HOST?: string; // Made optional as it's for emulator
}

const verifyJWT = async (req: Request, env: Bindings): Promise<Response> => {
  const authorization = req.headers.get('Authorization');
  if (authorization === null) {
    return new Response(JSON.stringify({ error: 'Authorization header missing' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' }
    });
  }
  const jwt = authorization.replace(/Bearer\s+/i, "");

  // Auth is designed as a singleton for Workers
  const auth = Auth.getOrInitialize(
    env.PROJECT_ID,
    WorkersKVStoreSingle.getOrInitialize(env.PUBLIC_JWK_CACHE_KEY, env.PUBLIC_JWK_CACHE_KV)
  );

  try {
    const firebaseToken = await auth.verifyIdToken(jwt, false, env);
    return new Response(JSON.stringify(firebaseToken), {
      headers: {
        "Content-Type": "application/json"
      }
    });
  } catch (error: any) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 401,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

export default {
  async fetch(request: Request, env: Bindings, ctx: ExecutionContext): Promise<Response> {
    return await verifyJWT(request, env);
  }
};

// To run, ensure wrangler.toml is configured:
// name = "firebase-auth-example"
// compatibility_date = "2022-07-05"
// 
// [vars]
// PROJECT_ID = "your-firebase-project-id"
// PUBLIC_JWK_CACHE_KEY = "public-jwk-cache-key"
// FIREBASE_AUTH_EMULATOR_HOST = "127.0.0.1:9099" # Only if using emulator
// 
// [[kv_namespaces]]
// binding = "PUBLIC_JWK_CACHE_KV"
// id = "<YOUR_KV_NAMESPACE_ID>"
// preview_id = "<YOUR_KV_NAMESPACE_PREVIEW_ID>"
// 
// You can install with: `npm i firebase-auth-cloudflare-workers`

view raw JSON →