Next.js 和 React

安装 npm install @blipit/nextjs

@blipit/nextjs 通过 layout 中的一个组件提供浏览器错误、Web 指标和会话回放,通过 instrumentation.ts 中的一行代码捕获 server component、route handler 和 server action 的错误。纯 React 应用使用 @blipit/browser。

1安装

sh
npm install @blipit/nextjs

2浏览器端

在根 layout 中添加一次该组件。它使用公钥,可安全用于浏览器代码;将其放在 NEXT_PUBLIC_BLIPIT_KEY 中。

app/layout.tsx
import { Blipit } from "@blipit/nextjs";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Blipit
          publicKey={process.env.NEXT_PUBLIC_BLIPIT_KEY!}
          environment={process.env.NEXT_PUBLIC_VERCEL_ENV ?? "development"}
          release={process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA}
          replay={{ onErrorSampleRate: 1 }}
        />
        {children}
      </body>
    </html>
  );
}

3服务端

Next.js 15 及更高版本会在 server component、route handler 和 server action 出错时调用 onRequestError。一行代码即可将其接入 Blipit。在服务器环境中设置 BLIPIT_SECRET_KEY,切勿设为 NEXT_PUBLIC_。

instrumentation.ts
export { captureRequestError as onRequestError } from "@blipit/nextjs/server";

4Content Security Policy

如果你的应用设置了 CSP,请将 https://in.blipit.io 加入 connect-src。SDK 与你的代码一起打包,因此 script-src 不需要新的主机,也不需要 nonce。

5Source map(可选)

为了让堆栈跟踪显示你的源码而不是压缩后的 bundle,请在构建步骤中为每个 release 上传 map 文件。

sh
BLIPIT_KEY=<secret key> npx @blipit/cli sourcemaps upload .next/static --release "$VERCEL_GIT_COMMIT_SHA"

6验证是否生效

添加一个会抛出错误的按钮,或在浏览器控制台中运行这段代码。打开 app.blipit.io 中的“问题”。首个事件几秒钟内就会出现,并归组为一个问题,负责人会收到邮件。

js
import { captureMessage } from "@blipit/nextjs";
captureMessage("Hello from Next.js");

须知

  • 不用 Next.js 的纯 React:npm install @blipit/browser,并在渲染前调用 Blipit.init;参见“任意网站”。
  • 在服务端省略 environment 和 release 时,默认取 VERCEL_ENV 和 VERCEL_GIT_COMMIT_SHA。
  • 已经在用 Sentry SDK?@sentry/nextjs 无需更改即可使用 DSN https://<public key>@in.blipit.io/<project id>;跳过 withSentryConfig,它会把 source map 上传到 Sentry。

遇到问题?发邮件至 support@blipit.io。每个项目的密钥和确切的 DSN 在 app.blipit.io 的“API 密钥”下。