You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Novu实现Next.js应用内实时通知无需手动刷新?

Next.js + Novu 实现实时通知无需刷新的解决方案

1. 先确认Novu实时连接已启用

Novu默认靠WebSocket推送实时通知,你得保证客户端初始化时没把这个功能关掉。在layout.tsx的NovuProvider里,务必填对subscriberId(当前登录用户的唯一标识)和applicationIdentifier(你的Novu应用ID);云版本不用额外配置socketUrl,自托管的话得填上你的WebSocket服务地址。

示例初始化代码:

import { NovuProvider } from '@novu/next';

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN">
      <body>
        <NovuProvider
          subscriberId="当前用户唯一ID"
          applicationIdentifier="你的Novu应用ID"
        >
          {children}
        </NovuProvider>
      </body>
    </html>
  );
}

2. 正确使用Novu的实时hooks

Novu的useNotifications hook本身就会监听WebSocket事件,有新通知时自动更新列表。别手动拉一次数据就停了,要在NotificationInbox.tsx里正确用这个hook,还可以把refreshInterval设为0,禁用轮询,完全依赖实时推送。

示例组件代码:

'use client';

import { useNotifications, NotificationBell } from '@novu/next';

export default function NotificationInbox() {
  const { notifications, fetchNotifications, markAsRead } = useNotifications({
    refreshInterval: 0, // 关闭轮询,全靠实时推送
  });

  return (
    <div>
      <NotificationBell unseenCount={notifications.filter(n => !n.seen).length} />
      <div className="notification-list">
        {notifications.map(note => (
          <div key={note._id} className="notification-item">
            <p>{note.content}</p>
            <button onClick={() => markAsRead(note._id)}>标记已读</button>
          </div>
        ))}
      </div>
    </div>
  );
}

3. 检查工作流的渠道配置

去Novu控制台看一下你的工作流,必须启用In-App渠道——实时推送只针对In-App通知生效,邮件、短信这类渠道不会触发前端自动更新。

4. 验证WebSocket连接状态

打开浏览器开发者工具,切换到Network标签的WS选项,看看有没有和Novu服务器的连接,状态得是OPEN。如果连不上,排查这几点:

  • 应用ID和用户ID是不是填错了
  • 网络有没有拦截WebSocket请求(比如防火墙、代理)
  • 自托管Novu的话,WebSocket服务是否正常运行

5. 手动监听事件兜底(可选)

要是上面的方法都没效果,那就手动监听Novu的WebSocket事件,收到新通知时主动刷新列表:

'use client';

import { useEffect } from 'react';
import { useNovu, useNotifications } from '@novu/next';

export default function NotificationInbox() {
  const { novu } = useNovu();
  const { notifications, fetchNotifications } = useNotifications();

  useEffect(() => {
    if (!novu) return;

    // 订阅新通知事件
    const unsubscribe = novu.notifications.subscribeToNewNotifications((newNote) => {
      console.log('新通知:', newNote);
      fetchNotifications(); // 主动拉取最新通知列表
    });

    return () => unsubscribe();
  }, [novu, fetchNotifications]);

  // 渲染通知列表的代码...
}

内容的提问来源于stack exchange,提问作者Sarmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 21:23:11