/firebase-tutorials

How to use Firebase auth with Next.js?

Discover a step-by-step guide to integrating Firebase auth in your Next.js app. From project setup to implementing a signup form, boost your app’s authentication today.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to use Firebase auth with Next.js?

 

Step 1: Set Up Your Firebase Project

 

  1. Go to the Firebase Console and log in with your Google account.
  2. Click on "Add Project" to create a new Firebase project.
  3. Enter a name for your project and click "Continue."
  4. Follow the setup steps and click "Create Project."
  5. Once your project is ready, click "Continue" to navigate to the Firebase project dashboard.
  6. In the Firebase project dashboard, click on "Authentication" from the side menu to open the Authentication section.
  7. Click on the "Get Started" button to enable Firebase Authentication.
  8. Under the "Sign-in Method" tab, enable the authentication providers you intend to use, such as Email/Password, Google, etc.

 

Step 2: Create a Next.js Project

 

Open your terminal and run:

npx create-next-app@latest my-firebase-app

 

Step 3: Install Firebase SDK

 

Navigate into your project directory and install the Firebase SDK:


cd my-firebase-app
npm install firebase

 

Step 4: Configure Firebase in Next.js

 

  1. Create a new file named firebaseConfig.js in the root of your Next.js project.
  2. In firebaseConfig.js, add the following configuration:

import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

// Your web app's Firebase configuration
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,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Firebase Authentication and get a reference to the service
export const auth = getAuth(app);
  1. Replace the placeholders in firebaseConfig with your actual Firebase project credentials from the Firebase Console.
  2. It is recommended to use environment variables for these keys. Create a .env.local file in the root of your project directory and add:

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-messaging-sender-id
NEXT_PUBLIC_FIREBASE_APP_ID=your-app-id

 

Step 5: Implement Authentication Logic

 

  1. Create a new directory named auth inside the pages directory.
  2. Create a new file named signup.js inside the auth directory.
  3. Add a simple signup form to signup.js:

import { useState } from 'react';
import { auth } from '../firebaseConfig';
import { createUserWithEmailAndPassword } from 'firebase/auth';

const Signup = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);

  const handleSignup = async (e) => {
    e.preventDefault();
    try {
      const userCredential = await createUserWithEmailAndPassword(auth, email, password);
      console.log('User signed up:', userCredential.user);
    } catch (error) {
      setError(error.message);
    }
  };

  return (
    

Sign Up

setEmail(e.target.value)} placeholder="Email" required /> setPassword(e.target.value)} placeholder="Password" required />
{error &&

{error}

}
); }; export default Signup;

 

Step 6: Run and Test Your Application

 

In the terminal, run your application with:


npm run dev
  1. Open your browser and navigate to http://localhost:3000/auth/signup.
  2. Test the signup functionality by entering an email and password.
  3. Implement similar logic for other authentication features like login and logout by creating additional pages in the auth directory.

 

Conclusion

 

Congratulations! You have successfully integrated Firebase Authentication with a Next.js application. You can now expand on this setup to include additional authentication services, handle authentication state, and implement more complex application flows based on your project's requirements.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022