Nextbase Docs
Nextbase Docs
HomeBlogWelcome to Nextbase v3!Getting Started with NextBaseQuick setup
Admin Panel GuideAsynchronous Data Fetching GuideAuthenticationCreating Admin Panel PageCreating Docs PageCreating in-app notificationsCreating a new Supabase tableCreating Protected PageCreating Public Dynamic PageCreating Public Static PageHandling Realtime Data With SupabaseManaging UsersMutating Data With SupabaseOptimizing Data Operations in Next.js 14 and SupabaseRow Level SecurityStripe Setup in Nextbase UltimateWriting Integration Tests with PlaywrightWriting Unit Tests with Vitest
Guides

Handling Realtime Data With Supabase

Learn how to handle realtime data in Supabase using server actions and react query

In this guide, we'll learn how to handle realtime data in Supabase using server actions and react query. We implemented notifications as a realtime feature in Nextbase Ultimate and we can use that as a reference.

Supabase Realtime

Supabase provides a realtime service which can be used to listen to changes in your database. When used with a React client component useEffect it looks something like this:

src/components/ui/NavigationMenu/Notifications.tsx

import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';
import {
  getPaginatedNotifications,
  getUnseenNotificationIds,
  readAllNotifications,
  seeNotification,
} from './fetchClientNotifications';

const useUnseenNotificationIds = (userId: string) => {
  const { data, refetch } = useQuery(
    ['unseen-notification-ids', userId],
    async () => {
      return getUnseenNotificationIds(userId);
    },
    {
      initialData: [],
    },
  );
useEffect(() => {
  const channelId = `user-notifications:${userId}`;
  const channel = supabaseClient
    .channel(channelId)
    .on(
      'postgres_changes',
      {
        event: 'INSERT',
        schema: 'public',
        table: 'user_notifications',
        filter: 'user_id=eq.' + userId,
      },
      () => {
        refetch();
      },
    )
    .on(
      'postgres_changes',
      {
        event: 'UPDATE',
        schema: 'public',
        table: 'user_notifications',
        filter: 'user_id=eq.' + userId,
      },
      (payload) => {
        refetch();
      },
    )
    .subscribe();
  return () => {
    channel.unsubscribe();
  };
}, [refetch, userId]);

In the above code, we are listening to changes in the user_notifications table and refetching the data when a change occurs. Depending on the scenario, you can also just use the payload from the realtime data to setState or update a react query cache directly.

Creating Public Static Page

Guide on how to create a public static page in a Next.js application such as in Nextbase.

Managing Users

Learn how to manage users with Supabase

On this page

Supabase Realtime