手动配置

https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/

配置DSN

防止额度被盗刷(重要防护)

配置采样率

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
  // 1. 错误追踪:前期建议 100% 捕获,因为你是单兵作战,每个报错都很重要
  sampleRate: 1.0, 

  // 2. 性能追踪 (Transactions):这是最费钱的
  // 建议设置极低,比如 0.1 (10%) 甚至 0.05 (5%)
  // 你不需要监控每一个用户的页面加载速度,只需要一个统计趋势
  tracesSampleRate: 0.1, 

  // 3. Session Replay (回放):非常贵且耗流量
  // 正常会话不录屏,只有报错时才录屏 100%
  replaysSessionSampleRate: 0, 
  replaysOnErrorSampleRate: 1.0, 
}

过滤垃圾报错

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
Sentry.init({
  // 简单粗暴的忽略列表
  ignoreErrors: [
    "ResizeObserver loop limit exceeded", // 经典良性错误,无视
    "Non-Error promise rejection captured",
    "Network Error", // 用户断网,不用报给我
    "Failed to fetch", // 同上
    "Loading chunk", // 网络波动导致懒加载失败
  ],
  
  // 或者使用更高级的 beforeSend 过滤
  beforeSend(event, hint) {
    const error = hint.originalException;
    // 过滤掉爬虫 (User Agent 判断)
    if (event.request?.headers?.['User-Agent']?.includes('Googlebot')) {
      return null;
    }
    return event;
  },
});

上传 Source Maps

  1. 获取 Sentry Auth Token (专用上传令牌): User Settings -> Developer Settings -> Personal Settings
  2. 配置 Cloudflare 环境变量
  3. 配置 next.config.mjs (SDK v8 语法)
  4. 验证上传是否成功

关联用户身份 (User Context)

脚本配置

第一步:准备 Sentry 项目

  1. 注册/登录 sentry.io
  2. 点击 Create Project
  3. 选择平台:Next.js
  4. Alert Frequency:建议选 “I’ll create my own alerts later”(避免初始邮件轰炸)。
  5. 输入项目名称(例如 my-saas-frontend),点击 Create Project。

第二步:使用官方向导自动安装 (推荐)

复制官方向导命令,打开你的 Next.js 项目终端,运行命令:

命令类似于下面的:

1
npx @sentry/wizard@latest -i nextjs

接下来向导会引导你完成配置(按提示操作):

  1. 登录:浏览器会自动弹窗请求授权 Sentry,点击确认。
  2. 选择项目:终端里会列出你的 Sentry 项目,用箭头键选择刚才创建的那个项目。
  3. 安装依赖:向导会自动安装 @sentry/nextjs 包。
  4. 是否使用 CI/CD:它会询问你是否在 CI/CD 环境(如 GitHub Actions)构建。
    • 如果是本地开发先选 No。
    • 注意:这一步通常会生成一个 SENTRY_AUTH_TOKEN,如果是 Vercel 部署,后面需要用到。
  5. 自动修改文件:向导会自动创建/修改以下文件:
    • sentry.client.config.ts (客户端错误配置)
    • sentry.server.config.ts (服务端错误配置)
    • sentry.edge.config.ts (Edge Runtime 错误配置)
    • next.config.js (注入 Webpack 插件,用于上传 Source Maps)

第三步:验证安装 (测试报错)

为了确认 Sentry 真的在工作,我们需要故意制造一个错误。

在你的 app/page.tsx (或者任意页面组件) 中加入一个测试按钮:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// app/page.tsx
"use client"; // 如果是 Server Component,需要加上这个才能用 onClick

export default function Home() {
  return (
    <main style={{ padding: 50 }}>
      <h1>Sentry Test</h1>
      <button
        type="button"
        style={{ padding: '10px 20px', background: 'red', color: 'white' }}
        onClick={() => {
          throw new Error("Sentry 测试错误: 这是我手动触发的!");
        }}
      >
        点我报错
      </button>
    </main>
  );
}
  1. 运行 npm run dev
  2. 打开页面,点击按钮。页面会崩溃(Next.js 开发模式下会显示红屏报错)。
  3. 不要慌,回到 Sentry 后台,点击左侧 Issues,你应该能在几秒钟内看到这个错误出现在列表中。

第四步:关键配置 (Source Maps 与 环境变量)

这是新手最容易踩坑的地方。如果在本地测试好好的,上线后发现报错全是 a.b is not a function 这种压缩后的代码,说明 Source Maps 没配置好。

1. 设置环境变量 (如果你用 Vercel 部署)

Sentry 需要在构建时上传 Source Maps,这需要权限。

  • 如果使用 Vercel

    1. 去 Sentry 后台 -> Settings -> Auth Tokens,创建一个 Token(勾选 project:releases)。
    2. 去 Vercel 后台 -> 你的项目 -> Settings -> Environment Variables。
    3. 添加变量名:SENTRY_AUTH_TOKEN,值填刚才生成的 Token。
    4. 重新 Deploy 你的项目。
  • 自动集成方式:你也可以在 Vercel 的 “Integrations” 市场里直接搜索 Sentry 并连接,它会自动帮你设置好环境变量。

2. 忽略不必要的错误 (降噪)

sentry.client.config.ts 中,你可以配置忽略某些不需要上报的错误(比如用户取消请求):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: "你的_DSN_地址",
  // 采样率:1.0 代表 100% 上报。生产环境建议调低(例如 0.1)以节省额度
  tracesSampleRate: 1.0, 
  
  // 忽略特定错误
  ignoreErrors: [
    "ResizeObserver loop limit exceeded", // 常见的浏览器良性错误
    "Network Error",
    "Failed to fetch"
  ],
});

第五步:关联用户信息 (进阶)

作为 SaaS,你肯定想知道是哪个用户遇到了报错。你可以在用户登录后,手动设置用户信息。

在你的 Layout 或 Auth Provider 中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import * as Sentry from "@sentry/nextjs";

// 假设你从 session 中获取了 user
if (user) {
  Sentry.setUser({
    id: user.id,
    email: user.email,
    username: user.name,
  });
} else {
  Sentry.setUser(null);
}

这样,当报错发生时,Sentry 的详情页会直接显示:“受影响用户:zhangsan@example.com”,极大方便排查。

总结

  1. 运行 npx @sentry/wizard@latest -i nextjs
  2. 确保 next.config.js 被自动修改了。
  3. 在 Vercel/生产环境配置 SENTRY_AUTH_TOKEN 以确保代码能反解(Source Maps)。
  4. 使用 Sentry.setUser 关联你的 SaaS 用户。