Realtime

Receive the information from Supabase, right when it happens.


With Supabase Realtime, you are able to directly receive incoming changes to the database. You can listen to updates, inserts, deletes, etc. This allows you to update the page for a user, without having to reload or refresh the page.

Supabase Realtime

Example of Realtime using Supabase.

supaboost darkmode supabase realtime

In the above example, you can see that a new row is added, an update is passed through and the row is deleted. This is visible, because for the table users, user_info and user_roles, I have enabled realtime. You can also include this, to make sure you update the information for the user, if a database mutation happens.

To do this, lets go over the steps.

Enabling Supabase Realtime

  1. Open https://supabase.com
  2. Open your project on Supabase
  3. Go to the database
  4. Select tables (from the overview)
  5. Edit the table you want to update supabase realtime setup supaboost
  6. Enable Realtime by clicking the checkbox supabase enable realtime for table
  7. Click Save

Adding Supabase Realtime to the code

In the template, we have added the functionality already. This RealtimeTodo is taken from the Supabase with cookies auth video playlist (Link).

You can call the following code in a Client Component, to render the data in realtime:

 const supabase = createClientComponentClient<Database>();
  const router = useRouter();
 
  useEffect(() => {
    const channel = supabase
      .channel("realtime todos") // name of the Realtime subscription to the database
      .on(
        "postgres_changes", 
        {
          event: "*", // subscribing to all changes
          schema: "public", // public, as that is where you create your tables
          table: "todos", // table to subscribe to
        },
        () => {
          router.refresh(); // Action that is done, when mutation happens
        }
      )
      .subscribe();
 
    return () => {
      supabase.removeChannel(channel);
    };
  }, [supabase, router]);

This code will wait for any table mutation in Todos, then refresh the component for the user.

Please note: Supabase free tier only allows 200 realtime subscriptions. So think properly before adding Realtime to all of your tables. It is advised to only use it on the most important tables.