Setting Up a Real-Time Database with Supabase

Friday, January 24, 2025

In today’s fast-paced world, real-time applications are everywhere—think live chats, collaborative tools, and dynamic dashboards. Building these features might seem complex, but Supabase makes it simple. As an open-source alternative to Firebase, Supabase offers powerful real-time capabilities with minimal setup.

In this guide, we’ll walk you through how to set up a real-time database using Supabase. By the end, you’ll have a basic app that updates in real-time whenever data changes in your database.


Prerequisites

Before we dive in, here’s what you’ll need:

  • A Supabase account (sign up for free if you don’t already have one).
  • Basic knowledge of JavaScript or TypeScript.
  • Node.js installed locally.
  • (Optional) Familiarity with Next.js for frontend development.

  • Step 1: Set Up a Supabase Project

  • Head over to the Supabase dashboard and create a new project.
  • Choose a project name, region, and password. Supabase will provision a PostgreSQL database for you.
  • Once your project is ready, navigate to the SettingsAPI section. Copy your API URL and anon key, as we’ll need these later.

  • Step 2: Initialize Your Frontend Project

    Now, let’s set up a basic frontend to connect to Supabase.

  • Create a new Next.js app (or use plain HTML/JavaScript if you prefer):
  • Install the Supabase client library:

  • Step 3: Connect to Supabase

    To interact with your Supabase project, you need to initialize the client. Create a new file, supabase.js, and add the following:

    Language: javascript
    import { createClient } from '@supabase/supabase-js';
    
    const supabaseUrl = 'YOUR_SUPABASE_URL';
    const supabaseKey = 'YOUR_ANON_KEY';
    export const supabase = createClient(supabaseUrl, supabaseKey);

    Replace YOUR_SUPABASE_URL and YOUR_ANON_KEY with the values you copied from your Supabase dashboard.


    Step 4: Create a Table and Add Data

    Next, we need a database table to store and manage data.

  • Go to the Table Editor in your Supabase dashboard and create a table named messages.
  • Add the following columns:
  • Save your changes and insert some sample data into the table.

  • Step 5: Enable Real-Time Subscriptions

    Supabase makes it easy to subscribe to real-time changes in your database.

    In your frontend, update your index.js or App.js file with the following code:

    Language: javascript
    import { supabase } from './supabase';  
    import { useState, useEffect } from 'react';  
    
    export default function App() {  
      const [messages, setMessages] = useState([]);  
    
      useEffect(() => {  
        // Fetch existing messages  
        async function fetchMessages() {  
          const { data } = await supabase.from('messages').select('*');  
          setMessages(data);  
        }  
        fetchMessages();  
    
        // Listen for changes in the 'messages' table  
        const channel = supabase  
          .channel('realtime-messages')  
          .on('postgres_changes', { event: '*', schema: 'public', table: 'messages' }, (payload) => {  
            console.log('Change received!', payload);  
            if (payload.eventType === 'INSERT') {  
              setMessages((prev) => [...prev, payload.new]);  
            }  
          })  
          .subscribe();  
    
        // Cleanup the subscription when the component unmounts  
        return () => {  
          supabase.removeChannel(channel);  
        };  
      }, []);  
    
      return (  
        <div>  
          <h1>Real-Time Messages</h1>  
          <ul>  
            {messages.map((msg) => (  
              <li key={msg.id}>{msg.content}</li>  
            ))}  
          </ul>  
        </div>  
      );  
    }

    Step 6: Test the Real-Time Features

  • Add a new row to your messages table via the Supabase dashboard or an API call.
  • Observe how the new message immediately appears in your app without requiring a refresh.

  • Conclusion

    Congratulations! You’ve successfully set up a real-time database with Supabase. This basic implementation demonstrates how easy it is to integrate live updates into your applications.

    From here, you can explore additional features like handling updates and deletes, adding authentication, or even building more complex real-time applications.