avatar

sunday

Sunday's Blog

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

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

发表于 2025-04-6 更新于 2025-04- 6
作者 sunday 已删除用户
7~9 分钟 阅读

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
许可协议:  CC BY 4.0
分享

相关文章

8月 12, 2025

nextjs15使用ai sdk的一些问题

目前作者使用的版本: "@ai-sdk/openai": "^2.0.10", "@ai-sdk/react": "^2.0.10", "ai": "^5.0.10", "@modelcontextprotocol/sdk": "^1.17.2", "next": "15.4.5", 1.strea

7月 1, 2025

nextjs使用three.js写一个3D模型的查看器Viewer

直接上代码 // components/GLBViewer.js "use client"; import { useEffect, useRef, useState } from "react"; import * as THREE from "three"; import { OrbitCon

5月 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 执行后会

下一篇

解决nextjs15使用useLocalStorage报错的问题

上一篇

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

最近更新

  • ios18 swiftUI 开发的一些问题
  • Cursor IDE中开发IOS应用——支持热更新
  • nginx + acme 不占用80端口申请证书
  • 免费CDN 阿里云ESA 加速国内网站
  • nextjs15使用ai sdk的一些问题

热门标签

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

目录

©2025 sunday. 保留部分权利。

使用 Halo 主题 Chirpy