In this guide, we'll walk through the process of setting up Next.js with Firebase Authentication, complete with code examples to get you started.
Why Next.js with Firebase Authentication?
Next.js provides a powerful framework for building React applications with server-side rendering, static site generation, and seamless client-side routing. Firebase Authentication, on the other hand, offers a comprehensive suite of authentication services, including email/password authentication, social login providers, and more, with built-in security features like OAuth and multi-factor authentication.By integrating Next.js with Firebase Authentication, developers can leverage the scalability, reliability, and security of Firebase while harnessing the flexibility and performance benefits of Next.js.
Getting Started
Before diving into code, ensure you have Node.js installed on your machine. Create a new Next.js project using the following command:npx create-next-app@latest my-next-firebase-app
npm install --save firebase
Setting Up Firebase
1. Create a Firebase Project: Go to the Firebase Console and create a new project.2. Add Firebase to Your Web App: In the Firebase Console, navigate to your project settings and click on "Add app" to add a web app. Follow the instructions to obtain your Firebase configuration object.
3. Enable Authentication: In the Firebase Console, go to the "Authentication" section and enable the sign-in methods you want to use (e.g., Email/Password, Google, etc.).
Integrating Firebase with Next.js
Initialize Firebase: Create a new file `firebase.js` in your Next.js project and initialize Firebase with your Firebase configuration:import firebase from 'firebase/app'; import 'firebase/auth'; const firebaseConfig = { // Your Firebase configuration }; if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig); } export default firebase;
import firebase from '../firebase'; const loginWithGoogle = async () => { const provider = new firebase.auth.GoogleAuthProvider(); try { await firebase.auth().signInWithPopup(provider); // Redirect or perform any desired action upon successful authentication } catch (error) { console.error(error.message); } };
Protecting Routes
To protect certain routes in your Next.js application, you can create a higher-order component (HOC) to check the user's authentication status:import React, { useEffect } from 'react'; import { useRouter } from 'next/router'; import firebase from '../firebase'; const withAuth = (Component) => { const AuthenticatedComponent = (props) => { const router = useRouter(); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged((user) => { if (!user) { router.push('/login'); // Redirect to login page if user is not authenticated } }); return () => unsubscribe(); }, []); return <Component {...props} />; }; return AuthenticatedComponent; }; export default withAuth;
import withAuth from '../utils/withAuth'; const ProtectedPage = () => { return <div>This page is protected!</div>; }; export default withAuth(ProtectedPage);