/supabase-tutorials

How to use subscriptions in Supabase?

Learn how to set up real-time subscriptions in Supabase—from project and table creation to client integration and event handling.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to use subscriptions in Supabase?

 

Step 1: Setup Supabase Project

 

To get started, you'll need to have a Supabase project. If you haven't already set one up, follow these instructions:

Go to the Supabase website and sign up or log in.

Once logged in, create a new project by clicking the "New Project" button.

Fill in the project details like database password, project name, and desired region. Then, proceed to create the project.

 

Step 2: Setup Database Table

 

Before using subscriptions, you need a table to subscribe to. You can create this directly from the Supabase dashboard.

Navigate to the "Table Editor" in the Supabase dashboard.

Click "New Table" to create a new table. For example, a "messages" table with columns like "id", "content", and "created_at".

Ensure you have a primary key set (usually an "id" column) and that all necessary columns are configured.

Click "Save" to create the table.

 

Step 3: Install Supabase Client Library

 

For interacting with Supabase in your application, you'll need to install the Supabase client library.

If using npm:

npm install @supabase/supabase-js

If using yarn:

yarn add @supabase/supabase-js

 

Step 4: Initialize Supabase Client in Your Application

 

Before subscribing to database changes, initialize the Supabase client in your application with the API keys from the Supabase project settings.

Grab your Supabase URL and the public API key from your Supabase dashboard under "Settings" -> "API".

In your application code, initialize the client:


import { createClient } from '@supabase/supabase-js';

const SUPABASE\_URL = 'https://your-project.supabase.co';
const SUPABASE_ANON_KEY = 'your-anon-public-api-key';

const supabase = createClient(SUPABASE_URL, SUPABASE_ANON\_KEY);

 

Step 5: Subscribe to Database Changes

 

Now, set up a subscription to a table to listen for changes. For instance, you might want to watch for new rows added to the "messages" table.

Use the Supabase client to set up a subscription:


const subscription = supabase
  .from('messages')
  .on('INSERT', (payload) => {
    console.log('New message:', payload.new);
  })
  .subscribe();

This example listens for INSERT operations on the "messages" table and logs the new items.

 

Step 6: Manage and Cleanup Subscriptions

 

When your app component unmounts or when you need to unsubscribe, ensure you remove the subscription to avoid memory leaks:


supabase.removeSubscription(subscription);

You might incorporate this in a cleanup function in components that use hooks or lifecycle methods.

 

Step 7: Testing the Subscription

 

To ensure everything is set up correctly, perform an insert operation to the "messages" table to see if the subscription logs the changes.

Add a new message using the Supabase dashboard or directly via the client:


const { data, error } = await supabase
  .from('messages')
  .insert([{ content: 'Hello, world!', created\_at: new Date() }]);

Check your application logs to verify that the new message is being captured by the subscription.

 

Step 8: Handle Subscription Events

 

Depending on your application's needs, you might handle different types of events like 'UPDATE', 'DELETE', etc. Adjust the event type as required in your subscription:


const updateSubscription = supabase
  .from('messages')
  .on('UPDATE', (payload) => {
    console.log('Updated message:', payload.new);
  })
  .subscribe();

This example listens for update events instead of insertions.

 

By integrating these steps, you'll effectively implement and manage real-time subscriptions with Supabase in your application.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022