{"id":16623,"library":"firebase-auth-cloudflare-workers","title":"Firebase Auth for Cloudflare Workers","description":"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.","status":"active","version":"2.0.6","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","web","app","jwt","firebase","cloudflare","workers","typescript"],"install":[{"cmd":"npm install firebase-auth-cloudflare-workers","lang":"bash","label":"npm"},{"cmd":"yarn add firebase-auth-cloudflare-workers","lang":"bash","label":"yarn"},{"cmd":"pnpm add firebase-auth-cloudflare-workers","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library is designed for ESM in Cloudflare Workers environments. Use named import.","wrong":"const Auth = require('firebase-auth-cloudflare-workers').Auth","symbol":"Auth","correct":"import { Auth } from 'firebase-auth-cloudflare-workers'"},{"note":"This specific implementation uses Cloudflare KV for caching public JWKs. Ensure it's correctly imported.","wrong":"import { KVStore } from 'firebase-auth-cloudflare-workers'","symbol":"WorkersKVStoreSingle","correct":"import { WorkersKVStoreSingle } from 'firebase-auth-cloudflare-workers'"},{"note":"EmulatorEnv is a type definition. Import it using 'import type' to avoid bundling issues.","wrong":"import { EmulatorEnv } from 'firebase-auth-cloudflare-workers'","symbol":"EmulatorEnv","correct":"import type { EmulatorEnv } from 'firebase-auth-cloudflare-workers'"}],"quickstart":{"code":"import type { EmulatorEnv } from \"firebase-auth-cloudflare-workers\";\nimport { Auth, WorkersKVStoreSingle } from \"firebase-auth-cloudflare-workers\";\n\ninterface Bindings extends EmulatorEnv {\n  PROJECT_ID: string;\n  PUBLIC_JWK_CACHE_KEY: string;\n  PUBLIC_JWK_CACHE_KV: KVNamespace;\n  FIREBASE_AUTH_EMULATOR_HOST?: string; // Made optional as it's for emulator\n}\n\nconst verifyJWT = async (req: Request, env: Bindings): Promise<Response> => {\n  const authorization = req.headers.get('Authorization');\n  if (authorization === null) {\n    return new Response(JSON.stringify({ error: 'Authorization header missing' }), {\n      status: 400,\n      headers: { 'Content-Type': 'application/json' }\n    });\n  }\n  const jwt = authorization.replace(/Bearer\\s+/i, \"\");\n\n  // Auth is designed as a singleton for Workers\n  const auth = Auth.getOrInitialize(\n    env.PROJECT_ID,\n    WorkersKVStoreSingle.getOrInitialize(env.PUBLIC_JWK_CACHE_KEY, env.PUBLIC_JWK_CACHE_KV)\n  );\n\n  try {\n    const firebaseToken = await auth.verifyIdToken(jwt, false, env);\n    return new Response(JSON.stringify(firebaseToken), {\n      headers: {\n        \"Content-Type\": \"application/json\"\n      }\n    });\n  } catch (error: any) {\n    return new Response(JSON.stringify({ error: error.message }), {\n      status: 401,\n      headers: { 'Content-Type': 'application/json' }\n    });\n  }\n};\n\nexport default {\n  async fetch(request: Request, env: Bindings, ctx: ExecutionContext): Promise<Response> {\n    return await verifyJWT(request, env);\n  }\n};\n\n// To run, ensure wrangler.toml is configured:\n// name = \"firebase-auth-example\"\n// compatibility_date = \"2022-07-05\"\n// \n// [vars]\n// PROJECT_ID = \"your-firebase-project-id\"\n// PUBLIC_JWK_CACHE_KEY = \"public-jwk-cache-key\"\n// FIREBASE_AUTH_EMULATOR_HOST = \"127.0.0.1:9099\" # Only if using emulator\n// \n// [[kv_namespaces]]\n// binding = \"PUBLIC_JWK_CACHE_KV\"\n// id = \"<YOUR_KV_NAMESPACE_ID>\"\n// preview_id = \"<YOUR_KV_NAMESPACE_PREVIEW_ID>\"\n// \n// You can install with: `npm i firebase-auth-cloudflare-workers`","lang":"typescript","description":"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."},"warnings":[{"fix":"Always use `Auth.getOrInitialize` to retrieve the Auth instance, passing the necessary environment variables for consistent behavior across requests.","message":"The `Auth.getOrInitialize` method is designed as a singleton. Repeated calls with the same `projectId` and `keyStore` will return the same `Auth` instance. This behavior is crucial for managing resources efficiently in a Cloudflare Worker's stateless execution model.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For enhanced security, call `authObj.verifyIdToken(idToken, true, env)` to ensure revocation status is checked. Be aware this incurs an additional network request to Firebase Auth backend.","message":"By default, `authObj.verifyIdToken` does NOT check if the Firebase session cookie (or ID token) has been revoked. This could allow access with a revoked token. To enable revocation checks, you must explicitly pass `true` as the second argument.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure `FIREBASE_AUTH_EMULATOR_HOST` is correctly configured in your Worker's `Bindings` interface and `wrangler.toml`, and always pass the `env` object to `authObj.verifyIdToken` when developing with the emulator.","message":"When using the Firebase Auth Emulator, the `env` parameter in `verifyIdToken` is critical for detecting the emulator host. Forgetting to pass `env` (or not configuring `FIREBASE_AUTH_EMULATOR_HOST` in `Bindings` and `wrangler.toml`) will cause token verification to attempt to reach production Firebase services, even if you intend to use the emulator.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refer to the official documentation for specific migration guides if upgrading from major version 1.x. Ensure `import { Auth } from 'firebase-auth-cloudflare-workers';` and associated types are correct.","message":"Versions prior to 2.x might have differing initialization patterns or require slightly different type definitions. Upgrading from 1.x to 2.x may require minor adjustments to import paths or method signatures.","severity":"breaking","affected_versions":"<2.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Verify that `env.PROJECT_ID` in your Worker's `Bindings` and `wrangler.toml` exactly matches your Firebase project ID (e.g., `example-project12345`). This ID is part of the token's claims.","cause":"The Firebase project ID extracted from the ID token does not match the `projectId` configured for the `Auth` instance in your Cloudflare Worker.","error":"Error: Firebase ID token has incorrect 'aud' (audience) claim."},{"fix":"Ensure the client application is refreshing Firebase ID tokens regularly before they expire. The client-side Firebase SDK handles this automatically, but custom implementations might need explicit refresh logic.","cause":"The JWT presented in the Authorization header has passed its expiration time.","error":"Error: Firebase ID token has expired. Get a fresh token from your client app and try again."},{"fix":"Add the `[[kv_namespaces]]` entry to your `wrangler.toml` and ensure `binding = \"PUBLIC_JWK_CACHE_KV\"` matches the name used in your code, along with a valid `id` for your KV namespace.","cause":"The `PUBLIC_JWK_CACHE_KV` binding, which is an instance of `KVNamespace`, was not properly declared and bound in your `wrangler.toml` file or passed correctly in the Worker's `Bindings`.","error":"ReferenceError: KVNamespace is not defined"},{"fix":"Check the `PUBLIC_JWK_CACHE_KEY` and `PUBLIC_JWK_CACHE_KV` configurations. Ensure the KV store is accessible and correctly storing / retrieving the public JSON Web Keys (JWKs). Clear the KV cache if keys might be stale.","cause":"The ID token's signature cannot be verified using the public keys obtained from Firebase, possibly due to a malformed token, incorrect public key caching, or an issue with the signing keys.","error":"Error: Firebase ID token has invalid signature."}],"ecosystem":"npm"}