avatar

sunday

Sunday's Blog

  • 首页
Home nextjs + clerk + supabase + realtime 实时监听数据库更改
文章

nextjs + clerk + supabase + realtime 实时监听数据库更改

Posted 2025-04-6 Updated 2025-04- 6
By sunday
7~9 min read

1.开启realtime.messages策略

在supabase的SQL Editor执行以下命令

create policy "Enable all access for authenticated users"
on "public"."messages"
as PERMISSIVE
for ALL
to authenticated
using (
  true
)

这里的意思是接受登录用户的所有操作

2.创建触发器的函数

在supabase的SQL Editor执行以下命令

create or replace function public.your_table_changes()
returns trigger
language plpgsql
as $$
begin
  perform realtime.broadcast_changes(
    'messages-changes',      -- topic - the topic to which we're broadcasting 在前端用supabse.channel监听的字符串
    TG_OP,                                             -- event - the event that triggered the function
    TG_OP,                                             -- operation - the operation that triggered the function
    TG_TABLE_NAME,                                     -- table - the table that caused the trigger
    TG_TABLE_SCHEMA,                                   -- schema - the schema of the table that caused the trigger
    NEW,                                               -- new record - the record after the change
    OLD                                                -- old record - the record before the change
  );
  return null;
end;
$$;

3.创建触发器

在supabase的SQL Editor执行以下命令

create trigger handle_your_table_changes
after insert or update or delete
on public.your_table
for each row
execute function your_table_changes ();

on public.your_table 改成你要监听更改的表

4.在nextjs中监听

      const clent = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, {
        async accessToken() {
          return session?.getToken() || '';
        },

        realtime: {
          // timeout: 30000,
          accessToken: async () => {
            return session?.getToken() || '';
          },
          heartbeatIntervalMs: 5000,
          reconnectAfterMs: () => {
            return 5000
          }
        }
      })
      await clent.realtime.setAuth()

      clent
        .channel(`messages-changes`, {
          config: { private: true, broadcast: { self: true } },
        })
        .on('broadcast', { event: 'INSERT' }, (payload) => console.log("insert:", payload))
        .on('broadcast', { event: 'UPDATE' }, (payload) => console.log("update:", payload))
        .on('broadcast', { event: 'DELETE' }, (payload) => console.log("delete:", payload))
        .subscribe((status, err) => console.log("status:", status, "err:", err))

session为 import { useSession } from "@clerk/nextjs"; 导入的hook

接下来可以向数据库public.your_table插入数据时,就会打印相关信息了

nextjs
nextjs
License:  CC BY 4.0
Share

Further Reading

May 3, 2025

nextjs15使用better-sqlite3的连接报错问题

1.出现如下错误 ⨯ Error: Could not locate the bindings file. Tried: 解决方法 我是使用pnpm包管理器,执行以下操作 首先安装node-gyp pnpm i node-gyp -D 然后执行 pnpm approve-builds 执行后会

Apr 6, 2025

nextjs + clerk + supabase + realtime 实时监听数据库更改

1.开启realtime.messages策略 在supabase的SQL Editor执行以下命令 create policy "Enable all access for authenticated users" on "public"."messages" as PERMISSIVE for

Mar 27, 2025

解决nextjs15使用useLocalStorage报错的问题

已经在组件中使用"use client"声明了,还是报错,错误如下: Unhandled Runtime Error Error: useLocalStorage is a client-only hook 1.解决方案1-使用 dynamic 导入 import dynamic from 'nex

OLDER

解决nextjs15使用useLocalStorage报错的问题

NEWER

nextjs15使用better-sqlite3的连接报错问题

Recently Updated

  • nextjs15使用better-sqlite3的连接报错问题
  • nextjs + clerk + supabase + realtime 实时监听数据库更改
  • 解决nextjs15使用useLocalStorage报错的问题
  • mac上使用nodejs appium控制chrome浏览器
  • 2024年终总结

Trending Tags

nginx acme 强制跳转HTTPS nodejs 代理 mac 神器 vue3 工具 docker

Contents

©2025 sunday. Some rights reserved.

Using the Halo theme Chirpy