AskHandle Blog
How to Implement Firebase Authentication in Next.js

How to Implement Firebase Authentication in Next.js
Are you looking to incorporate Firebase Authentication into your Next.js application? Firebase offers powerful authentication features that integrate seamlessly with Next.js. This article will guide you through the process of setting up Firebase Authentication in your Next.js project step-by-step.
Getting Started
Ensure you have a Firebase project set up. If you don't have one yet, create a new project in the Firebase Console. Once your Firebase project is ready, follow these steps:
Step 1: Install Firebase SDK
First, install the Firebase SDK in your Next.js project by running the following command:
1npm install firebaseStep 2: Initialize Firebase
Next, initialize Firebase in your Next.js application. Create a new file called firebaseClient.js in the root of your project and add the following code:
1import firebase from 'firebase/app';
2import 'firebase/auth';
3
4const firebaseConfig = {
5 apiKey: 'YOUR_API_KEY',
6 authDomain: 'YOUR_AUTH_DOMAIN',
7 projectId: 'YOUR_PROJECT_ID',
8 storageBucket: 'YOUR_STORAGE_BUCKET',
9 messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
10 appId: 'YOUR_APP_ID'
11};
12
13if (!firebase.apps.length) {
14 firebase.initializeApp(firebaseConfig);
15}
16
17export default firebase;Replace 'YOUR_API_KEY', 'YOUR_AUTH_DOMAIN', 'YOUR_PROJECT_ID', 'YOUR_STORAGE_BUCKET', 'YOUR_MESSAGING_SENDER_ID', and 'YOUR_APP_ID' with your Firebase project's configuration.
Step 3: Create Firebase Authentication Functions
You can create functions to handle Firebase Authentication in your application. For example, create a signInWithGoogle function to enable Google Sign-In:
1import firebase from './firebaseClient';
2
3const signInWithGoogle = () => {
4 const provider = new firebase.auth.GoogleAuthProvider();
5 return firebase.auth().signInWithPopup(provider);
6};
7
8export { signInWithGoogle };You can create more functions for other authentication methods like email/password and Facebook, depending on your requirements.
Step 4: Integrate Authentication in Next.js Pages
Integrate Firebase Authentication in your Next.js pages. For instance, create a Login page that allows users to sign in with Google:
1import { signInWithGoogle } from '../firebaseClient';
2
3const Login = () => {
4 const handleGoogleSignIn = async () => {
5 try {
6 await signInWithGoogle();
7 // Redirect or show a success message
8 } catch (error) {
9 // Handle errors
10 }
11 };
12
13 return (
14 <div>
15 <h1>Login Page</h1>
16 <button onClick={handleGoogleSignIn}>Sign in with Google</button>
17 </div>
18 );
19};
20
21export default Login;Following these steps helps implement Firebase Authentication in your Next.js application, providing a user-friendly login experience.
Additional Considerations
Secure Routes
To protect certain routes and restrict access to authenticated users, create a Higher Order Component (HOC) to check the user's authentication status. Here's an example:
1import { useRouter } from 'next/router';
2import { useAuthState } from 'react-firebase-hooks/auth';
3import firebase from './firebaseClient';
4
5const AuthCheck = ({ children }) => {
6 const [user, loading] = useAuthState(firebase.auth());
7 const router = useRouter();
8
9 if (loading) {
10 return <div>Loading...</div>;
11 }
12
13 if (!user) {
14 router.push('/login');
15 return null;
16 }
17
18 return children;
19};
20
21export default AuthCheck;Wrap protected routes with this AuthCheck component to ensure that only authenticated users can access them.
Real-time Authentication Status
For real-time user authentication status, use Firebase's onAuthStateChanged method. Here's an example:
1import { useEffect, useState } from 'react';
2import firebase from './firebaseClient';
3
4const AuthStatus = () => {
5 const [user, setUser] = useState(null);
6
7 useEffect(() => {
8 const unsubscribe = firebase.auth().onAuthStateChanged((authUser) => {
9 setUser(authUser);
10 });
11
12 return unsubscribe;
13 }, []);
14
15 return (
16 <div>
17 {user ? `Welcome, ${user.displayName}!` : 'Please sign in.'}
18 </div>
19 );
20};
21
22export default AuthStatus;Include the AuthStatus component in your layout to provide users with real-time feedback on their authentication status.
This guide provides clear instructions for implementing Firebase Authentication in a Next.js application. Customize and expand upon these examples to fit your specific needs.