Introduction
Firebase is a Backend-as-a-Service (BaaS) platform developed by Google. It provides developers with a suite of tools and services to build, improve, and scale web and mobile apps. Key features include:
- Authentication (Email/Password, Google, GitHub, etc.)
- Firestore (real-time NoSQL database)
- Cloud Storage
- Hosting
- Cloud Functions
- Analytics
For this guide, we'll focus primarily on Firebase Authentication with Next.js, which allows you to add secure login functionality to your apps with minimal setup.
Why Use Firebase with Next.js?
Next.js is a powerful React framework that supports both server-rendering and client-side rendering, making it ideal for building full-stack applications. When combined Firebase with Next.js, you get:
- Simple and secure authentication
- Real-time capabilities (with Firestore or Realtime DB)
- Easy deployment via Firebase Hosting or Vercel
- Reduced backend boilerplate
Using Firebase with Next.js 15, especially with the App Router and React Server Components, allows for a clean and scalable architecture. Learn More about Server side rendering in Next.js
What's New in Next.js 15?
Next.js 15 continues to evolve the App Router architecture introduced in version 13+. Notable improvements that benefit Firebase integration include:
- Improved Server Actions
- More Stable React Server Components
- Simplified Data Fetching Patterns
You'll learn how to integrate Firebase Auth while staying compatible with the latest updates in Next.js 15.
Setting Up the Project
Step 1: Create a Next.js 15 Project
If you haven't already, create a new Next.js project using the latest version (with the App Router):
.ssh
1npx create-next-app@latest firebase-auth-nextjs15 --experimental-app
Choose the following options during setup:
- TypeScript: Yes (recommended)
- App Router: Yes
- Tailwind CSS: Optional, but recommended for styling
- ESLint / Prettier: Optional
Navigate into your project folder:
.ssh
1cd firebase-auth-nextjs15
Step 2: Install Firebase SDK
Install the official Firebase JavaScript SDK:
.ssh
1npm install firebase
This package includes everything you need to work with Firebase Authentication, Firestore, Storage, etc.
Step 3: Add Firebase Config to .env.local
When you set up your Firebase project with Next.js , you'll get configuration values like apiKey, authDomain, etc.
Add those values in your .env.local
file like this:
.env
1NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key
2NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your_project_id.firebaseapp.com
3NEXT_PUBLIC_FIREBASE_PROJECT_ID=your_project_id
4NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your_project_id.appspot.com
5NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your_sender_id
6NEXT_PUBLIC_FIREBASE_APP_ID=your_app_id
Notice the NEXT_PUBLIC part. That makes these variables accessible in browser.
Step 4: Create a Firebase Config File
Create a new file in your project lib/firebase.ts:
.tsx
1// lib/firebase.ts
2import { initializeApp, getApps, getApp } from 'firebase/app';
3
4const firebaseConfig = {
5apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
6authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
7projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
8storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
9messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
10appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
11};
12
13const app = getApps().length ? getApp() : initializeApp(firebaseConfig);
14
15export default app;
This ensures Firebase isn't initialized more than once (important in Next.js hot-reload dev mode). At this point, your project is set up to start integrating Firebase Authentication in Next.js.
To prepare for using Firebase Auth, you can also export the auth module from the same file:
.tsx
1// lib/firebase.ts (continued)
2import { getAuth } from 'firebase/auth';
3
4export const auth = getAuth(app);
Firebase Project Setup
To use Firebase with Next.js 15 app, you need to set up a Firebase project and configure authentication.
- Go to Firebase Console
- Click “Add project”
- Enter a project name (e.g., nextjs-firebase-auth)
- You can skip Google Analytics (or enable it if you need it)
- Click “Create project”
Once it's created, you'll be redirected to your Firebase project dashboard.
Enable Authentication
To use Firebase Authentication with Next.js (email/password, Google sign-in, etc.):
- In the left sidebar, click “Build” → “Authentication”
- Go to the Sign-in method tab
- Enable the providers you want:
- Email/Password: Turn it ON for basic auth
- Google: Turn it ON and provide a project support email
You can also enable GitHub, Facebook, etc., later if needed.
Get Firebase Config Keys
To get your Firebase config keys:
- In the left sidebar, click “Project Settings”
- Scroll down to “Your apps”
- Click </> (Web) to register your app
- Enter a nickname (e.g., nextjs-app)
- Choose “No Firebase Hosting” for now (you'll add hosting later if needed)
Once registered, you'll get your Firebase config object like this:
.js
1const firebaseConfig = {
2apiKey: "your-api-key",
3authDomain: "your-project-id.firebaseapp.com",
4projectId: "your-project-id",
5storageBucket: "your-project-id.appspot.com",
6messagingSenderId: "your-sender-id",
7appId: "your-app-id"
8};
Copy these keys and paste them into your .env.local
file
Implementing Firebase Authentication
Now that Firebase is initialized in your Next.js app, it's time to implement the core authentication flows: Sign Up, Sign In, and Sign Out using Firebase Authentication.
We'll use Firebase Email/Password method first.
Sign Up with Email & Password
Create Sign Up and Login pages in your app directory.
/app/signup/page.tsx:
.tsx
1'use client';
2import { useState } from 'react';
3import { createUserWithEmailAndPassword } from 'firebase/auth';
4import { auth } from '@/lib/firebase';
5
6export default function SignUpPage() {
7const [email, setEmail] = useState('');
8const [password, setPassword] = useState('');
9
10const handleSignup = async (e: any) => {
11 e.preventDefault();
12 try {
13 await createUserWithEmailAndPassword(auth, email, password);
14 alert('Signup successful!');
15 } catch (err) {
16 console.error(err);
17 alert('Signup failed!');
18 }
19};
20
21return (
22 <form onSubmit={handleSignup}>
23 <input placeholder="Email" onChange={(e) => setEmail(e.target.value)} required />
24 <input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} required />
25 <button type="submit">Sign Up</button>
26 </form>
27);
28}
/app/login/page.tsx
.tsx
1'use client';
2import { useState } from 'react';
3import { signInWithEmailAndPassword } from 'firebase/auth';
4import { auth } from '@/lib/firebase';
5
6export default function LoginPage() {
7const [email, setEmail] = useState('');
8const [password, setPassword] = useState('');
9
10const handleLogin = async (e: any) => {
11 e.preventDefault();
12 try {
13 await signInWithEmailAndPassword(auth, email, password);
14 alert('Login successful!');
15 } catch (err) {
16 console.error(err);
17 alert('Login failed!');
18 }
19};
20
21return (
22 <form onSubmit={handleLogin}>
23 <input placeholder="Email" onChange={(e) => setEmail(e.target.value)} required />
24 <input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} required />
25 <button type="submit">Login</button>
26 </form>
27);
28}
29
These Pages will allow users to sign up and log in using their email and password. The createUserWithEmailAndPassword
and signInWithEmailAndPassword
functions from the Firebase SDK handle the authentication process.
Sign Out or Logout button
You can place this button anywhere in your app:
.tsx
1'use client';
2import { signOut } from 'firebase/auth';
3import { auth } from '@/lib/firebase';
4
5export default function LogoutButton() {
6const handleLogout = async () => {
7 await signOut(auth);
8 alert('Logged out!');
9};
10
11return <button onClick={handleLogout}>Logout</button>;
12}
By now, you've successfully implemented a basic email/password authentication flow using Firebase with Next.js 15 app.
Google Login with Firebase in Next.js
Adding Google Sign-In lets users log in with a single click using their Google account. Firebase makes this very easy.
Let's walk through how to set up in your Google authentication in Next.js app.
Make sure you enable Google in Authentication > Sign-in method in firebase console
Add Google Sign-In Function
Create a new component for Google Sign-In in your project:
.tsx
1'use client';
2import { signInWithPopup, GoogleAuthProvider } from 'firebase/auth';
3import { auth } from '@/lib/firebase';
4
5export default function GoogleLoginButton() {
6const googleProvider = new GoogleAuthProvider();
7const handleGoogleLogin = async () => {
8 try {
9 await signInWithPopup(auth, googleProvider);
10 alert('Logged in with Google!');
11 } catch (error) {
12 console.error(error);
13 alert('Google login failed.');
14 }
15};
16
17return (
18 <button onClick={handleGoogleLogin} className="bg-red-500 text-white px-4 py-2 rounded">
19 Continue with Google
20 </button>
21);
22}
23
You can place this GoogleLoginButton on your login or signup page for optional login methods.
Protecting Routes & Displaying User Info
Once users can sign up or log in, the next step is to protect sensitive pages (like dashboards) and show their information.
Why Protect Routes?
Imagine you have a /dashboard page that shows personal data. You don't want someone accessing it by typing the URL if they haven't logged in. So, you'll add logic that:
- Checks if the user is authenticated
- Redirects them to /login if they aren't
How Firebase Handles Auth State
Firebase has a built-in method called onAuthStateChanged() that lets you listen to the user's login state. It tells you whether someone is logged in or not — and gives you their user info.
We'll wrap this in a reusable custom hook: useAuth
.
Create a file: hooks/useAuth.ts
.ts
1'use client';
2import { useEffect, useState } from 'react';
3import { onAuthStateChanged, User } from 'firebase/auth';
4import { auth } from '@/lib/firebase';
5
6export default function useAuth() {
7const [user, setUser] = useState<User | null>(null);
8const [loading, setLoading] = useState(true);
9
10useEffect(() => {
11 const unsubscribe = onAuthStateChanged(auth, (user) => {
12 setUser(user);
13 setLoading(false);
14 });
15
16 return () => unsubscribe();
17}, []);
18
19return { user, loading };
20}
Create a Protected Page (e.g., Dashboard)
.ts
1'use client';
2import useAuth from '@/hooks/useAuth';
3import { useRouter } from 'next/navigation';
4
5export default function DashboardPage() {
6const { user, loading } = useAuth();
7const router = useRouter();
8
9if (loading) return <p>Loading...</p>;
10if (!user) {
11 router.push('/login');
12 return null;
13}
14
15return (
16 <div className="p-6">
17 <h1 className="text-2xl font-bold">Welcome to your Dashboard</h1>
18 <p>Email: {user.email}</p>
19 {user.displayName && <p>Name: {user.displayName}</p>}
20 </div>
21);
22}
23
If the user isn't logged in, they'll be redirected to /login.
Displaying User Info
Once the user is authenticated, Firebase provides details like:
-
user.email
-
user.displayName
-
user.uid
-
user.photoURL
.ts
1'use client';
2import useAuth from '@/hooks/useAuth';
3
4export default function UserInfo() {
5const { user } = useAuth();
6
7if (!user) return null;
8
9return (
10 <div className="text-right">
11 <p className="font-semibold">{user.displayName || 'User'}</p>
12 <p className="text-sm text-gray-500">{user.email}</p>
13 </div>
14);
15}
You can show this data in places like the dashboard, navbar, or profile page.
Frequently Asked Questions
-
Q: Is Firebase Authentication free to use?
A: Yes, Firebase Authentication has a generous free tier that supports Email/Password, Google, GitHub, and other providers. It's suitable for small to medium-sized projects.
-
Q: Do I need to use a backend with Firebase Authentication?
A: Not necessarily. Firebase handles authentication and session management for you on the frontend. However, if you want secure data access or custom logic, a backend is recommended.
-
Q: Can I use Firebase Authentication with the App Router in Next.js 15?
A: Yes! Firebase Authentication works perfectly with the App Router. You just need to manage the auth state inside Client Components using Firebase's
onAuthStateChanged
. -
Q: Can I use Firebase with TypeScript in Next.js?
A: Absolutely! Firebase provides full TypeScript support. You can type auth responses like User, UserCredential, etc., for better DX.
Conclusion
In this guide, you learned how to integrate Firebase Authentication with Next.js — from setting up the project and initializing Firebase to implementing Google Sign-In and protecting routes.
Firebase makes it easy to handle authentication with minimal backend work, while Next.js 15's App Router allows for a modern, flexible structure. Whether you're building a personal project or a production-ready app, this setup gives you everything you need to securely authenticate users and create a smooth user experience.
Now that your auth system is ready, you can:
-
Add other providers like GitHub, Facebook, or Apple
-
Integrate Firestore for user data storage
-
Secure backend APIs using Firebase Admin SDK
The possibilities are endless — and you're just getting started.
If you found this article helpful, feel free to share it with others who may benefit from it!