Published on

How to Integrate Firebase with Next.js 15 for Real-Time Apps

Integrating Firebase with Next.js 15 allows you to build real-time applications in under 30 minutes by syncing a cloud database with a high-performance React framework. This combination enables instant data updates across all connected users without manual page refreshes, making it ideal for chat apps, live dashboards, and collaborative tools. You can achieve a fully functional real-time connection by using the Firebase SDK (Software Development Kit) alongside Next.js Client Components and the onSnapshot listener.

Why combine Firebase with Next.js 15?

Next.js 15 is a powerful framework built on top of React 19 that handles both the front-end and back-end of your website. It excels at speed and SEO (Search Engine Optimization), but it requires an external database to store user information or live messages.

Firebase acts as your "Backend-as-a-Service" (BaaS), providing a managed database called Firestore. Firestore is a NoSQL database, meaning it stores data in flexible, JSON-like documents rather than rigid tables.

When these two tools work together, Firebase handles the heavy lifting of live data syncing while Next.js ensures your interface is fast and responsive. This setup removes the need for you to manage your own servers or write complex WebSocket code for live updates.

What will you need to get started?

Before writing code, ensure you have a few basic tools installed on your computer. You will need a code editor like VS Code and a recent version of Node.js (version 20.0 or higher is recommended for 2026 standards).

  • Node.js & npm: The environment and package manager used to run JavaScript on your machine.
  • A Google Account: Required to access the Firebase Console.
  • Terminal Knowledge: You should know how to open your terminal and paste basic commands.
  • Next.js 15: We will use the latest stable version.
  • Firebase SDK 11+: The latest version of the Firebase library for JavaScript.

Step 1: How do you create a Firebase project?

First, you need to set up a home for your data in the cloud. Visit the Firebase Console and click "Add project" to begin.

Give your project a name, click through the setup screens, and wait for the dashboard to load. Once inside, click the "Web" icon (it looks like </>) to register your application.

Firebase will provide you with a firebaseConfig object containing keys and IDs. Keep this window open or copy the code snippet, as you will need these credentials to connect your Next.js app to the database.

Step 2: How do you initialize Next.js 15?

Open your terminal and run the following command to create a brand new Next.js project. We will use the latest defaults, including TypeScript for better error checking and Tailwind CSS for styling.

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

During the setup, choose these options:

  • TypeScript: Yes (This helps catch bugs before they happen).
  • ESLint: Yes.
  • Tailwind CSS: Yes.
  • src/ directory: Yes.
  • App Router: Yes (This is the modern way to build Next.js apps).
  • Import alias: Yes.

Once the installation finishes, move into your project folder by typing cd my-realtime-app. Now, install the Firebase package by running npm install firebase.

Step 3: How do you configure the Firebase connection?

You need to tell Next.js how to talk to your specific Firebase project. Inside your src folder, create a new folder called lib and a file inside it named firebase.ts.

Copy the following code into firebase.ts, replacing the placeholders with the actual keys from your Firebase Console.

// Import the functions you need from the SDKs
import { initializeApp, getApps } from "firebase/app";
import { getFirestore } from "firebase/firestore";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT.appspot.com",
  messagingSenderId: "YOUR_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase only if it hasn't been initialized already
const app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];

// Export the database service
export const db = getFirestore(app);

Step 4: How do you set up the Firestore Database?

Go back to your Firebase Console and click on "Firestore Database" in the left-hand menu. Click "Create database," choose a location near you, and start in Test Mode.

CRITICAL SECURITY WARNING: Test Mode sets your security rules to allow read, write: if true;. This is a major security risk because anyone on the internet can delete or steal your data. Never use these settings for a real application with sensitive information; always update your rules before launching.

Create a "Collection" named items. Add one document manually with a field called name (string) and a value like "Hello Firebase" so we have something to display.

Step 5: How do you build the real-time component?

Now we will create a page that listens for changes in your database. Open src/app/page.tsx and replace the code with this example.

We've found that using the onSnapshot function is the most efficient way to handle live updates because it only sends data when something actually changes.

"use client"; // Required because we are using React hooks

import { useEffect, useState } from "react";
import { db } from "@/lib/firebase"; 
import { collection, onSnapshot, query } from "firebase/firestore";

// Define what an Item looks like
interface Item {
  id: string;
  name: string;
}

export default function RealTimePage() {
  const [items, setItems] = useState<Item[]>([]);

  useEffect(() => {
    // Create a reference to our 'items' collection
    const q = query(collection(db, "items"));

    // Listen for real-time updates
    const unsubscribe = onSnapshot(q, (querySnapshot) => {
      const itemsArray: Item[] = [];
      querySnapshot.forEach((doc) => {
        // Push each document data into our array
        itemsArray.push({ ...(doc.data() as { name: string }), id: doc.id });
      });
      setItems(itemsArray);
    });

    // Clean up the listener when the page closes
    return () => unsubscribe();
  }, []);

  return (
    <main className="p-10">
      <h1 className="text-2xl font-bold mb-4">Real-Time List</h1>
      <ul>
        {items.map((item) => (
          <li key={item.id} className="border-b py-2">{item.name}</li>
        ))}
      </ul>
    </main>
  );
}

What are the common gotchas for beginners?

One common mistake is forgetting the "use client" directive at the top of your file. Firebase listeners rely on React hooks like useEffect, which only run in the browser, not on the server.

Another issue involves "Ghost Listeners." If you don't return the unsubscribe() function inside your useEffect, the app will keep listening even after the user leaves the page, which can slow down the browser.

Don't worry if your data doesn't appear immediately. Check your browser's console (Right-click > Inspect > Console) to see if there are any "Permission Denied" errors, which usually mean your Firebase security rules have expired.

Next Steps

Now that you have live data flowing into your Next.js app, you can try adding a form to send data back to Firebase using the addDoc function. You might also explore Firebase Authentication to let users sign in before they can see the live list.

It is normal to feel overwhelmed by all the configuration options at first. The key is to get the basic connection working before adding complex features like user profiles or file uploads.

For more information, visit the official Next.js documentation.


Read the Next.js Documentation