Better Auth Firebase Authentication Plugin

2.0.5 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

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.

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>
//   );
// }
*/

view raw JSON →