Estimated Read Time: 5 min

Next.js Authentication with Firebase Auth
Introduction to Firebase Authentication
Authentication is a crucial aspect of any web application, ensuring that only authorized users can access certain features or data. In this tutorial, we'll explore how to implement authentication in a Next.js application using Firebase Authentication. Firebase provides a robust set of tools for managing user authentication, making it a popular choice among developers.
Creating a Firebase Account and Obtaining API Keys
Before we can start using Firebase Authentication in our Next.js project, we need to create a Firebase account and obtain the necessary API keys. Head over to the Firebase console and create a new project. Once the project is created, navigate to the project settings and locate the API keys section. Here, you'll find the keys needed to authenticate your application with Firebase services.
Configuring Firebase Sign-In Methods
Firebase supports various sign-in methods, including email/password, Google, Facebook, and more. To configure the sign-in methods for your project, navigate to the Authentication section in the Firebase console. Here, you can enable and customize the sign-in providers you want to use. For example, to enable Google sign-in, simply click on the Google provider and follow the setup instructions.
Adding Firebase Environment Variables to Your Next.js Project
To securely store your Firebase API keys and other configuration values, we'll use environment variables in our Next.js project. Create a .env.local
file in the root of your project and add your Firebase configuration values like so:
NEXT_PUBLIC_FIREBASE_API_KEY=your-api-key
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-auth-domain
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-storage-bucket
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your-sender-id
NEXT_PUBLIC_FIREBASE_APP_ID=your-app-id
Make sure to replace your-api-key, your-auth-domain, and other placeholders with your actual Firebase configuration values.
Installing the Firebase Library
In order to use Firebase services in our Next.js project, we need to install the Firebase JavaScript SDK. You can do this via npm or yarn:
npm install firebase
or
yarn add firebase
Creating a Firebase Instance in Next.js
To initialize Firebase in our Next.js application, we'll create a separate module to handle Firebase setup. Create a new file called firebase.js in your project's lib directory and add the following code:
import firebase from 'firebase/app';
import 'firebase/auth';
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,
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export default firebase;
This module initializes Firebase using the provided configuration values from the environment variables.
Implementing User Authentication with Firebase
Now that we've set up Firebase in our Next.js project, let's implement user authentication. We'll start by creating a login page where users can sign in using their email and password.
// pages/login.js
import React, { useState } from 'react';
import firebase from '../lib/firebase';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async () => {
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
// User is authenticated, redirect to dashboard or home page
} catch (error) {
console.error('Error signing in:', error);
}
};
return (
<div>
<h1>Login</h1>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default Login;
This code sets up a basic login page where users can enter their email and password to authenticate using Firebase Authentication.
Using Firebase Admin SDK for Server-Side Authentication
In addition to client-side authentication, Firebase also provides an Admin SDK for server-side authentication. This allows you to authenticate users and perform administrative tasks from your backend server.
To use the Firebase Admin SDK, you'll need to install the firebase-admin package:
npm install firebase-admin
or
yarn add firebase-admin
Then, initialize the Admin SDK in your server-side code:
// server.js
import * as admin from 'firebase-admin';
const serviceAccount = require('./path/to/serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://your-project-id.firebaseio.com',
});
// Now you can use admin.auth() to authenticate users and perform admin tasks.
With the Admin SDK, you can authenticate users, manage user data, and perform other administrative tasks directly from your server-side code.
Managing User Data and Realtime Database
Once a user is authenticated with Firebase, you can manage their data using Firebase Realtime Database or Cloud Firestore. These NoSQL databases provide a scalable and flexible way to store user-related information such as profile data, preferences, and more.
To store user data in the Realtime Database, you can use the following approach:
// Save user data to Realtime Database after successful authentication
firebase.auth().onAuthStateChanged((user) => {
if (user) {
firebase.database().ref(`users/${user.uid}`).set({
email: user.email,
displayName: user.displayName,
// Add additional user data as needed
});
}
});
This code listens for changes in the authentication state and saves user data to the Realtime Database when a user signs in.
Building a Login Page and Sign-Up Flow
In this section, we'll build a complete login page and sign-up flow using Firebase Authentication in our Next.js application. The login page will allow existing users to sign in, while the sign-up flow will enable new users to create an account.
// pages/login.js
import React, { useState } from 'react';
import { useRouter } from 'next/router';
import firebase from '../lib/firebase';
const Login = () => {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async () => {
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
router.push('/dashboard');
} catch (error) {
console.error('Error signing in:', error);
}
};
return (
<div>
<h1>Login</h1>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default Login;
In this code, we've implemented a basic login page with email/password authentication using Firebase. When the user successfully logs in, they are redirected to the dashboard page.
For the sign-up flow, we can create a separate page similar to the login page, allowing users to register for a new account using their email and password.
Conclusion
In this tutorial, we've learned how to integrate Firebase Authentication into a Next.js application to implement user authentication. We covered the setup process, configuring sign-in methods, managing user data, and building a complete login page and sign-up flow. With Firebase Authentication, you can easily add secure authentication to your Next.js projects, enabling users to access your application's features with confidence.