mcpField
S
sentry-nextjs-sdk

sentry-nextjs-sdk

github.com/getsentry開発25656 回インストール35 週間前に更新
リポジトリ

sentry-nextjs-sdk について

sentry-nextjs-sdkは、Next.jsプロジェクトを調べ、ブラウザー、Node.jsサーバー、EdgeランタイムでのSentry設定を案内するコーディングエージェント向けスキルです。ルーターの種類やバージョン、既存ファイルに応じて推奨内容と手順を調整します。

主な機能

  1. 01Next.jsのバージョンとルーターを検出
  2. 02ウィザードまたは手動設定を案内
  3. 03ブラウザー、サーバー、Edgeを設定
  4. 04プロジェクトに応じた可観測性機能の提案
  5. 05エラー捕捉とソースマップを検証

活用シーン

  1. 01既存のNext.jsアプリにSentryを追加
  2. 02エラー監視とトレーシングを設定
  3. 03セッションリプレイ、ログ、プロファイリングを設定
  4. 04各ランタイムのSentry設定を確認

インストール

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

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

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

同梱ファイル

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

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

詳細

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 呼び出しが検出された場合に推奨します
  • ⚡ Cron — 実行されなかった、または失敗したスケジュール済みジョブを検出します。cron のパターンが検出された場合に推奨します
  • ⚡ メトリクス — Sentry.metrics.* によるカスタムメトリクスです。カスタム KPI やビジネスメトリクスが必要な場合に推奨します

推奨ロジック:

機能推奨する条件
エラー監視常に — 必須の基本機能です
トレーシングNext.js では常に — サーバールートのトレーシングとクライアントナビゲーションは非常に有用です
セッションリプレイユーザー向けアプリ、ログインフロー、またはチェックアウトページがある場合
ロギングアプリで構造化ロギングを使用している場合や、ログとトレースの相関が必要な場合
プロファイリングパフォーマンスが重要なアプリで、クライアントが Document-Policy: js-profiling を設定している場合
AI 監視アプリが OpenAI、Vercel AI SDK、または Anthropic を呼び出す場合
Cronアプリに 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 を withSentryConfig() でラップして、ソースマップのアップロードを設定し、動作確認用の /sentry-example-page を追加します。

ウィザードの実行後は、検証に進んでください。


オプション 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___",

  sendDefaultPii: true,

  // 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___",

  sendDefaultPii: true,
  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 を作成 — エッジランタイム
import * as Sentry from "@sentry/nextjs";

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

  sendDefaultPii: true,
  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).*)",
  ],
};

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

ソースマップを使うと、本番環境のスタックトレースを読みやすくできます。ソースマップがない場合は、圧縮されたコードが表示されます。本番アプリでは必須です。

ステップ 1:Sentry 認証トークンを生成する

sentry.io/settings/auth-tokens/ にアクセスし、project:releases および org:read のスコープを持つトークンを作成します。

ステップ 2:環境変数を設定する

# .env.sentry-build-plugin  (gitignore this file)
SENTRY_AUTH_TOKEN=sntrys_eyJ...

または、CI のシークレットに設定します。

SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org        # optional if set in next.config
SENTRY_PROJECT=my-project # optional if set in next.config

ステップ 3:.gitignore に追加する

.env.sentry-build-plugin

ステップ 4:next.config.ts に authToken が設定されていることを確認する

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

ソースマップは、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

機能ごとに、リファレンスファイルを読み、手順に正確に従い、次に進む前に検証してください。


検証

ウィザードまたは手動でセットアップした後、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 ルートハンドラーでエラーをスローします
ソースマップが機能しているスタックトレースに読みやすいファイル名が表示されることを確認します
Session Replay が機能しているSentry ダッシュボードの Replays タブを確認します

設定リファレンス

Sentry.init() のオプション
オプション型デフォルト備考
dsnstring—必須です。クライアントには NEXT_PUBLIC_SENTRY_DSN、サーバーには SENTRY_DSN を使用します
tracesSampleRatenumber—0~1。開発環境では 1.0、本番環境では 0.1 を推奨します
replaysSessionSampleRatenumber0.1記録する全セッションの割合
replaysOnErrorSampleRatenumber1.0記録するエラー発生セッションの割合
sendDefaultPiibooleanfalseイベントに IP とリクエストヘッダーを含めます
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 によって内部的に設定されます)

フェーズ 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() を追加します

コメント