mcpField
S
sentry-nextjs-sdk

sentry-nextjs-sdk

github.com/getsentry開発2723.7k 回インストール今日更新
リポジトリ

sentry-nextjs-sdk について

Next.jsプロジェクトにSentryを導入するためのセットアップスキルです。ブラウザー、Node.jsサーバー、Edgeの各ランタイムを調査し、SDKの設定や機能選択、検証を案内します。

主な機能

  1. 01Next.jsのバージョンとルーターを検出
  2. 023種類のランタイム設定を案内
  3. 03監視・可観測性機能を設定
  4. 04ウィザードと手動設定に対応
  5. 05ソースマップのアップロードを案内

活用シーン

  1. 01Next.jsアプリへのSentry導入
  2. 02プロジェクトに合う監視機能の選択
  3. 03本番ビルドへのソースマップ追加

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/getsentry/sentry-for-ai --skill sentry-nextjs-sdk

インストール後、Claude Code で/sentry-nextjs-sdkを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
ai-monitoring.md
crons.md
error-monitoring.md
logging.md
metrics.md
profiling.md
session-replay.md
tracing.md

詳細

すべてのスキル > SDK のセットアップ > Next.js SDK

Sentry Next.js SDK

Next.js プロジェクトをスキャンし、ブラウザー、Node.js サーバー、Edge の3つのランタイムすべてにわたる Sentry の完全なセットアップを案内する、独自の方針を持ったウィザードです。

このスキルを使用する場面

  • ユーザーが Next.js アプリに「Sentry を追加」または「Sentry をセットアップ」するよう求めた場合
  • @sentry/nextjs のインストールまたは設定を希望する場合
  • Next.js のエラー監視、トレーシング、セッションリプレイ、ロギング、プロファイリングを希望する場合
  • instrumentation.ts、withSentryConfig()、または global-error.tsx について尋ねられた場合
  • サーバーアクション、サーバーコンポーネントのエラー、または Edge ランタイムのエラーを捕捉したい場合

注: 以下の SDK バージョンと API は、執筆時点での Sentry の最新ドキュメント(@sentry/nextjs ≥8.28.0)に基づいています。 実装前に必ずdocs.sentry.io/platforms/javascript/guides/nextjs/で確認してください。


フェーズ 1:検出

推奨を行う前に、以下のコマンドを実行してプロジェクトの状況を確認してください。

# Detect Next.js version and existing Sentry
cat package.json | grep -E '"next"|"@sentry/'

# Detect router type (App Router vs Pages Router)
ls src/app app src/pages pages 2>/dev/null

# Check for existing Sentry config files
ls instrumentation.ts instrumentation-client.ts sentry.server.config.ts sentry.edge.config.ts 2>/dev/null
ls src/instrumentation.ts src/instrumentation-client.ts 2>/dev/null

# Check next.config
ls next.config.ts next.config.js next.config.mjs 2>/dev/null

# Check for existing error boundaries
find . -name "global-error.tsx" -o -name "_error.tsx" 2>/dev/null | grep -v node_modules

# Check build tool
cat package.json | grep -E '"turbopack"|"webpack"'

# Check for logging libraries
cat package.json | grep -E '"pino"|"winston"|"bunyan"'

# Check for companion backend
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3

確認する項目:

質問影響
Next.js のバージョンは?13 以降が必須です。Turbopack のサポートには 15 以降が必要です
App Router と Pages Router のどちらを使用していますか?必要なエラーバウンダリーファイル(global-error.tsx と _error.tsx のどちらか)が決まります
@sentry/nextjs はすでに導入されていますか?インストールを省略し、機能設定に進みます
既存の instrumentation.ts はありますか?置き換えるのではなく、そこに Sentry を統合します
Turbopack を使用していますか?withSentryConfig によるツリーシェイキングは webpack 専用です
ロギングライブラリが検出されましたか?Sentry Logs 統合を推奨します
バックエンドのディレクトリが見つかりましたか?フェーズ 4 の関連案内の提案を行います

フェーズ 2:推奨

確認できた内容に基づいて、具体的な推奨事項を提示してください。自由形式の質問はせず、提案を先に示します。

推奨(基本的なカバレッジ):

  • ✅ エラー監視 — 常に有効にします。サーバーエラー、クライアントエラー、サーバーアクション、未処理の Promise 拒否を捕捉します
  • ✅ トレーシング — すべてのランタイムにわたるサーバー側のリクエストトレーシングとクライアント側のナビゲーションスパンを提供します
  • ✅ セッションリプレイ — ユーザー向けアプリに推奨します。エラー発生前後のセッションを記録します

オプション(オブザーバビリティの強化):

  • ⚡ ロギング — Sentry.logger.* による構造化ログです。pino/winston を使用している場合や、ログ検索が必要な場合に推奨します
  • ⚡ プロファイリング — 継続的なプロファイリングです。Document-Policy: js-profiling ヘッダーが必要です
  • ⚡ AI 監視 — OpenAI、Vercel AI SDK、Anthropic に対応します。AI/LLM 呼び出しが検出された場合に推奨します
  • ⚡ Crons — 実行されなかった、または失敗したスケジュール済みジョブを検出します。cron のパターンが検出された場合に推奨します
  • ⚡ メトリクス — Sentry.metrics.* によるカスタムメトリクスです。カスタム KPI やビジネスメトリクスが必要な場合に推奨します

推奨ロジック:

機能次の場合に推奨します
エラー監視常に — 必須の基本機能です
トレーシングNext.js では常に — サーバールートのトレーシングとクライアントナビゲーションは大きな効果があります
セッションリプレイユーザー向けアプリ、ログインフロー、またはチェックアウトページがある場合
ロギングアプリで構造化ロギングを使用している場合、またはログとトレースの関連付けが必要な場合
プロファイリングパフォーマンスが重要なアプリで、クライアントが Document-Policy: js-profiling を設定している場合
AI 監視アプリで OpenAI、Vercel AI SDK、または Anthropic の呼び出しがある場合
Cronsアプリに Vercel Cron ジョブ、スケジュール済み API ルート、または node-cron の使用がある場合
メトリクスSentry.metrics.* によるカスタムカウンター、ゲージ、またはヒストグラムが必要な場合

次のように提案してください。「エラー監視 + トレーシング + セッションリプレイのセットアップをおすすめします。ロギングやプロファイリングも追加しますか?」


フェーズ 3:ガイド

オプション 1:ウィザード(推奨)

これはユーザー自身が実行する必要があります — ウィザードはログイン用のブラウザーを開き、エージェントでは対応できない対話形式の入力が必要です。以下をコピーしてターミナルに貼り付けてください:

npx @sentry/wizard@latest -i nextjs

ログイン、組織/プロジェクトの選択、SDK のインストール、設定ファイル(instrumentation-client.ts、sentry.server.config.ts、sentry.edge.config.ts、instrumentation.ts)、next.config.ts のラップ、ソースマップのアップロード、/sentry-example-page の追加を処理します。

完了したら戻り、検証 に進んでください。

ウィザードをスキップする場合は、以下のオプション 2(手動セットアップ)に進みます。


オプション 2:手動セットアップ
インストール
npm install @sentry/nextjs --save
instrumentation-client.ts を作成 — ブラウザー/クライアントランタイム

以前のドキュメントでは sentry.client.config.ts を使用していました — 現在のパターンは instrumentation-client.ts です。

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

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN ?? "___PUBLIC_DSN___",

  dataCollection: {
    // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
    // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection
    // userInfo: false,
    // httpBodies: [],
  },

  // 100% in dev, 10% in production
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,

  // Session Replay: 10% of all sessions, 100% of sessions with errors
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,

  enableLogs: true,

  integrations: [
    Sentry.replayIntegration(),
    // Optional: user feedback widget
    // Sentry.feedbackIntegration({ colorScheme: "system" }),
  ],
});

// Hook into App Router navigation transitions (App Router only)
export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;
sentry.server.config.ts を作成 — Node.js サーバーランタイム
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? "___DSN___",

  dataCollection: {
    // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
    // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection
    // userInfo: false,
    // httpBodies: [],
  },
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,

  // Attach local variable values to stack frames
  includeLocalVariables: true,

  enableLogs: true,
});
sentry.edge.config.ts を作成 — Edge ランタイム
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? "___DSN___",

  dataCollection: {
    // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
    // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection
    // userInfo: false,
    // httpBodies: [],
  },
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,

  enableLogs: true,
});
instrumentation.ts を作成 — サーバーサイド登録フック

Next.js < 14.0.4 では、next.config に experimental.instrumentationHook: true が必要です。14.0.4 以降では安定版です。

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

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");
  }
}

// Automatically captures all unhandled server-side request errors
// Requires @sentry/nextjs >= 8.28.0
export const onRequestError = Sentry.captureRequestError;

ランタイムの振り分け:

NEXT_RUNTIME読み込まれる設定ファイル
"nodejs"sentry.server.config.ts
"edge"sentry.edge.config.ts
(クライアントバンドル)instrumentation-client.ts(Next.js が直接処理します)
App Router:app/global-error.tsx を作成

ルートレイアウトのエラーと React のレンダーエラーを捕捉します:

"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 statusCode={0} />
      </body>
    </html>
  );
}
Pages Router:pages/_error.tsx を更新
import * as Sentry from "@sentry/nextjs";
import type { NextPageContext } from "next";
import NextErrorComponent from "next/error";

type ErrorProps = { statusCode: number };

export default function CustomError({ statusCode }: ErrorProps) {
  return <NextErrorComponent statusCode={statusCode} />;
}

CustomError.getInitialProps = async (ctx: NextPageContext) => {
  await Sentry.captureUnderscoreErrorException(ctx);
  return NextErrorComponent.getInitialProps(ctx);
};
next.config.ts を withSentryConfig() でラップ
import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs";

const nextConfig: NextConfig = {
  // your existing Next.js config
};

export default withSentryConfig(nextConfig, {
  org: "___ORG_SLUG___",
  project: "___PROJECT_SLUG___",

  // Source map upload auth token (see Source Maps section below)
  authToken: process.env.SENTRY_AUTH_TOKEN,

  // Upload wider set of client source files for better stack trace resolution
  widenClientFileUpload: true,

  // Create a proxy API route to bypass ad-blockers
  tunnelRoute: "/monitoring",

  // Suppress non-CI output
  silent: !process.env.CI,
});
ミドルウェアでトンネルルートを除外

middleware.ts がある場合は、トンネルパスを認証またはリダイレクトのロジックから除外します:

// middleware.ts
export const config = {
  matcher: [
    // Exclude monitoring route, Next.js internals, and static files
    "/((?!monitoring|_next/static|_next/image|favicon.ico).*)",
  ],
};

ソースマップのセットアップ

withSentryConfig は本番ビルド時にソースマップをアップロードするため、スタックトレースには圧縮された出力ではなく元のコードが表示されます。SDK 固有の設定は、next.config.ts の authToken(およびクライアントのスタックトレースを改善する widenClientFileUpload)です:

withSentryConfig(nextConfig, {
  org: "my-org",
  project: "my-project",
  authToken: process.env.SENTRY_AUTH_TOKEN, // from CI env or a gitignored .env.sentry-build-plugin
  widenClientFileUpload: true,
});

SENTRY_AUTH_TOKEN はビルド時のシークレットであり、DSN とは別のものです。トークンの作成、CI への設定、圧縮されたトレースのトラブルシューティングについては、sentry-source-maps を参照してください。

ソースマップは next build のたびに自動でアップロードされます。


合意した各機能について

対応するリファレンスファイルを読み込み、その手順に従います:

機能リファレンスファイル読み込むタイミング...
エラーモニタリングreferences/error-monitoring.md常に(基本設定)— App Router のエラーバウンダリー、Pages Router の _error.tsx、サーバーアクションのラップ
トレーシングreferences/tracing.mdサーバーサイドのリクエストトレーシング、クライアントナビゲーション、分散トレーシング、tracePropagationTargets
セッションリプレイreferences/session-replay.mdユーザー向けアプリの場合。プライバシーマスキング、キャンバスの記録、ネットワークのキャプチャ
ロギングreferences/logging.md構造化ログ、Sentry.logger.*、ログとトレースの相関
プロファイリングreferences/profiling.md継続的プロファイリング、Document-Policy ヘッダー、nodeProfilingIntegration
AI モニタリングreferences/ai-monitoring.mdアプリで OpenAI、Vercel AI SDK、または Anthropic を使用する場合
クロンreferences/crons.mdVercel Cron、スケジュールされた API ルート、node-cron
メトリクスreferences/metrics.mdSentry.metrics.* によるカスタムカウンター、ゲージ、分布

各機能について、リファレンスファイルを読み、手順に正確に従って、次に進む前に検証します。


設定リファレンス

Sentry.init() のオプション
オプション型デフォルト備考
dsnstring—必須です。クライアントには NEXT_PUBLIC_SENTRY_DSN、サーバーには SENTRY_DSN を使用します
tracesSampleRatenumber—0~1。開発環境では 1.0、本番環境では 0.1 を推奨します
replaysSessionSampleRatenumber0.1記録する全セッションの割合
replaysOnErrorSampleRatenumber1.0記録するエラー発生セッションの割合
dataCollectionobject設定しない場合は保守的自動収集するカテゴリ(userInfo、cookies、httpHeaders、httpBodies、queryParams、genAI)をきめ細かく制御します。省略すると、SDK は sendDefaultPii(デフォルトは false)にフォールバックします。このオブジェクトを渡すと({} も含む)、未設定のカテゴリは許可するデフォルト値に切り替わります。カテゴリごとにオプトアウトできます。
includeLocalVariablesbooleanfalseスタックフレームにローカル変数の値を付加します(サーバーのみ)
enableLogsbooleanfalseSentry Logs 製品を有効にします
environmentstring自動"production"、"staging" など
releasestring自動コミット SHA またはバージョンタグを設定します
debugbooleanfalseSDK の動作をコンソールに記録します
withSentryConfig() のオプション
オプション型備考
orgstringSentry 組織のスラッグ
projectstringSentry プロジェクトのスラッグ
authTokenstringソースマップのアップロードトークン(SENTRY_AUTH_TOKEN)
widenClientFileUploadbooleanスタックトレースの精度向上のため、クライアントファイルをより多くアップロードします
tunnelRoutestring広告ブロッカーを回避するための API ルートパス(例:"/monitoring")
silentbooleanビルド出力を抑制します(!process.env.CI を推奨)
webpack.treeshake.*objectSDK の機能をツリーシェイクします(webpack のみ。Turbopack は対象外)
環境変数
変数実行環境用途
NEXT_PUBLIC_SENTRY_DSNクライアントブラウザーでの Sentry 初期化用 DSN(公開)
SENTRY_DSNサーバー / Edgeサーバー/Edge での Sentry 初期化用 DSN
SENTRY_AUTH_TOKENビルドソースマップのアップロード用認証トークン(シークレット)
SENTRY_ORGビルド組織のスラッグ(設定の org の代替)
SENTRY_PROJECTビルドプロジェクトのスラッグ(設定の project の代替)
SENTRY_RELEASEサーバーリリースのバージョン文字列(git から自動検出)
NEXT_RUNTIMEサーバー / Edge"nodejs" または "edge"(Next.js によって内部的に設定)

検証

ウィザードまたは手動でのセットアップ後、Sentry が動作していることを確認します。

// Add temporarily to a server action or API route, then remove
import * as Sentry from "@sentry/nextjs";

throw new Error("Sentry test error — delete me");
// or
Sentry.captureException(new Error("Sentry test error — delete me"));

次に、Sentry Issues ダッシュボードを確認します。エラーは約 30 秒以内に表示されるはずです。

検証チェックリスト:

確認項目方法
クライアントエラーの捕捉クライアントコンポーネントで例外をスローし、Sentry で確認します
サーバーエラーの捕捉サーバーアクションまたは API ルートで例外をスローします
Edge エラーの捕捉ミドルウェアまたは Edge ルートハンドラーで例外をスローします
ソースマップの動作スタックトレースに読みやすいファイル名が表示されることを確認します
セッションリプレイの動作Sentry ダッシュボードの Replays タブを確認します

フェーズ 4:相互リンク

Next.js のセットアップ完了後、関連するサービスがないか確認します。

# Check for backend services in adjacent directories
ls ../backend ../server ../api ../services 2>/dev/null

# Check for backend language indicators
cat ../go.mod 2>/dev/null | head -3
cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -3
cat ../Gemfile 2>/dev/null | head -3
cat ../pom.xml ../build.gradle 2>/dev/null | head -3

バックエンドが見つかった場合は、対応する SDK スキルを提案します。

検出されたバックエンド提案するスキル
Go(go.mod)sentry-go-sdk
Python(requirements.txt、pyproject.toml)sentry-python-sdk
Ruby(Gemfile)sentry-ruby-sdk
Java/Kotlin(pom.xml、build.gradle)docs.sentry.io/platforms/java/ を参照
Node.js(Express、Fastify、Hapi)@sentry/node — docs.sentry.io/platforms/javascript/guides/express/ を参照

フロントエンドとバックエンドで同じ DSN を使用するか、プロジェクトをリンクすると、分散トレーシングが有効になります。これにより、ブラウザー、Next.js サーバー、バックエンド API にまたがるスタックトレースを、単一のトレースビューで確認できます。


トラブルシューティング

問題原因解決策
イベントが表示されないDSN の設定ミス、または debug: false によってエラーが非表示になっている一時的に debug: true に設定し、ブラウザーのネットワークタブで sentry.io へのリクエストを確認します
スタックトレースに圧縮されたコードが表示されるソースマップがアップロードされていないSENTRY_AUTH_TOKEN が設定されていることを確認し、next build を実行してビルド出力に「Source Maps」があるか確認します
onRequestError が実行されないSDK のバージョンが 8.28.0 未満アップグレードします:npm install @sentry/nextjs@latest
Edge ランタイムのエラーが表示されないsentry.edge.config.ts が読み込まれていないNEXT_RUNTIME === "edge" のときに instrumentation.ts からインポートされていることを確認します
トンネルルートが 404 を返すtunnelRoute が設定されているが、Next.js のルートがないプラグインが自動的に作成します。tunnelRoute の追加後に next build を実行したことを確認します
withSentryConfig のツリーシェイキングでビルドが壊れるTurbopack を使用しているツリーシェイキングのオプションは webpack でのみ機能します。Turbopack を使用する場合は webpack.treeshake オプションを削除します
global-error.tsx でエラーを捕捉できない"use client" ディレクティブがないglobal-error.tsx の最初の行に "use client" を追加します
セッションリプレイが記録されないクライアントの初期化時に replayIntegration() がないinstrumentation-client.ts の integrations に Sentry.replayIntegration() を追加します

コメント