Better Auth Firebase Authentication Plugin
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.
Common errors
-
ModuleNotFoundError: Module not found: Error: Can't resolve 'firebase-admin' in '...'
cause Attempting to import `firebaseAuthPlugin` or `firebase-admin` directly into client-side (browser) code.fixFor client-side code, use `import { firebaseAuthClientPlugin } from 'better-auth-firebase-auth/client';`. Ensure `firebaseAuthPlugin` is strictly used in server environments only. -
TypeError: (0 , better_auth_api__WEBPACK_IMPORTED_MODULE_0__.createAuthMiddleware) is not a function
cause Mismatch between the `better-auth` package version and the expected import path for `createAuthMiddleware`.fixEnsure your `better-auth` dependency is at least `1.5.0` and that you are importing `createAuthMiddleware` from `better-auth/api`. -
FirebaseError: Firebase: Error (auth/invalid-credential).
cause The Firebase Admin SDK was initialized with an invalid, missing, or malformed service account key.fixVerify 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.
Warnings
- breaking 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.
- gotcha 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.
- gotcha 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.
- breaking This package requires Node.js version `>=22`. Running on older Node.js environments will result in errors.
- gotcha 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.
Install
-
npm install better-auth-firebase-auth -
yarn add better-auth-firebase-auth -
pnpm add better-auth-firebase-auth
Imports
- firebaseAuthClientPlugin
import { firebaseAuthClientPlugin } from 'better-auth-firebase-auth';import { firebaseAuthClientPlugin } from 'better-auth-firebase-auth/client'; - firebaseAuthPlugin
import { firebaseAuthPlugin } from 'better-auth-firebase-auth';import { firebaseAuthPlugin } from 'better-auth-firebase-auth/server'; - createAuthMiddleware
import { createAuthMiddleware } from 'better-auth/plugins';import { createAuthMiddleware } from 'better-auth/api';
Quickstart
import { createAuthOptions, createAuthMiddleware } from "better-auth/api";
import { firebaseAuthPlugin } from "better-auth-firebase-auth/server";
import { initializeApp, getApps, cert } from 'firebase-admin/app';
import { getAuth } from 'firebase-admin/auth';
import type { NextApiRequest, NextApiResponse } from 'next'; // Example for Next.js
// Initialize Firebase Admin SDK (ensure FIREBASE_SERVICE_ACCOUNT_KEY is a parsed JSON string)
if (!getApps().length) {
try {
const serviceAccountKey = process.env.FIREBASE_SERVICE_ACCOUNT_KEY;
if (!serviceAccountKey) {
throw new Error('FIREBASE_SERVICE_ACCOUNT_KEY environment variable is not set.');
}
initializeApp({
credential: cert(JSON.parse(serviceAccountKey)),
});
} catch (error) {
console.error("Failed to initialize Firebase Admin SDK:", error);
// In production, you might want to throw or exit if core services fail
}
}
const firebaseAdminAuth = getAuth();
// Define Better Auth options with the Firebase plugin
const authOptions = createAuthOptions({
secret: process.env.AUTH_SECRET ?? 'your-super-secret-fallback-key', // Set a strong secret in production env
plugins: [
firebaseAuthPlugin({
firebaseAdminAuth,
// Optional: Specify providers for Firebase Auth, e.g., Google, Email/Password
providers: ['google', 'email'],
// Optional: Customize session cookie options, callbacks, etc.
sessionCookieName: '__session',
cookieOptions: {
secure: process.env.NODE_ENV === 'production',
},
}),
],
// Optional: Add an adapter for database persistence if needed (e.g., for user profiles)
// adapter: YourDatabaseAdapter(),
});
// Create the Better Auth middleware handler
const handler = createAuthMiddleware(authOptions);
// Example: Export the API route handler for a framework like Next.js
export default async function betterAuthHandler(req: NextApiRequest, res: NextApiResponse) {
await handler(req, res);
}
/*
// For client-side integration in your frontend application (e.g., in _app.tsx or a layout component):
// import { AuthProvider } from 'better-auth/client';
// import { firebaseAuthClientPlugin } from 'better-auth-firebase-auth/client';
// import { initializeApp } from 'firebase/app';
// import { getAuth } from 'firebase/auth';
//
// const firebaseClientConfig = {
// apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY ?? '',
// authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN ?? '',
// projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID ?? '',
// // ... other client-side firebase config from your project settings
// };
//
// const firebaseClientApp = initializeApp(firebaseClientConfig);
// const firebaseClientAuth = getAuth(firebaseClientApp);
//
// function MyRootAppComponent({ children }) {
// return (
// <AuthProvider plugins={[firebaseAuthClientPlugin({ firebaseClientAuth })]}>
// {children}
// </AuthProvider>
// );
// }
*/