Logo

Real-Time Data Updates with Firebase Firestore in Next.js

Monday, January 27, 2025

Real-time data has become a cornerstone of modern web applications, enabling instant updates and dynamic user experiences. Firebase Firestore is a powerful NoSQL database that provides real-time data syncing, making it an excellent choice for projects requiring live updates.

In this tutorial, we’ll guide you through integrating Firebase Firestore with a Next.js application to display real-time data updates. By the end, you’ll have a fully functional example of a real-time messaging app, a perfect starting point for your own projects.


Setting Up Firebase

Before we dive into coding, let’s get Firebase ready for our project:

Create a Firebase Project:

  • Go to the Firebase Console.
  • Click "Add Project" and follow the setup wizard.
  • Enable Firestore:

  • Navigate to the Firestore Database section in the console.
  • Select "Create Database" and choose "Start in production mode."
  • Set up your preferred Cloud Firestore location.
  • Generate Configuration Keys:

  • In the "Project Settings," find your Firebase SDK config under "Your apps."
  • Copy the configuration keys—we’ll use these in our app.

  • Installing Dependencies

    Next, let’s set up Firebase in our Next.js project:

    Install Firebase:

    Language: bash
    npm install firebase

    Configuring Firebase in Next.js

    To connect Firebase to our Next.js app, create a dedicated firebase.js file for configuration:

    Language: javascript
    // firebase.js
    import { initializeApp } from "firebase/app";
    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",
    };
    
    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);
    
    export { db };

    This setup ensures Firestore is initialized and ready to use throughout your app.


    Setting Up Firestore Data

    Now that Firebase is configured, we’ll prepare some sample data:

    Create a Collection:

  • In Firestore, create a collection named messages.
  • Add Documents:

  • Each document will have fields like:
  • Language: json
    {
      "text": "Hello, world!",
      "timestamp": "2025-01-26T12:00:00Z"
    }

    Displaying Real-Time Data in a Next.js Component

    Let’s create a component to display the messages from Firestore in real time:

    Language: javascript
    import { useState, useEffect } from "react";
    import { collection, onSnapshot } from "firebase/firestore";
    import { db } from "../firebase";
    
    const Messages = () => {
      const [messages, setMessages] = useState([]);
    
      useEffect(() => {
        const unsubscribe = onSnapshot(collection(db, "messages"), (snapshot) => {
          setMessages(snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() })));
        });
        return () => unsubscribe();
      }, []);
    
      return (
        <ul>
          {messages.map((message) => (
            <li key={message.id}>{message.text}</li>
          ))}
        </ul>
      );
    };
    
    export default Messages;

    This component uses Firestore’s real-time listener (onSnapshot) to keep the messages state updated as changes occur in the database.


    Styling the Component

    To improve the user experience, let’s style the message list using Tailwind CSS:

    Language: html
    <ul className="space-y-2">
      {messages.map((message) => (
        <li key={message.id} className="bg-blue-100 p-2 rounded shadow">
          {message.text}
        </li>
      ))}
    </ul>

    This adds padding, rounded corners, and a subtle shadow to each message, enhancing the visual appeal.


    Testing Real-Time Updates

    To see real-time updates in action:

  • Open the Firestore console and add a new document to the messages collection.
  • Watch the new message appear instantly in your app—no refresh needed!

  • Conclusion

    By combining Firebase Firestore with Next.js, you can build powerful real-time applications with minimal effort. In this tutorial, we demonstrated how to:

  • Set up Firebase Firestore.
  • Create and manage real-time listeners.
  • Style and display data dynamically in a Next.js app.
  • Real-time data opens up a world of possibilities, from chat apps to live dashboards. Explore Firestore further to implement advanced features like querying, offline persistence, and security rules.

    Blog/Terms/Privacy policy/Tools/Twitter/Instagram/TikTok