{"id":16600,"library":"better-auth-firebase-auth","title":"Better Auth Firebase Authentication Plugin","description":"better-auth-firebase-auth is a specialized plugin designed to integrate Firebase Authentication seamlessly with the Better Auth library. Currently at version 2.0.5, it provides robust authentication capabilities, leveraging Firebase's built-in email services for password resets and verification, global infrastructure for high availability, and battle-tested security. The package maintains an active release cadence, frequently addressing security vulnerabilities and improving compatibility. It differentiates itself by simplifying the integration of Firebase's comprehensive authentication features, allowing developers to benefit from a multi-platform SDK and customizable email templates without the complexities of managing their own email infrastructure. This makes it particularly suitable for applications seeking a secure, performant, and feature-rich authentication solution with minimal setup effort, especially when existing Firebase projects are in use.","status":"active","version":"2.0.5","language":"javascript","source_language":"en","source_url":"https://github.com/yultyyev/better-auth-firebase-auth","tags":["javascript","better-auth","firebase","firebase-auth","authentication","authjs","nextauth","oauth","session","typescript"],"install":[{"cmd":"npm install better-auth-firebase-auth","lang":"bash","label":"npm"},{"cmd":"yarn add better-auth-firebase-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add better-auth-firebase-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core authentication library that this package extends and integrates with.","package":"better-auth","optional":false},{"reason":"Client-side Firebase SDK for browser-based authentication (e.g., Google Sign-in).","package":"firebase","optional":false},{"reason":"Server-side Firebase Admin SDK for backend authentication operations, token verification, and user management.","package":"firebase-admin","optional":false},{"reason":"Peer dependency for type checking and development, as the library ships with full TypeScript types.","package":"typescript","optional":true}],"imports":[{"note":"Use this path for client-side code (e.g., React components, browser bundles) to avoid bundling server-side dependencies like 'firebase-admin'.","wrong":"import { firebaseAuthClientPlugin } from 'better-auth-firebase-auth';","symbol":"firebaseAuthClientPlugin","correct":"import { firebaseAuthClientPlugin } from 'better-auth-firebase-auth/client';"},{"note":"Use this path for server-side code (e.g., API routes, server components) where 'firebase-admin' is available. The main export should be avoided to prevent bundling issues.","wrong":"import { firebaseAuthPlugin } from 'better-auth-firebase-auth';","symbol":"firebaseAuthPlugin","correct":"import { firebaseAuthPlugin } from 'better-auth-firebase-auth/server';"},{"note":"This function is provided by the peer dependency 'better-auth'. Since 'better-auth' v1.5+, the recommended import path is 'better-auth/api'. The plugin maintains backward compatibility but direct usage should use the preferred path.","wrong":"import { createAuthMiddleware } from 'better-auth/plugins';","symbol":"createAuthMiddleware","correct":"import { createAuthMiddleware } from 'better-auth/api';"}],"quickstart":{"code":"import { createAuthOptions, createAuthMiddleware } from \"better-auth/api\";\nimport { firebaseAuthPlugin } from \"better-auth-firebase-auth/server\";\nimport { initializeApp, getApps, cert } from 'firebase-admin/app';\nimport { getAuth } from 'firebase-admin/auth';\nimport type { NextApiRequest, NextApiResponse } from 'next'; // Example for Next.js\n\n// Initialize Firebase Admin SDK (ensure FIREBASE_SERVICE_ACCOUNT_KEY is a parsed JSON string)\nif (!getApps().length) {\n  try {\n    const serviceAccountKey = process.env.FIREBASE_SERVICE_ACCOUNT_KEY;\n    if (!serviceAccountKey) {\n      throw new Error('FIREBASE_SERVICE_ACCOUNT_KEY environment variable is not set.');\n    }\n    initializeApp({\n      credential: cert(JSON.parse(serviceAccountKey)),\n    });\n  } catch (error) {\n    console.error(\"Failed to initialize Firebase Admin SDK:\", error);\n    // In production, you might want to throw or exit if core services fail\n  }\n}\nconst firebaseAdminAuth = getAuth();\n\n// Define Better Auth options with the Firebase plugin\nconst authOptions = createAuthOptions({\n  secret: process.env.AUTH_SECRET ?? 'your-super-secret-fallback-key', // Set a strong secret in production env\n  plugins: [\n    firebaseAuthPlugin({\n      firebaseAdminAuth,\n      // Optional: Specify providers for Firebase Auth, e.g., Google, Email/Password\n      providers: ['google', 'email'],\n      // Optional: Customize session cookie options, callbacks, etc.\n      sessionCookieName: '__session',\n      cookieOptions: {\n        secure: process.env.NODE_ENV === 'production',\n      },\n    }),\n  ],\n  // Optional: Add an adapter for database persistence if needed (e.g., for user profiles)\n  // adapter: YourDatabaseAdapter(),\n});\n\n// Create the Better Auth middleware handler\nconst handler = createAuthMiddleware(authOptions);\n\n// Example: Export the API route handler for a framework like Next.js\nexport default async function betterAuthHandler(req: NextApiRequest, res: NextApiResponse) {\n  await handler(req, res);\n}\n\n/*\n// For client-side integration in your frontend application (e.g., in _app.tsx or a layout component):\n// import { AuthProvider } from 'better-auth/client';\n// import { firebaseAuthClientPlugin } from 'better-auth-firebase-auth/client';\n// import { initializeApp } from 'firebase/app';\n// import { getAuth } from 'firebase/auth';\n//\n// const firebaseClientConfig = {\n//   apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY ?? '',\n//   authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN ?? '',\n//   projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID ?? '',\n//   // ... other client-side firebase config from your project settings\n// };\n//\n// const firebaseClientApp = initializeApp(firebaseClientConfig);\n// const firebaseClientAuth = getAuth(firebaseClientApp);\n//\n// function MyRootAppComponent({ children }) {\n//   return (\n//     <AuthProvider plugins={[firebaseAuthClientPlugin({ firebaseClientAuth })]}>\n//       {children}\n//     </AuthProvider>\n//   );\n// }\n*/","lang":"typescript","description":"This quickstart demonstrates the server-side setup of `better-auth-firebase-auth` within a Better Auth middleware, including Firebase Admin SDK initialization and plugin configuration. It also provides commented guidance for client-side integration."},"warnings":[{"fix":"Update `package.json` by running `npm uninstall @yultyyev/better-auth-firebase-auth && npm install better-auth-firebase-auth`. Then, globally replace `@yultyyev/better-auth-firebase-auth` with `better-auth-firebase-auth` in your import statements.","message":"The package name changed in v2.0.0 from `@yultyyev/better-auth-firebase-auth` to `better-auth-firebase-auth`. This requires updating your `package.json` dependencies and all import statements throughout your codebase.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always use `import { firebaseAuthClientPlugin } from 'better-auth-firebase-auth/client';` for browser-side code and `import { firebaseAuthPlugin } from 'better-auth-firebase-auth/server';` for server-side code. Avoid the main export `better-auth-firebase-auth` if your bundler isn't configured for environment-specific code splitting.","message":"Importing server-side modules (like `firebase-admin` or `firebaseAuthPlugin` from the main export) into client-side code will cause bundling errors or runtime failures due to Node.js-specific dependencies.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For your own `better-auth` code, ensure you import `createAuthMiddleware` from `better-auth/api`. Update your `better-auth` peer dependency to `>=1.5.0` to leverage the latest features and import paths.","message":"The `better-auth` library updated its `createAuthMiddleware` import path in v1.5.0. While this plugin attempts to maintain backward compatibility, direct usage of `better-auth` features should be aware of this change.","severity":"gotcha","affected_versions":">=1.5.0"},{"fix":"Upgrade your Node.js environment to version 22 or higher. Verify your `engines` field in `package.json` to ensure compatibility.","message":"This package requires Node.js version `>=22`. Running on older Node.js environments will result in errors.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Ensure `initializeApp` from `firebase-admin/app` is called only once in your server-side entry point, guarded by `!getApps().length`. Verify that `process.env.FIREBASE_SERVICE_ACCOUNT_KEY` is correctly set, parsed as valid JSON, and contains the correct service account credentials for your Firebase project.","message":"Improper initialization of the Firebase Admin SDK (e.g., initializing multiple times, providing invalid credentials, or missing `FIREBASE_SERVICE_ACCOUNT_KEY`) will lead to runtime errors or authentication failures.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"For client-side code, use `import { firebaseAuthClientPlugin } from 'better-auth-firebase-auth/client';`. Ensure `firebaseAuthPlugin` is strictly used in server environments only.","cause":"Attempting to import `firebaseAuthPlugin` or `firebase-admin` directly into client-side (browser) code.","error":"ModuleNotFoundError: Module not found: Error: Can't resolve 'firebase-admin' in '...'"},{"fix":"Ensure your `better-auth` dependency is at least `1.5.0` and that you are importing `createAuthMiddleware` from `better-auth/api`.","cause":"Mismatch between the `better-auth` package version and the expected import path for `createAuthMiddleware`.","error":"TypeError: (0 , better_auth_api__WEBPACK_IMPORTED_MODULE_0__.createAuthMiddleware) is not a function"},{"fix":"Verify that your `FIREBASE_SERVICE_ACCOUNT_KEY` environment variable contains a valid JSON string of your Firebase service account credentials. Ensure it's correctly loaded and parsed when `firebase-admin` is initialized on the server.","cause":"The Firebase Admin SDK was initialized with an invalid, missing, or malformed service account key.","error":"FirebaseError: Firebase: Error (auth/invalid-credential)."}],"ecosystem":"npm"}