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:
Step 1: Set Up a Supabase Project
Step 2: Initialize Your Frontend Project
Now, let’s set up a basic frontend to connect to Supabase.
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:
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.
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:
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
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.