Sentry Setup For Next.js

参考文档 https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/

  1. 首先选择上 TracingSession Replay,否则下面的配置不会包含这些功能相关的选项。

2. 使用环境变量管理 Sentry org,project

因为有多处配置文件使用到这些变量,所以最好使用环境变量集中管理。其中包括:

SENTRY_AUTH_TOKEN=sntrys_***
NEXT_PUBLIC_SENTRY_DSN=https://***
NEXT_PUBLIC_SENTRY_PROJECT=***
NEXT_PUBLIC_SENTRY_ORG=***
.env
module.exports = withSentryConfig(nextConfig, {
  org: process.env.NEXT_PUBLIC_SENTRY_ORG,
  project: process.env.NEXT_PUBLIC_SENTRY_PROJECT,
});
next.config.js

3. 运行环境 environment

一般情况,一个项目都会有测试环境(development)和生产环境(production)

我们可以分别定义 ENVIRONMENT 在不用的 .env 文件中,如:

ENVIRONMENT=production
.env.production
ENVIRONMENT=development
.env.development

在配置文件中使用:

import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  environment: process.env.ENVIRONMENT
});
sentry.(edge|server).config.ts, instrumentation-client.ts

配置 environment 后可在Sentry中显示错误来源的运行环境。

4. 运行版本 release

此配置可用于定位错误触发的版本。

可在 CI 中获取 或 生成 BUILD_HASH, 写入到 .env.local 中,可在 next.js 中使用。

如果可以获取 git commit sha:

# 如果可以获取 git commit sha: 
BUILD_HASH=$(git rev-parse --short HEAD)

# 如果不能回去 git commit 信息,可用其他方案,如当前时间
BUILD_HASH=$(date +%Y%m%d-%H%M%S)

echo "BUILD_HASH=$BUILD_HASH" >> .env.local
JavaScript
const packageJson = require("./package.json")

module.exports = withSentryConfig(module.exports, {

  org: process.env.NEXT_PUBLIC_SENTRY_ORG,
  project: process.env.NEXT_PUBLIC_SENTRY_PROJECT,
  release: {
    name: `${packageJson.name}@${packageJson.version}-${process.env.BUILD_HASH}`,
  },
})
next.config.js

配置后,Sentry中的错误信息会显示错误来源的版本号,这儿只会显示 @符号 后的内容。

5. 上传 Source Maps

参考 https://docs.sentry.io/platforms/javascript/sourcemaps

必须开启 productionBrowserSourceMaps

module.exports ={
  reactStrictMode: true,
  productionBrowserSourceMaps: true,
}
next.config.js

const { sentryWebpackPlugin } = require("@sentry/webpack-plugin")

/**
 * here is the config for webpack that not related to nextjs
 */
module.exports = /** @type {import('webpack').Configuration} */ ({
  devtool: "source-map", // for sentry sourcemaps feature, we must enable source map
  plugins: [
    // Put the Sentry Webpack plugin after all other plugins
    sentryWebpackPlugin({
      authToken: process.env.SENTRY_AUTH_TOKEN,
      org: process.env.NEXT_PUBLIC_SENTRY_ORG,
      project: process.env.NEXT_PUBLIC_SENTRY_PROJECT,
    }),
  ],
})
webpack.config.js

SourceMaps 文件会在build后上传到 Sentry,并删除本地的 .map 文件,所以你并不会在打包结果中看到他们。

59 thoughts on “Sentry Setup For Next.js

  1. AI Logo Generator

    Great post on Sentry setup for Next.js! I’ve been using environment variables to manage sensitive info like the SENTRY_DSN, but the section on configuring `release` versions was a helpful addition. It’s something I didn’t consider before but seems crucial for pinpointing the exact source of errors.

Comments are closed.