sentry-nextjs-sdk について
Next.jsプロジェクトにSentryを導入するためのセットアップスキルです。ブラウザー、Node.jsサーバー、Edgeの各ランタイムを調査し、SDKの設定や機能選択、検証を案内します。
主な機能
- 01Next.jsのバージョンとルーターを検出
- 023種類のランタイム設定を案内
- 03監視・可観測性機能を設定
- 04ウィザードと手動設定に対応
- 05ソースマップのアップロードを案内
活用シーン
- 01Next.jsアプリへのSentry導入
- 02プロジェクトに合う監視機能の選択
- 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.mdcrons.mderror-monitoring.mdlogging.mdmetrics.mdprofiling.mdsession-replay.mdtracing.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.md | Vercel Cron、スケジュールされた API ルート、node-cron |
| メトリクス | references/metrics.md | Sentry.metrics.* によるカスタムカウンター、ゲージ、分布 |
各機能について、リファレンスファイルを読み、手順に正確に従って、次に進む前に検証します。
設定リファレンス
Sentry.init() のオプション
| オプション | 型 | デフォルト | 備考 |
|---|---|---|---|
dsn | string | — | 必須です。クライアントには NEXT_PUBLIC_SENTRY_DSN、サーバーには SENTRY_DSN を使用します |
tracesSampleRate | number | — | 0~1。開発環境では 1.0、本番環境では 0.1 を推奨します |
replaysSessionSampleRate | number | 0.1 | 記録する全セッションの割合 |
replaysOnErrorSampleRate | number | 1.0 | 記録するエラー発生セッションの割合 |
dataCollection | object | 設定しない場合は保守的 | 自動収集するカテゴリ(userInfo、cookies、httpHeaders、httpBodies、queryParams、genAI)をきめ細かく制御します。省略すると、SDK は sendDefaultPii(デフォルトは false)にフォールバックします。このオブジェクトを渡すと({} も含む)、未設定のカテゴリは許可するデフォルト値に切り替わります。カテゴリごとにオプトアウトできます。 |
includeLocalVariables | boolean | false | スタックフレームにローカル変数の値を付加します(サーバーのみ) |
enableLogs | boolean | false | Sentry Logs 製品を有効にします |
environment | string | 自動 | "production"、"staging" など |
release | string | 自動 | コミット SHA またはバージョンタグを設定します |
debug | boolean | false | SDK の動作をコンソールに記録します |
withSentryConfig() のオプション
| オプション | 型 | 備考 |
|---|---|---|
org | string | Sentry 組織のスラッグ |
project | string | Sentry プロジェクトのスラッグ |
authToken | string | ソースマップのアップロードトークン(SENTRY_AUTH_TOKEN) |
widenClientFileUpload | boolean | スタックトレースの精度向上のため、クライアントファイルをより多くアップロードします |
tunnelRoute | string | 広告ブロッカーを回避するための API ルートパス(例:"/monitoring") |
silent | boolean | ビルド出力を抑制します(!process.env.CI を推奨) |
webpack.treeshake.* | object | SDK の機能をツリーシェイクします(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() を追加します |