A practical guide to use Sentry in Next.js
Sentry 提供端到端的分布式追踪,使开发者能够识别和调试其系统和服务的性能问题和错误。
Manual Setup | Sentry for Next.js
pnpm add @sentry/nextjs
next.config.js
import { withSentryConfig } from "@sentry/nextjs";
const nextConfig = {
// Your existing Next.js configuration
};
// Make sure adding Sentry options is the last code to run before exporting
export default withSentryConfig(nextConfig, {
org: "example-org",
project: "example-project",
// Only print logs for uploading source maps in CI
// Set to `true` to suppress logs
silent: !process.env.CI,
// Automatically tree-shake Sentry logger statements to reduce bundle size
disableLogger: true,
});
app/layout.tsx
上添加额外配置 import * as Sentry from "@sentry/nextjs";
import type { Metadata } from "next";
export function generateMetadata(): Metadata {
return {
// ... your existing metadata
other: {
...Sentry.getTraceData(),
},
};
}
instrumentation-client.(js|ts)
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
// Adds request headers and IP for users, for more info visit:
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#sendDefaultPii
sendDefaultPii: true,
// Capture Replay for 10% of all sessions,
// plus for 100% of sessions with an error
// Learn more at
// https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
// Note: if you want to override the automatic release value, do not set a
// `release` value here - use the environment variable `SENTRY_RELEASE`, so
// that it will also get attached to your source maps
});
// This export will instrument router navigations, and is only relevant if you enable tracing.
// `captureRouterTransitionStart` is available from SDK version 9.12.0 onwards
export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;
sentry.server.config.(js|ts)
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
// Adds request headers and IP for users, for more info visit:
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#sendDefaultPii
sendDefaultPii: true,
// ...
// Note: if you want to override the automatic release value, do not set a
// `release` value here - use the environment variable `SENTRY_RELEASE`, so
// that it will also get attached to your source maps
});
sentry.edge.config.(js|ts)
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
// Adds request headers and IP for users, for more info visit:
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#sendDefaultPii
sendDefaultPii: true,
// ...
// Note: if you want to override the automatic release value, do not set a
// `release` value here - use the environment variable `SENTRY_RELEASE`, so
// that it will also get attached to your source maps
});
在根目录或者src(如果有)下创建 instrumentation.ts
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
await import("./sentry.server.config");
}
if (process.env.NEXT_RUNTIME === "edge") {
await import("./sentry.edge.config");
}
}
在Next.js的 error.tsx
或者 global-error.tsx
中加入
"use client";
import * as Sentry from "@sentry/nextjs";
import NextError from "next/error";
import { useEffect } from "react";
export default function GlobalError({
error,
}: {
error: Error & { digest?: string };
}) {
useEffect(() => {
Sentry.captureException(error);
}, [error]);
return (
<html>
<body>
{/* `NextError` is the default Next.js error page component. Its type
definition requires a `statusCode` prop. However, since the App Router
does not expose status codes for errors, we simply pass 0 to render a
generic error message. */}
<NextError statusCode={0} />
</body>
</html>
);
}
instrumentation.ts
中加入 import * as Sentry from "@sentry/nextjs";
export const onRequestError = Sentry.captureRequestError;
dsn
dsn: 'https://<key>@o<org>.ingest.sentry.io/<project>',
dsn: ''
),Sentry 不会上传任何数据。tracesSampleRate
(性能监控采样率) tracesSampleRate: 1.0,
0 ~ 1
1.0
,上线后通常设置为 0.1
或更低以减少数据量。replaysSessionSampleRate
和 replaysOnErrorSampleRate
(会话回放) replaysSessionSampleRate: 0.1, // 正常会话记录采样率
replaysOnErrorSampleRate: 1.0, // 出错会话记录采样率
sendDefaultPii
(是否发送用户隐私数据) sendDefaultPii: true,
setUser({ email })
显示用户身份integrations
(集成插件) integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration(),
Sentry.feedbackIntegration(),
]
常见插件:
插件 | 用途 |
---|---|
BrowserTracing | 前端性能监控(用于页面加载时间、资源加载、API 调用等) |
Replay | 用户操作录屏 |
Feedback | 内置用户反馈 UI,可弹出对话框收集意见 |
HttpClient | 追踪 XMLHttpRequest 和 Fetch 请求 |
Console | 收集 console.error 等信息 |
SessionTiming | 记录用户会话时间(默认包含) |
beforeSend
(发送前钩子) beforeSend(event, hint) {
if (event.message?.includes('IgnoreError')) return null;
return event;
}
null
表示忽略该事件,不上传environment
(环境标签) environment: process.env.NODE_ENV,
production
、staging
、dev
Sentry.setUser({
id: '12345',
email: 'user@example.com',
username: 'tester',
});
Sentry.setTag('feature', 'checkout');
Sentry.setContext('cart', {
items: 3,
total: 100,
});
try {
// some code
} catch (e) {
Sentry.captureException(e);
}
或手动记录信息:
Sentry.captureMessage('Something unusual happened');
若你在多端项目中(前端 + 后端)都用了 Sentry,还可通过:
Sentry.getCurrentHub().getScope()?.getSpan()?.toTraceparent()
传递 traceparent
header 实现端到端追踪(如 API 调用链追踪)。
debug: true,
.env
中加入sentry.io中的DSN