| name | firebase-auth-setup |
| description | Configures Firebase Authentication — providers, security rules, custom claims, and React auth hooks |
| user-invocable | true |
Firebase Auth Setup
You are a security-focused engineer responsible for configuring Firebase Authentication in Next.js App Router projects. You set up auth providers, create React hooks, configure middleware, and sync Firebase users with Supabase profiles.
Planning Protocol (MANDATORY — execute before ANY action)
Before creating or modifying any auth configuration, you MUST complete this planning phase:
-
Understand the request. Determine: (a) which auth providers are needed, (b) whether this is initial setup or adding to an existing configuration, (c) any role-based access requirements (custom claims), (d) whether Firebase-Supabase sync is already configured.
-
Survey the existing auth setup. Check: (a) src/lib/firebase/ for existing client and admin SDK initialization, (b) src/hooks/use-auth.ts for existing auth hooks, (c) src/middleware.ts for existing auth middleware, (d) src/app/api/auth/ for existing sync routes, (e) .env.example (NOT .env.local) to see which Firebase env vars are expected. Do NOT read .env.local or any file containing actual credential values.
-
Build an execution plan. Write out: (a) which files need to be created vs modified, (b) the dependency order (SDK init first, then hooks, then components, then sync route), (c) which Firebase Console settings the user will need to configure manually.
-
Identify risks. Flag: (a) changes to auth middleware that could lock out existing users, (b) sync route changes that could break the Firebase-Supabase user mapping, (c) missing env vars that will cause runtime errors. For each risk, define the mitigation.
-
Execute step by step. Create or modify files in dependency order. After each file, verify it compiles. Test the auth flow end-to-end if possible.
-
Summarize. Report what was configured, which files are new or modified, and the manual steps the user must complete in the Firebase Console (enable providers, add authorized domains, etc.).
Do NOT skip this protocol. Auth misconfiguration can lock users out or create security vulnerabilities.
Architecture Overview
This stack uses Firebase for authentication and Supabase for data storage. The flow is:
- User authenticates via Firebase (Google, Apple, email/password, etc.).
- Firebase issues a JWT (ID token).
- The Next.js middleware or Server Component verifies the token via Firebase Admin SDK.
- A corresponding Supabase profile is created/updated (synced via a trigger or API route).
- Supabase RLS policies use the Firebase UID stored in the
profiles.id column.
Auth Hook
Create/update src/hooks/use-auth.ts:
"use client";
import { useEffect, useState, useCallback } from "react";
import {
onAuthStateChanged,
signInWithPopup,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signOut as firebaseSignOut,
GoogleAuthProvider,
OAuthProvider,
type User,
} from "firebase/auth";
import { auth } from "@/lib/firebase/client";
interface AuthState {
user: User | null;
loading: boolean;
error: string | null;
}
export function useAuth() {
const [state, setState] = useState<AuthState>({
user: null,
loading: true,
error: null,
});
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
setState({ user, loading: false, error: null });
});
return unsubscribe;
}, []);
const signInWithGoogle = ( () => {
{
( ({ ...prev, : , : }));
provider = ();
(auth, provider);
} (: ) {
( ({ ...prev, : , : error. }));
}
}, []);
signInWithApple = ( () => {
{
( ({ ...prev, : , : }));
provider = ();
provider.();
provider.();
(auth, provider);
} (: ) {
( ({ ...prev, : , : error. }));
}
}, []);
signInWithEmail = (
(: , : ) => {
{
( ({ ...prev, : , : }));
(auth, email, password);
} (: ) {
( ({ ...prev, : , : error. }));
}
},
[]
);
signUpWithEmail = (
(: , : ) => {
{
( ({ ...prev, : , : }));
(auth, email, password);
} (: ) {
( ({ ...prev, : , : error. }));
}
},
[]
);
signOut = ( () => {
{
(auth);
} (: ) {
( ({ ...prev, : error. }));
}
}, []);
{
...state,
signInWithGoogle,
signInWithApple,
signInWithEmail,
signUpWithEmail,
signOut,
};
}
Auth Provider Component
Create src/components/shared/auth-provider.tsx:
"use client";
import { createContext, useContext } from "react";
import { useAuth } from "@/hooks/use-auth";
import type { User } from "firebase/auth";
interface AuthContextType {
user: User | null;
loading: boolean;
error: string | null;
signInWithGoogle: () => Promise<void>;
signInWithApple: () => Promise<void>;
signInWithEmail: (email: string, password: string) => Promise<void>;
signUpWithEmail: (email: string, password: string) => Promise<void>;
signOut: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | >();
() {
auth = ();
;
}
() {
context = ();
(!context) {
();
}
context;
}
Server-Side Token Verification
Create/update src/lib/firebase/verify-token.ts:
import { adminAuth } from "@/lib/firebase/admin";
export async function verifyFirebaseToken(token: string) {
try {
const decodedToken = await adminAuth.verifyIdToken(token);
return { uid: decodedToken.uid, email: decodedToken.email };
} catch {
return null;
}
}
Firebase-Supabase User Sync
Create src/app/api/auth/sync/route.ts to sync Firebase users with Supabase profiles:
import { NextRequest, NextResponse } from "next/server";
import { adminAuth } from "@/lib/firebase/admin";
import { createClient } from "@supabase/supabase-js";
const supabaseAdmin = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!
);
export async function POST(request: NextRequest) {
const authHeader = request.headers.get("Authorization");
if (!authHeader?.startsWith("Bearer ")) {
return NextResponse.json({ error: "Missing token" }, { status: 401 });
}
try {
const token = authHeader.split("Bearer ")[1];
const decoded = await adminAuth.verifyIdToken(token);
const { error } = await supabaseAdmin
.()
.(
{
: decoded.,
: decoded. || ,
: decoded. || ,
: decoded. || ,
: ().(),
},
{ : }
);
(error) error;
.({ : });
} (: ) {
.(
{ : error. },
{ : }
);
}
}
Login Page Template
Create src/app/(auth)/login/page.tsx:
"use client";
import { useAuthContext } from "@/components/shared/auth-provider";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export default function LoginPage() {
const { user, loading, error, signInWithGoogle, signInWithApple } =
useAuthContext();
const router = useRouter();
useEffect(() => {
if (user && !loading) {
user.getIdToken().then((token) => {
fetch("/api/auth/sync", {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
}).then(() => router.push("/dashboard"));
});
}
}, [user, loading, router]);
if (loading) {
return (
<div className="flex min-h-screen items-center justify-center">
<p className="text-muted-foreground">Loading...
);
}
(
);
}
Custom Claims
For role-based access (admin, editor, viewer):
import { adminAuth } from "@/lib/firebase/admin";
export async function setUserRole(uid: string, role: "admin" | "editor" | "viewer") {
await adminAuth.setCustomUserClaims(uid, { role });
}
export async function getUserRole(token: string): Promise<string | null> {
try {
const decoded = await adminAuth.verifyIdToken(token);
return (decoded.role as string) || null;
} catch {
return null;
}
}
Adding a New Auth Provider
When the user asks to add a new provider:
- Update the
useAuth hook with the new sign-in method.
- Add the provider button to the login page.
- Test the flow locally.
- Remind the user to enable the provider in the Firebase Console (Settings > Authentication > Sign-in method).
- Commit:
feat: add <provider> authentication.
Security Checklist