Integrate Firebase Authentication with Next.js — email/password, Google OAuth, session cookies, and protected routes with middleware.

Abdur Razzak
Full-Stack Web Developer
Firebase Authentication provides a complete authentication backend with no server infrastructure to manage. It supports email/password, Google, Facebook, Twitter, GitHub, phone number, and anonymous auth out of the box. For projects that don't need a custom auth server, Firebase Auth is an excellent choice — it handles token management, email verification, password reset, and session persistence automatically.
Create a Firebase project at console.firebase.google.com and enable Authentication with your desired providers. Install firebase (client SDK) and firebase-admin (server SDK). Create a client-side Firebase app instance in lib/firebase.ts using initializeApp with your project config from environment variables. Store Firebase config values in your .env.local file.
Use signInWithEmailAndPassword, createUserWithEmailAndPassword, and signInWithPopup from firebase/auth for client-side auth operations. Wrap your app with an AuthProvider component that listens to onAuthStateChanged — this fires whenever auth state changes and gives you the current user. Store the user in React Context or Zustand for global access. Firebase automatically handles token refresh.
Firebase ID tokens are JWTs that expire after 1 hour. For SSR with Next.js, exchange the Firebase ID token for a long-lived session cookie using firebase-admin on the server. Create an API route that calls admin.auth().createSessionCookie() with the ID token. Store the session cookie as an HTTP-only cookie. In Next.js Middleware, verify the session cookie with admin.auth().verifySessionCookie() to protect routes.
Create a Next.js middleware.ts that reads your Firebase session cookie and verifies it using the firebase-admin SDK. Redirect unauthenticated users to /login and redirect authenticated users away from /login to /dashboard. The middleware runs at the edge before any page renders, providing fast, server-side route protection without client-side flash of content.
Firebase's security model relies on Firestore Security Rules — never rely solely on client-side checks. Write rules that allow read/write only when the requesting user's UID matches the document's owner field. Test your rules in the Firebase console's Rules Playground. Avoid storing sensitive data in Firebase directly — use your own backend API for business logic and only use Firebase for auth token management.