πŸŽ‰ Happy New Year 2025! πŸŽ‰

🌟 Start the year with inspiration and innovation. Check out our latest tech blogs and tools to make 2025 your most productive year yet! πŸš€

~/blog/how-to-integrate-firebase-into-a-nextjs-application
Published on

How to Integrate Firebase into a Next.js Application

1235 words7 min read0
Views
Authors
  • avatar
    Name
    codewithininsight
    Twitter
    @

In this blog, I'll guide you through integrating Firebase into your Next.js application for features like Authentication, Firestore, and Hosting.


Step 1: Set Up Firebase Project

  • Go to the Firebase Console.
  • Create a new project or select an existing one.
  • Navigate to Project Settings > General and note the configuration keys:
    apiKey, authDomain, projectId, etc.

Step 2: Install Firebase SDK

Install the Firebase JavaScript SDK in your Next.js project.

npm install firebase

Step 3: Initialize Firebase

  • Create a Firebase utility file for easy access across your application. Save this file as lib/firebase.js

import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from 'firebase/firestore'

const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
};

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

// Export modules for use
const auth = getAuth(app);
const db = getFirestore(app);

export { auth, db }

Replace the placeholder values with your Firebase Project Configuration keys.

Step 4: Implement Firebase Authentication

Now that Firebase is initialized, let’s add Google Login functionality using Firebase Authentication.

  • Create a new Login component.
import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { auth } from "@/lib/firebase";

export default function Login() {
  const handleLogin = async () => {
    try {
      const provider = new GoogleAuthProvider();
      const result = await signInWithPopup(auth, provider);
      console.log("User Info:", result.user);
    } catch (error) {
      console.error("Login Error:", error.message);
    }
  };

  return (
    <div>
      <button
        onClick={handleLogin}
        className="rounded-lg bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
      >
        Login with Google
      </button>
    </div>
  );
}

Step 5: Store Data in Firestore

Once users log in, save their details to Firestore.

import { doc, setDoc } from 'firebase/firestore'
import { db } from '@/lib/firebase'

async function saveUserData(user) {
  const userRef = doc(db, 'users', user.uid)
  await setDoc(userRef, {
    name: user.displayName,
    email: user.email,
    createdAt: new Date(),
  })
}

Example Integration:

Update the login function to save user data after successful login.

import { signInWithPopup, GoogleAuthProvider } from 'firebase/auth'
import { auth, db } from '@/lib/firebase'
import { doc, setDoc } from 'firebase/firestore'

export default function Login() {
  const handleLogin = async () => {
    try {
      const provider = new GoogleAuthProvider()
      const result = await signInWithPopup(auth, provider)

      const user = result.user
      const userRef = doc(db, 'users', user.uid)

      await setDoc(userRef, {
        name: user.displayName,
        email: user.email,
        createdAt: new Date(),
      })

      console.log('User data saved successfully!')
    } catch (error) {
      console.error('Login Error:', error.message)
    }
  }

  return (
    <div>
      <button
        onClick={handleLogin}
        className="rounded-lg bg-green-500 px-4 py-2 text-white hover:bg-green-600"
      >
        Login with Google
      </button>
    </div>
  )
}

Step 6: Fetch Data from Firestore

Retrieve data from Firestore using getDocs:

import { collection, getDocs } from 'firebase/firestore'
import { db } from '@/lib/firebase'

async function fetchUsers() {
  const querySnapshot = await getDocs(collection(db, 'users'))
  const users = querySnapshot.docs.map((doc) => doc.data())
  console.log(users)
}

Step 7: Deploy to Firebase Hosting

Once your Next.js project is ready, you can deploy it to Firebase Hosting for a seamless, scalable, and fast hosting experience.


1. Install Firebase CLI

First, install the Firebase Command Line Interface (CLI) globally on your system:

npm install -g firebase-tools

2. Log in to your Firebase account:

firebase login

3. Initialize Firebase Hosting:

firebase init hosting
  • Select your Firebase project.
  • Set the public directory to out (for Next.js static exports).

4. Initialize Firebase Hosting:

npm run build
npm run export

5. Deploy the site:

firebase deploy

Summary

Congratulations! πŸŽ‰ You have successfully integrated Firebase into your Next.js application. You can now:

  • Use Firebase Authentication to log in users effortlessly.
  • Store and fetch data securely using Firestore.
  • Deploy your site seamlessly with Firebase Hosting for fast and reliable performance.

Your Next.js application is now enhanced with Firebase capabilities, making it scalable, secure, and ready for production. πŸš€

If you have any questions or run into issues, feel free to drop a comment below or check out the Firebase Documentation for further guidance.