npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@api-buddy/auth-firebase

v3.0.0

Published

Firebase Authentication for API Buddy - Core package with React hooks and utilities

Readme

@api-buddy/auth-firebase

Core Firebase Authentication package for API Buddy, providing React hooks, providers, and utilities for Firebase Auth integration in Next.js applications.

Features

  • 🔐 Authentication Methods

    • Email/Password authentication
    • Social logins (Google, Facebook, Twitter, GitHub, etc.)
    • Phone authentication
    • Anonymous sign-in
    • Email verification
    • Password reset flow
  • 🛡 Security

    • Secure session management
    • Type-safe API integration
    • Automatic token refresh
    • Comprehensive error handling
  • 🚀 Developer Experience

    • React hooks for easy integration
    • Full TypeScript support
    • Flexible provider pattern
    • Development emulator support

Table of Contents

Installation

Prerequisites

Install Package

# Using npm
npm install @api-buddy/auth-firebase firebase

# Using yarn
yarn add @api-buddy/auth-firebase firebase

# Using pnpm
pnpm add @api-buddy/auth-firebase firebase

Basic Usage

  1. Setup Firebase Client

    First, initialize Firebase in your application:

    // lib/firebase/client.ts
    import { initializeApp } from 'firebase/app';
    import { getAuth } from 'firebase/auth';
    
    const firebaseConfig = {
      apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
      // ... other config
    };
    
    const app = initializeApp(firebaseConfig);
    export const auth = getAuth(app);
  2. Wrap your app with AuthProvider

    // app/providers.tsx
    'use client';
       
    import { AuthProvider } from '@api-buddy/auth-firebase';
    import { auth } from '@/lib/firebase/client';
    
    export function Providers({ children }: { children: React.ReactNode }) {
      return (
        <AuthProvider firebaseAuth={auth}>
          {children}
        </AuthProvider>
      );
    }
  3. Use auth in your components

    // components/LoginForm.tsx
    'use client';
       
    import { useAuth } from '@api-buddy/auth-firebase';
    import { useState } from 'react';
    
    export function LoginForm() {
      const { signIn } = useAuth();
      const [email, setEmail] = useState('');
      const [password, setPassword] = useState('');
      const [error, setError] = useState('');
    
      const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
          await signIn(email, password);
          // Redirect or handle success
        } catch (err) {
          setError(err.message);
        }
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Email"
            required
          />
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Password"
            required
          />
          {error && <div className="error">{error}</div>}
          <button type="submit">Sign In</button>
        </form>
      );
    }
# Using pnpm (recommended)
pnpm add @api-buddy/plugin-auth-firebase firebase firebase-admin

# Using npm
npm install @api-buddy/plugin-auth-firebase firebase firebase-admin

# Using yarn
yarn add @api-buddy/plugin-auth-firebase firebase firebase-admin

Environment Variables

Create a .env.local file in your project root with the following variables:

# Firebase Client Config
NEXT_PUBLIC_FIREBASE_API_KEY=your-api-key
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your-sender-id
NEXT_PUBLIC_FIREBASE_APP_ID=your-app-id
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=your-measurement-id

# Firebase Admin Config (server-side only)
FIREBASE_ADMIN_PROJECT_ID=your-project-id
FIREBASE_ADMIN_CLIENT_EMAIL=your-service-account-email
FIREBASE_ADMIN_PRIVATE_KEY="your-private-key"

# Optional: Enable Firebase Emulator
NEXT_PUBLIC_USE_FIREBASE_EMULATOR=true
FIREBASE_AUTH_EMULATOR_HOST=localhost:9099

Quick Start

  1. Initialize the plugin
# Run the setup wizard
npx @api-buddy/plugin-auth-firebase init

# Or manually generate the required files
npx @api-buddy/plugin-auth-firebase generate
  1. Wrap your app with AuthProvider

Update your app/layout.tsx:

import { AuthProvider } from '@api-buddy/plugin-auth-firebase';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <AuthProvider>
          {children}
        </AuthProvider>
      </body>
    </html>
  );
}
  1. Use authentication in your components
'use client';

import { useAuth } from '@api-buddy/plugin-auth-firebase';

export default function ProfilePage() {
  const { user, loading, signOut } = useAuth();

  if (loading) return <div>Loading...</div>;
  if (!user) return <div>Not authenticated</div>;

  return (
    <div>
      <h1>Welcome, {user.email}!</h1>
      <button onClick={signOut}>Sign Out</button>
    </div>
  );
}

Configuration

Plugin Options

You can configure the plugin by creating a auth.config.ts file in your project root:

// auth.config.ts
import type { AuthPluginConfig } from '@api-buddy/plugin-auth-firebase';

const config: AuthPluginConfig = {
  // Required: Your Firebase config
  firebase: {
    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 Firebase config
  },
  
  // Optional: Customize auth pages
  pages: {
    signIn: '/auth/signin',
    signUp: '/auth/signup',
    verifyEmail: '/auth/verify-email',
    resetPassword: '/auth/reset-password',
    error: '/auth/error',
  },
  
  // Optional: Enable/disable features
  features: {
    emailVerification: true,
    passwordReset: true,
    socialLogins: ['google', 'github'],
  },
  
  // Optional: Custom callbacks
  callbacks: {
    signIn: async (user) => {
      // Custom logic after successful sign in
      return true;
    },
    redirect: async (url, baseUrl) => {
      // Custom redirect logic
      return url.startsWith(baseUrl) ? url : baseUrl;
    },
  },
};

export default config;

API Reference

Hooks

useAuth()

A React hook that provides authentication state and methods.

const {
  user,           // Current user or null
  loading,        // Loading state
  error,          // Error object if any
  signIn,         // Sign in function
  signUp,         // Sign up function
  signOut,        // Sign out function
  resetPassword,  // Reset password function
  updateProfile,  // Update profile function
  reload,         // Reload user data
} = useAuth();

useSession()

A React hook to access the current session.

const { session, status } = useSession();

Server Components

getServerSession()

Get the session in a Server Component.

import { getServerSession } from '@api-buddy/plugin-auth-firebase/server';

export default async function Page() {
  const session = await getServerSession();
  // ...
}

Middleware

withAuth

Higher-order function to protect API routes.

import { withAuth } from '@api-buddy/plugin-auth-firebase';

export const GET = withAuth(async (req, user) => {
  // This route is protected and will only run for authenticated users
  return Response.json({ user });
});

CLI Commands

Initialize

# Run the setup wizard
npx @api-buddy/plugin-auth-firebase init

# Or generate files with options
npx @api-buddy/plugin-auth-firebase generate \
  --pages login,signup,profile,reset-password \
  --api

Available Commands

  • init: Interactive setup wizard
  • generate: Generate auth pages and API routes
  • add-user: Add a new user (admin only)
  • list-users: List all users (admin only)

Customization

Custom Pages

You can create custom auth pages by creating files in the app/auth directory:

  • signin/page.tsx - Sign in page
  • signup/page.tsx - Sign up page
  • reset-password/page.tsx - Password reset page
  • verify-email/page.tsx - Email verification page
  • error/page.tsx - Error page

Custom Components

You can use the provided UI components or create your own:

import { AuthForm, SocialLoginButtons } from '@api-buddy/plugin-auth-firebase/components';

function CustomSignIn() {
  return (
    <div>
      <h1>Welcome Back</h1>
      <AuthForm type="signin" />
      <SocialLoginButtons providers={['google', 'github']} />
    </div>
  );
}

Troubleshooting

Common Issues

Firebase Admin Initialization Error

Error: Failed to initialize Firebase Admin: Error: Failed to parse private key

Make sure your FIREBASE_ADMIN_PRIVATE_KEY is properly formatted with escaped newlines:

# Correct
FIREBASE_ADMIN_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMII...\n-----END PRIVATE KEY-----\n"

# Incorrect
FIREBASE_ADMIN_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----
MII...
-----END PRIVATE KEY-----

CORS Errors

If you're seeing CORS errors in development, make sure to configure your CORS headers:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const response = NextResponse.next();
  
  // Set CORS headers
  response.headers.set('Access-Control-Allow-Origin', '*');
  response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  
  return response;
}

Contributing

Contributions are welcome! Please read our Contributing Guide for details on how to get started.

License

This project is licensed under the MIT License - see the LICENSE file for details. yarn add @api-buddy/plugin-auth-firebase firebase firebase-admin


## Quick Start

1. **Initialize Firebase Auth in your Next.js app**:

```bash
# Using API Buddy CLI
api-buddy firebase-auth init

# Or manually
npx @api-buddy/plugin-auth-firebase init
  1. Set up environment variables in .env.local:
# Firebase Client Configuration
NEXT_PUBLIC_FIREBASE_API_KEY=your-api-key
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-app.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-bucket.appspot.com
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your-sender-id
NEXT_PUBLIC_FIREBASE_APP_ID=your-app-id

# Firebase Admin Configuration
FIREBASE_ADMIN_PROJECT_ID=your-project-id
FIREBASE_ADMIN_CLIENT_EMAIL=your-service-account@project.iam.gserviceaccount.com
FIREBASE_ADMIN_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nYourPrivateKeyHere\n-----END PRIVATE KEY-----\n"
  1. Wrap your app with AuthProvider in app/layout.tsx:
import { AuthProvider } from '@api-buddy/plugin-auth-firebase';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        <AuthProvider>
          {children}
        </AuthProvider>
      </body>
    </html>
  )
}
  1. Use authentication in your components:
'use client';

import { useAuth } from '@api-buddy/plugin-auth-firebase';

export default function Profile() {
  const { user, loading, signOut } = useAuth();

  if (loading) return <div>Loading...</div>;
  if (!user) return <div>Please sign in</div>;

  return (
    <div>
      <h1>Welcome, {user.email}!</h1>
      <button onClick={signOut}>Sign Out</button>
    </div>
  );
}

Configuration

Firebase Setup

  1. Go to the Firebase Console
  2. Create a new project or select an existing one
  3. Navigate to Project Settings > General
  4. Under "Your apps", add a new web app
  5. Copy the configuration object and add it to your environment variables

Environment Variables

| Variable | Description | Required | Default | |----------|-------------|:--------:|:-------:| | NEXT_PUBLIC_FIREBASE_API_KEY | Firebase API key | ✅ | - | | NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN | Firebase Auth domain | ✅ | - | | NEXT_PUBLIC_FIREBASE_PROJECT_ID | Firebase project ID | ✅ | - | | NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET | Firebase storage bucket | ✅ | - | | NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID | Firebase messaging sender ID | ✅ | - | | NEXT_PUBLIC_FIREBASE_APP_ID | Firebase app ID | ✅ | - | | FIREBASE_ADMIN_PROJECT_ID | Firebase Admin project ID | ✅ | - | | FIREBASE_ADMIN_CLIENT_EMAIL | Firebase Admin client email | ✅ | - | | FIREBASE_ADMIN_PRIVATE_KEY | Firebase Admin private key | ✅ | - |

Usage

Authentication Methods

Email/Password Authentication

import { useAuth } from '@api-buddy/plugin-auth-firebase';

function AuthForm() {
  const { signUp, signIn, signOut, user } = useAuth();

  const handleSignUp = async (email: string, password: string) => {
    try {
      await signUp(email, password);
      // User is signed up and signed in
    } catch (error) {
      console.error('Error signing up:', error);
    }
  };

  // Similar for signIn and signOut
}

Social Authentication

function SocialAuth() {
  const { signInWithGoogle, signInWithFacebook } = useAuth();

  return (
    <div>
      <button onClick={signInWithGoogle}>Sign in with Google</button>
      <button onClick={signInWithFacebook}>Sign in with Facebook</button>
    </div>
  );
}

Protected Routes

import { withAuth } from '@api-buddy/plugin-auth-firebase';

function ProtectedPage() {
  return <div>This is a protected page</div>;
}

export default withAuth(ProtectedPage);

API Reference

Hooks

useAuth()

Main authentication hook that provides authentication state and methods.

const {
  user,           // Current user object or null
  loading,        // Loading state
  error,          // Error object if any
  signIn,         // Email/password sign in
  signUp,         // Email/password sign up
  signOut,        // Sign out
  resetPassword,  // Send password reset email
  updateProfile,  // Update user profile
  // Social auth methods
  signInWithGoogle,
  signInWithFacebook,
  signInWithTwitter,
  signInWithGithub,
  signInAnonymously,
} = useAuth();

Components

AuthProvider

Provider component that should wrap your application.

ProtectedRoute

Component that renders children only if user is authenticated.

import { ProtectedRoute } from '@api-buddy/plugin-auth-firebase';

function App() {
  return (
    <ProtectedRoute>
      <YourProtectedContent />
    </ProtectedRoute>
  );
}

Advanced Usage

Custom Authentication Pages

You can create custom authentication pages by using the provided hooks and components:

// app/auth/custom-signin/page.tsx
'use client';

import { useAuth } from '@api-buddy/plugin-auth-firebase';

export default function CustomSignIn() {
  const { signIn } = useAuth();
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);
    const email = formData.get('email') as string;
    const password = formData.get('password') as string;
    
    try {
      await signIn(email, password);
    } catch (error) {
      console.error('Sign in failed:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="email" type="email" required />
      <input name="password" type="password" required />
      <button type="submit">Sign In</button>
    </form>
  );
}

Troubleshooting

Common Issues

Missing Environment Variables

Ensure all required environment variables are set in your .env.local file.

CORS Issues

If you encounter CORS issues, make sure your Firebase Auth domain is properly configured in the Firebase Console.

Authentication Errors

Check the browser console and server logs for detailed error messages. Common issues include:

  • Incorrect API keys
  • Unauthorized domain
  • Disabled authentication methods

Contributing

Contributions are welcome! Please read our contributing guide to get started.

License

This project is licensed under the MIT License - see the LICENSE file for details.

  • Hooks for auth state changes

  • Server-side rendering support

  • API route protection

  • 📱 Mobile Ready

    • Responsive design
    • Touch-friendly components
    • Offline support
    • PWA ready
  • 🎨 UI Components

    • Pre-built auth forms
    • Customizable themes
    • Loading states
    • Error handling

Quick Start

1. Install the Plugin

# Using pnpm (recommended)
pnpm add @api-buddy/plugin-auth-firebase firebase firebase-admin

# Using npm
npm install @api-buddy/plugin-auth-firebase firebase firebase-admin

# Using yarn
yarn add @api-buddy/plugin-auth-firebase firebase firebase-admin

2. Initialize the Plugin

// In your app's plugin configuration
import { FirebaseAuthPlugin } from '@api-buddy/plugin-auth-firebase';

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
  
  // Optional: Configure which auth methods are enabled
  enableGoogleSignIn: true,
  enableFacebookSignIn: true,
  enableTwitterSignIn: true,
  enableGithubSignIn: true,
  enablePhoneSignIn: true,
  enableAnonymousSignIn: true,
  
  // Optional: Session persistence (default: 'local')
  // 'local' - persists even when the window is closed
  // 'session' - persists in current session/tab
  // 'none' - no persistence
  persistence: 'local'
};

// Initialize the plugin
const firebaseAuth = new FirebaseAuthPlugin(firebaseConfig);

// Register with your app's plugin system
app.registerPlugin(firebaseAuth);

3. Generate Authentication Pages and API Routes

Use the API Buddy CLI to generate authentication pages and API routes:

# Generate all auth pages and API routes
api-buddy firebase-auth generate

# Or specify which pages to generate
api-buddy firebase-auth generate --pages login,signup,profile,reset-password

# Skip API routes generation
api-buddy firebase-auth generate --no-api

# Specify custom output directory (default: 'app')
api-buddy firebase-auth generate --output src/app

4. Use the Auth Context in Your Components

'use client';

import { useAuth } from '@api-buddy/plugin-auth-firebase';

export function UserProfile() {
  const { user, loading, error } = useAuth();
  
  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  if (!user) return <div>Please sign in</div>;
  
  return (
    <div>
      <h1>Welcome, {user.email}!</h1>
      <button onClick={() => auth.signOut()}>Sign Out</button>
    </div>
  );
}

API Reference

Auth Methods

signInWithEmail(email: string, password: string)

Sign in with email and password.

try {
  const user = await auth.signInWithEmail('[email protected]', 'password123');
  console.log('Signed in:', user.uid);
} catch (error) {
  console.error('Sign in failed:', error);
}

signUpWithEmail(email: string, password: string)

Create a new user account with email and password.

signInWithGoogle()

Sign in with Google OAuth.

signInWithFacebook()

Sign in with Facebook OAuth.

signInWithTwitter()

Sign in with Twitter OAuth.

signInWithGithub()

Sign in with GitHub OAuth.

signInAnonymously()

Sign in anonymously.

signOut()

Sign out the current user.

getCurrentUser()

Get the currently signed-in user.

onAuthStateChanged(callback)

Subscribe to auth state changes.

Error Handling

All auth methods throw errors that include a code property for programmatic error handling:

try {
  await auth.signInWithEmail('[email protected]', 'wrong-password');
} catch (error) {
  if (error.code === 'auth/wrong-password') {
    // Handle wrong password
  } else if (error.code === 'auth/user-not-found') {
    // Handle user not found
  }
  console.error('Auth error:', error.message);
}

Configuration Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | apiKey | string | - | Required Firebase API key | | authDomain | string | - | Required Firebase Auth domain | | projectId | string | - | Required Firebase project ID | | appId | string | - | Required Firebase app ID | | enableGoogleSignIn | boolean | false | Enable Google Sign-In | | enableFacebookSignIn | boolean | false | Enable Facebook Sign-In | | enableTwitterSignIn | boolean | false | Enable Twitter Sign-In | | enableGithubSignIn | boolean | false | Enable GitHub Sign-In | | enablePhoneSignIn | boolean | false | Enable Phone Number Sign-In | | enableAnonymousSignIn | boolean | false | Enable Anonymous Sign-In | | persistence | 'local' | 'session' | 'none' | 'local' | Auth session persistence |

TypeScript Support

The plugin includes TypeScript type definitions. All auth methods and hooks are fully typed.

Security Considerations

  • Always use HTTPS in production
  • Enable appropriate security headers
  • Implement rate limiting
  • Use secure, HTTP-only cookies for sessions
  • Keep Firebase security rules up to date
  • Regularly rotate API keys and secrets

5. Configure Environment Variables

Create or update your .env.local file with your Firebase configuration:

# Client-side (NEXT_PUBLIC_*)
NEXT_PUBLIC_FIREBASE_API_KEY=your-api-key
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-storage-bucket
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your-messaging-sender-id
NEXT_PUBLIC_FIREBASE_APP_ID=your-app-id

# Server-side (only used in API routes)
FIREBASE_CLIENT_EMAIL=your-service-account-email
FIREBASE_PRIVATE_KEY="your-private-key"

# Optional: Configure which auth methods are enabled
NEXT_PUBLIC_ENABLE_GOOGLE_SIGNIN=true
NEXT_PUBLIC_ENABLE_FACEBOOK_SIGNIN=true
NEXT_PUBLIC_ENABLE_TWITTER_SIGNIN=true
NEXT_PUBLIC_ENABLE_GITHUB_SIGNIN=true
NEXT_PUBLIC_ENABLE_PHONE_SIGNIN=true
NEXT_PUBLIC_ENABLE_ANONYMOUS_SIGNIN=true

# Optional: Session persistence (local, session, none)
NEXT_PUBLIC_AUTH_PERSISTENCE=local

6. Start Developing

Run your Next.js application:

npm run dev

Visit http://localhost:3000/auth/login to see the login page.

Advanced Usage

Custom Auth Pages

You can customize the generated auth pages by modifying the components in the app/auth directory. The pages are built using Shadcn UI components and can be fully customized to match your app's design.

Server-Side Authentication

For server-side authentication in API routes or server components:

import { getServerAuth } from '@api-buddy/plugin-auth-firebase/server';

export async function GET(request: Request) {
  const session = await getServerAuth(request);
  
  if (!session) {
    return new Response('Unauthorized', { status: 401 });
  }
  
  // User is authenticated
  return Response.json({ user: session.user });
}

Custom Error Pages

Customize error pages by creating the following files in your app directory:

  • app/auth/error.tsx - For auth-related errors
  • app/not-found.tsx - For 404 errors
  • app/error.tsx - For all other errors

Theming

The auth components support theming through CSS variables. Override the default theme in your global CSS:

:root {
  --primary: #0070f3;
  --primary-foreground: #ffffff;
  --border: #e2e8f0;
  --input: #e2e8f0;
  --ring: #0070f3;
  --radius: 0.5rem;
}

.dark {
  --background: #0f172a;
  --foreground: #f8fafc;
  --card: #1e293b;
  --card-foreground: #f8fafc;
  --popover: #1e293b;
  --popover-foreground: #f8fafc;
  --primary: #60a5fa;
  --primary-foreground: #1e40af;
  --secondary: #334155;
  --secondary-foreground: #f8fafc;
  --muted: #334155;
  --muted-foreground: #94a3b8;
  --accent: #334155;
  --accent-foreground: #f8fafc;
  --destructive: #7f1d1d;
  --destructive-foreground: #fecaca;
  --border: #334155;
  --input: #334155;
  --ring: #60a5fa;
}

Migration Guide

Upgrading from v0.x to v1.0

  1. Update your dependencies:

    pnpm up @api-buddy/plugin-auth-firebase@latest
  2. The auth API has been updated to be more consistent. Update any direct method calls:

    • auth.signIn()auth.signInWithEmail()
    • auth.createUser()auth.signUpWithEmail()
    • auth.currentUserauth.getCurrentUser()
  3. The error handling has been improved. Update your error handling code to use the new error codes and messages.

Troubleshooting

Common Issues

Firebase Not Initialized

Make sure you've called initializeApp with your Firebase config before using any auth methods.

CORS Errors

If you're seeing CORS errors, make sure your Firebase Auth domain is properly configured in the Firebase Console.

Invalid API Key

Double-check that your Firebase API key is correct and hasn't been restricted in the Firebase Console.

Session Persistence

If users are being signed out unexpectedly, check your persistence setting and ensure it matches your app's requirements.

Contributing

Contributions are welcome! Please read our contributing guide to get started.

License

MIT

CLI Commands

firebase-auth generate

Generate authentication pages and API routes.

Options:

  • -p, --pages <pages>: Comma-separated list of pages to generate (login, signup, profile)
  • --no-api: Skip generating API routes
  • -o, --output <path>: Output directory (default: 'app')

Examples:

# Generate all auth pages and API routes
api-buddy firebase-auth generate

# Generate only login and signup pages without API routes
api-buddy firebase-auth generate --pages login,signup --no-api

Development Status

✅ Implemented

  • Page generation (login, signup, profile)
  • API route generation for authentication
  • Email/password authentication
  • Session management
  • TypeScript support
  • Environment configuration

🚧 In Progress

  • OAuth provider setup
  • Error handling improvements
  • Test coverage
  • Documentation

📅 Planned

  • Phone authentication
  • Multi-factor authentication
  • Admin dashboard
  • Custom templates
  • Social login providers (Google, Facebook, GitHub, etc.)
  • Passwordless authentication

Installation

# Using pnpm (recommended)
pnpm add @api-buddy/plugin-auth-firebase firebase

# Using npm
npm install @api-buddy/plugin-auth-firebase firebase

# Using yarn
yarn add @api-buddy/plugin-auth-firebase firebase

Getting Started

1. Initialize the Plugin

import { PluginManager } from '@api-buddy/plugin-core';
import FirebaseAuthPlugin from '@api-buddy/plugin-auth-firebase';

// Initialize plugin manager
const pluginManager = new PluginManager();

// Create and configure the auth plugin
const authPlugin = new FirebaseAuthPlugin({
  // Required Firebase config
  apiKey: 'your-api-key',
  authDomain: 'your-project.firebaseapp.com',
  projectId: 'your-project-id',
  appId: 'your-app-id',
  
  // Optional Firebase config
  storageBucket: 'your-storage-bucket',
  messagingSenderId: 'your-messaging-sender-id',
  measurementId: 'your-measurement-id',
  
  // Plugin options
  persistence: 'local', // 'local' | 'session' | 'none' (default: 'local')
  enableEmailPassword: true,  // Enable email/password auth (default: true)
  enableGoogleSignIn: false,  // Enable Google OAuth (default: false)
  enableFacebookSignIn: false,// Enable Facebook OAuth (default: false)
  enableTwitterSignIn: false, // Enable Twitter OAuth (default: false)
  enableGithubSignIn: false,  // Enable GitHub OAuth (default: false)
  enablePhoneSignIn: false,   // Enable phone auth (default: false)
  enableAnonymousSignIn: false // Enable anonymous auth (default: false)
});

// Register the plugin
await pluginManager.registerPlugin('firebase-auth', authPlugin);

2. Using Auth Methods

// Get auth methods from plugin context
const auth = pluginManager.context?.data.get('auth') as AuthMethods;

// Sign up a new user
try {
  const user = await auth.signUpWithEmail('[email protected]', 'secure-password');
  console.log('User created:', user);
} catch (error) {
  console.error('Sign up failed:', error);
}

// Sign in
try {
  const user = await auth.signInWithEmail('[email protected]', 'secure-password');
  console.log('Signed in as:', user);
} catch (error) {
  console.error('Sign in failed:', error);
}

// Sign out
try {
  await auth.signOut();
  console.log('Signed out');
} catch (error) {
  console.error('Sign out failed:', error);
}

// Get current user
const currentUser = auth.getCurrentUser();
console.log('Current user:', currentUser);

// Subscribe to auth state changes
const unsubscribe = auth.onAuthStateChanged((user) => {
  console.log('Auth state changed:', user ? 'Signed in' : 'Signed out');
  console.log('User details:', user);
});

// Unsubscribe when done
// unsubscribe();

API Reference

FirebaseAuthPlugin

Constructor

new FirebaseAuthPlugin(config: FirebaseAuthConfig)

Configuration Options:

| Option | Type | Required | Default | Description | |--------|------|----------|---------|-------------| | apiKey | string | Yes | - | Your Firebase API key | | authDomain | string | Yes | - | Your Firebase auth domain | | projectId | string | Yes | - | Your Firebase project ID | | appId | string | Yes | - | Your Firebase app ID | | storageBucket | string | No | - | Firebase storage bucket | | messagingSenderId | string | No | - | Firebase messaging sender ID | | measurementId | string | No | - | Google Analytics measurement ID | | persistence | 'local' | 'session' | 'none' | No | 'local' | Auth state persistence mode | | enableEmailPassword | boolean | No | true | Enable email/password auth | | enableGoogleSignIn | boolean | No | false | Enable Google OAuth | | enableFacebookSignIn | boolean | No | false | Enable Facebook OAuth | | enableTwitterSignIn | boolean | No | false | Enable Twitter OAuth | | enableGithubSignIn | boolean | No | false | Enable GitHub OAuth | | enablePhoneSignIn | boolean | No | false | Enable phone auth | | enableAnonymousSignIn | boolean | No | false | Enable anonymous auth |

AuthMethods Interface

interface AuthMethods {
  // Email/Password
  signInWithEmail(email: string, password: string): Promise<FirebaseUser>;
  signUpWithEmail(email: string, password: string): Promise<FirebaseUser>;
  
  // Session
  signOut(): Promise<void>;
  getCurrentUser(): FirebaseUser | null;
  onAuthStateChanged(callback: (user: FirebaseUser | null) => void): () => void;
}

FirebaseUser Interface

interface FirebaseUser {
  uid: string;
  email: string | null;
  emailVerified: boolean;
  displayName: string | null;
  photoURL: string | null;
  phoneNumber: string | null;
  disabled: boolean;
  metadata: {
    creationTime?: string;
    lastSignInTime?: string;
  };
  providerData: Array<{
    uid: string;
    providerId: string;
    displayName: string | null;
    email: string | null;
    phoneNumber: string | null;
    photoURL: string | null;
  }>;
}

Error Handling

All auth methods return Promises that reject with errors. Common error cases include:

  • auth/invalid-email: The email address is invalid
  • auth/user-disabled: The user account has been disabled
  • auth/user-not-found: No user found with this email
  • auth/wrong-password: The password is invalid
  • auth/email-already-in-use: Email already in use
  • auth/weak-password: Password is too weak
  • auth/too-many-requests: Too many failed login attempts

License

MIT © API Buddy