{"id":16718,"library":"cloudfire-auth","title":"Firebase Auth for Cloudflare Workers","description":"Cloudfire Auth is a JavaScript/TypeScript library designed to integrate Firebase Authentication functionalities directly within Cloudflare Workers environments. Currently at version 0.4.0, it provides core features such as Firebase ID token verification, user retrieval, and user deletion. The library leverages native Cloudflare APIs, specifically Cloudflare KV, for efficient OAuth2 token caching, which is crucial for performance and cost-effectiveness in a serverless context. It is built with a strong emphasis on modern JavaScript, being ESM-only, and offers full TypeScript support, making it suitable for contemporary development workflows. Key differentiators include its tight integration with Cloudflare's ecosystem, minimal external dependencies (only 'jose' for JWT handling), and its focus on solving the specific challenge of running Firebase Auth in a Worker environment where the official Firebase Admin SDK is not directly compatible due to Node.js-specific dependencies.","status":"active","version":"0.4.0","language":"javascript","source_language":"en","source_url":"https://github.com/Connor56/cloudfire-auth","tags":["javascript","firebase","auth","cloudflare","workers","authentication","jwt","firebase-auth","typescript"],"install":[{"cmd":"npm install cloudfire-auth","lang":"bash","label":"npm"},{"cmd":"yarn add cloudfire-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add cloudfire-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for secure JSON Web Token (JWT) handling and verification.","package":"jose","optional":false}],"imports":[{"note":"The library is ESM-only and does not support CommonJS `require()` syntax. Use ES module imports.","wrong":"const CloudFireAuth = require('cloudfire-auth');","symbol":"CloudFireAuth","correct":"import { CloudFireAuth } from 'cloudfire-auth';"},{"note":"Import the `ServiceAccountKey` type explicitly for type-checking, especially when defining your service account object.","symbol":"ServiceAccountKey","correct":"import type { ServiceAccountKey } from 'cloudfire-auth/types';"},{"note":"While `KVNamespace` is a global type in Cloudflare Workers, it's often passed to the constructor. Ensure it's correctly typed and available in your Worker's `env` object.","symbol":"KVNamespace","correct":"declare const env: { YOUR_KV_NAMESPACE?: KVNamespace }; // In Workers environment\nconst auth = new CloudFireAuth(serviceAccountKey, env.YOUR_KV_NAMESPACE);"}],"quickstart":{"code":"import { CloudFireAuth } from \"cloudfire-auth\";\n\ninterface Env {\n  YOUR_KV_NAMESPACE?: KVNamespace;\n  FIREBASE_PRIVATE_KEY: string;\n  FIREBASE_CLIENT_EMAIL: string;\n  // ... other service account fields as environment variables\n}\n\nexport default {\n  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {\n    // It is best practice to store your service account key separately and\n    // load it from a secure source, e.g., environment variables.\n    const serviceAccountKey = {\n      private_key: env.FIREBASE_PRIVATE_KEY.replace(/\\\\n/g, '\\n'), // Handle newline characters if from env\n      client_email: env.FIREBASE_CLIENT_EMAIL,\n      // Add other necessary fields from your Firebase service account key\n      // For example, project_id, type, private_key_id, etc.\n      // Ensure the structure matches ServiceAccountKey type.\n    };\n\n    // Initialize with your Firebase project credentials\n    const auth = new CloudFireAuth(\n      serviceAccountKey,\n      env.YOUR_KV_NAMESPACE // Optional: KV namespace for token caching\n    );\n\n    const idToken = request.headers.get('Authorization')?.split('Bearer ')[1];\n\n    if (!idToken) {\n      return new Response('No ID token provided', { status: 401 });\n    }\n\n    // Verify an ID token\n    try {\n      const decodedToken = await auth.verifyIdToken(idToken);\n      console.log(\"User ID:\", decodedToken.uid);\n      return new Response(`Verified user: ${decodedToken.uid}`, { status: 200 });\n    } catch (error: any) {\n      console.error(\"Token verification failed:\", error.message);\n      return new Response(`Token verification failed: ${error.message}`, { status: 401 });\n    }\n  },\n};","lang":"typescript","description":"This quickstart demonstrates how to initialize `CloudFireAuth` in a Cloudflare Worker, load service account credentials from environment variables, and verify a Firebase ID token from an incoming request's Authorization header."},"warnings":[{"fix":"Always use ES module import syntax: `import { CloudFireAuth } from 'cloudfire-auth';`","message":"Cloudfire Auth is ESM-only. Attempting to import it using CommonJS `require()` will result in a runtime error.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Review the API reference carefully before integrating to ensure the required functionality is available. If a method is missing, you may need to implement it manually using the Firebase REST API or contribute to the library.","message":"Not all Firebase Admin SDK methods are currently implemented. Several authentication and user management methods are marked with '❌' in the API reference (e.g., `verifySessionCookie`, `createCustomToken`, `createUser`, `getUserByEmail`, `deleteUsers`).","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Ensure the `private_key` string in your `serviceAccountKey` object has actual newline characters '\\n', not escaped '\\\\n'. When loading from `.env` or similar, explicit replacement might be needed.","message":"The `serviceAccountKey` must be correctly formatted. When loading from environment variables, private keys with newline characters (e.g., `-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----`) must have these newlines preserved or correctly replaced (e.g., using `.replace(/\\\\n/g, '\\n')`).","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"This specific library is designed for Cloudflare Workers. Ensure you are importing correctly (`import`) and that your build process for the Worker handles ESM correctly. This error can also indicate a misconfigured dependency attempting to use Node.js crypto, but `cloudfire-auth` aims to avoid this by using `jose` which is universal.","cause":"Attempting to use `cloudfire-auth` in a Node.js-incompatible environment (like Cloudflare Workers) while a dependency tries to `require` Node.js built-ins, or if the library itself is incorrectly bundled.","error":"Error: Dynamic require of \"crypto\" is not supported"},{"fix":"Ensure your Cloudflare Worker environment and local development setup are configured for ES Modules. If using `npm install` and bundling, verify your bundler (e.g., Webpack, Rollup, esbuild) correctly handles `module` and `exports` fields in `package.json` for ESM.","cause":"Trying to run ESM-only code in an environment that only supports CommonJS, or a build tool is misconfigured for ESM.","error":"SyntaxError: Unexpected token 'export'"},{"fix":"Instruct the client application to refresh the ID token and send the newly obtained token. Firebase client SDKs automatically handle token refreshing; ensure the client-side logic correctly retrieves and sends fresh tokens.","cause":"The Firebase ID token provided to `verifyIdToken` has exceeded its validity period (typically 1 hour).","error":"Error: Id token is expired. Get a fresh one from your client app and try again."},{"fix":"If you intend to use KV caching, ensure `env.YOUR_KV_NAMESPACE` (or whatever your KV binding is named) is correctly passed as the second argument to `new CloudFireAuth()`. If not using KV, ensure the constructor is called without the second argument, or explicitly with `undefined`.","cause":"The `KVNamespace` object was not provided to the `CloudFireAuth` constructor when it was expected, or `env` is not correctly passed/typed in your Worker handler.","error":"TypeError: Cannot read properties of undefined (reading 'YOUR_KV_NAMESPACE')"}],"ecosystem":"npm"}