sentry-nestjs-sdk
Full Sentry SDK setup for NestJS. Use when asked to "add Sentry to NestJS", "install @sentry/nestjs", "setup Sentry in NestJS", or configure error monitoring, tracing, profiling, logging, metrics, crons, or AI monitoring for NestJS applications. Supports Express and Fastify adapters, GraphQL, micros
By getsentry · 2,284 installs
npx skills add getsentry/sentry-for-ai --skill sentry-nestjs-sdk
Source repository · Upstream listing
[All Skills](../../SKILL TREE.md) [SDK Setup](../sentry sdk setup/SKILL.md) NestJS SDK
Sentry NestJS SDK
Opinionated wizard that scans your NestJS project and guides you through complete Sentry setup.
Invoke This Skill When
User asks to "add Sentry to NestJS" or "setup Sentry" in a NestJS app
User wants error monitoring, tracing, profiling, logging, metrics, or crons in NestJS
User mentions @sentry/nestjs or Sentry + NestJS
User wants to monitor NestJS controllers, services, guards, microservices, or background jobs
Note: SDK versions and APIs below reflect @sentry/nestjs 10.x (NestJS 8–11 supported).
Always verify against [docs.sentry.io/platforms/node/guides/nestjs/](https://docs.sentry.io/platforms/node/guides/nestjs/) before implementing.
Phase 1: Detect
Run these commands to understand the project before making recommendations:
What to note:
Is @sentry/nestjs already installed? If yes, check if instrument.ts exists and Sentry.init() is called — may just need feature config.
Sentry DI wrapper detected? → The project wraps Sentry behind a DI token (e.g. SENTRY PROXY TOKEN ) for testability. Use the injected proxy for all runtime Sentry calls ( startSpan , captureException , withIsolationScope ) instead of importing @sentry/nestjs directly in controllers, services, and processors. Only instrument.ts should import @sentry/nestjs directly.
Config class detected? → The project uses a typed config class for Sentry.init() options (e.g. loaded from YAML or @nestjs/config ). Any new SDK options must be added to the config type — do not hardcode values that should be configurable per environment.
SentryModule.forRoot() already registered? → If it's in a shared module (e.g. a Sentry proxy module), do not add it again in AppModule — this causes duplicate interceptor registration.
Express (default) or Fastify adapter? Express is fully supported; Fastify works but has known edge cases.
GraphQL detected? → SentryGlobalFilter handles it natively.
Microservices detected? → Recommend RPC exception filter.
Task queues / @nestjs/schedule ? → Recommend crons.
AI libraries? → Auto instrumented, zero config.
Prisma? → Requires manual prismaIntegration() .
Companion frontend? → Triggers Phase 4 cross link.
Phase 2: Recommend
Based on what you found, present a concrete proposal. Don't ask open ended questions — lead with a recommendation:
Always recommended (core coverage):
✅ Error Monitoring — captures unhandled exceptions across HTTP, GraphQL, RPC, and WebSocket contexts
✅ Tracing — auto instruments middleware, guards, pipes, interceptors, filters, and route handlers
Recommend when detected:
✅ Profiling — production apps where CPU performance matters ( @sentry/profiling node )
✅ Logging — structured Sentry Logs + optional console capture
✅ Crons — @nestjs/schedule , Bull, or BullMQ detected
✅ Metrics — business KPIs or SLO tracking
✅ AI Monitoring — OpenAI/Anthropic/LangChain/etc. detected (auto instrumented, zero config)
Recommendation matrix:
Feature Recommend when... Reference
Error Monitoring Always — non negotiable baseline ${SKILL ROOT}/references/error monitoring.md
Tracing Always — NestJS lifecycle is auto instrumented ${SKILL ROOT}/references/tracing.md
Profiling Production + CPU sensitive workloads ${SKILL ROOT}/references/profiling.md
Logging Always; enhanced for structured log aggregation ${SKILL ROOT}/references/logging.md
Metrics Custom business KPIs or SLO tracking ${SKILL ROOT}/references/metrics.md
Crons @nestjs/schedule , Bull, or BullMQ detected ${SKILL ROOT}/references/crons.md
AI Monitoring OpenAI/Anthropic/LangChain/etc. detected ${SKILL ROOT}/references/ai monitoring.md
Propose: "I recommend Error Monitoring + Tracing + Logging. Want Profiling, Crons, or AI Monitoring too?"
Phase 3: Guide
Install
⚠️ Do NOT install @sentry/node alongside @sentry/nestjs — @sentry/nestjs re exports everything from @sentry/node . Installing both causes duplicate registration.
Three File Setup (Required)
NestJS requires a specific three file initialization pattern because the Sentry SDK must patch Node.js modules (via OpenTelemetry) before NestJS loads them.
Before creating new files , check Phase 1 results:
If instrument.ts already exists → modify it, don't create a new one.
If a config class drives Sentry.init() → read options from the config instead of hardcoding env vars.
If a Sentry DI wrapper exists → use it for runtime calls instead of importing @sentry/nestjs directly in services/controllers.
Step 1: Create src/instrument.ts
Config driven Sentry.init() : If Phase 1 found a typed config class (e.g. SentryConfig ), read options from it instead of using raw process.env . This is common in NestJS apps that use @nestjs/config or custom config loaders:
When adding new SDK options (e.g. dataCollection , profileSessionSampleRate ), add them to the config type so they can be configured per environment.
Step 2: Import instrument.ts FIRST in src/main.ts
Why first? OpenTelemetry must monkey patch http , express , database drivers, and other modules before they load. Any module that loads before instrument.ts will not be auto instrumented.
Step 3: Register SentryModule and SentryGlobalFilter in src/app.module.ts
What each piece does:
SentryModule.forRoot() — registers SentryTracingInterceptor as a global APP INTERCEPTOR , enabling HTTP transaction naming
SentryGlobalFilter — extends BaseExceptionFilter ; captures exceptions across HTTP, GraphQL (rethrows HttpException without reporting), and RPC contexts
⚠️ Do NOT register SentryModule.forRoot() twice. If Phase 1 found it already imported in a shared library module (e.g. a SentryProxyModule or AnalyticsModule ), do not add it again in AppModule . Duplicate registration causes every span to be intercepted twice, bloating trace data.
⚠️ Two entrypoints, different imports:
@sentry/nestjs → SDK init, capture APIs, decorators ( SentryTraced , SentryCron , SentryExceptionCaptured )
@sentry/nestjs/setup → NestJS DI constructs ( SentryModule , SentryGlobalFilter )
Never import SentryModule from @sentry/nestjs (main entrypoint) — it loads @nestjs/common before OpenTelemetry patches it, breaking auto instrumentation.
ESM Setup (Node ≥ 18.19.0)
For ESM applications, use import instead of a file import:
Or via environment:
Exception Filter Options
Choose the approach that fits your existing architecture:
Option A: No existing global filter — use SentryGlobalFilter (recommended)
Already covered in Step 3 above. This is the simplest option.
Option B: Existing custom global filter — add @SentryExceptionCaptured() decorator
Option C: Specific exception type — manual capture
Option D: Microservice RPC exceptions
Decorators
@SentryTraced(op?) — Instrument any method
@SentryCron(slug, config?) — Monitor scheduled jobs
Background Job Scope Isolation
Background jobs share the default isolation scope — wrap with Sentry.withIsolationScope() to prevent cross contamination:
Apply withIsolationScope to: @Cron() , @Interval() , @OnEvent() , @Processor() , and any code outside the request lifecycle.
Working with Sentry DI Wrappers
Some NestJS projects wrap Sentry behind a dependency injection token (e.g. SENTRY PROXY TOKEN ) for testability and decoupling. If Phase 1 detected this pattern, use the injected service for all runtime Sentry calls — do not import @sentry/nestjs directly in controllers, services, or processors.
Where direct @sentry/nestjs import is still correct:
instrument.ts — always uses import as Sentry from "@sentry/nestjs" for Sentry.init()
Standalone scripts and exception filters that run outside the DI container
Verification
Add a test endpoint to confirm events reach Sentry:
Hit GET /debug sentry and check the Sentry Issues dashboard within seconds.
For Each Agreed Feature
Walk through features one at a time. Load the reference, follow its steps, verify before moving on:
Feature Reference file Load when...
Error Monitoring ${SKILL ROOT}/references/error monitoring.md Always (baseline)
Tracing ${SKILL ROOT}/references/tracing.md Always (NestJS routes are auto traced)
Profiling ${SKILL ROOT}/references/profiling.md CPU intensive production apps
Logging ${SKILL ROOT}/references/logging.md Structured log aggregation needed
Metrics ${SKILL ROOT}/references/metrics.md Custom KPIs / SLO tracking
Crons ${SKILL ROOT}/references/crons.md Scheduled jobs or task queues
AI Monitoring ${SKILL ROOT}/references/ai monitoring.md OpenAI/Anthropic/LangChain detected
For each feature: Read ${SKILL ROOT}/references/<feature .md , follow steps exactly, verify it works.
Configuration Reference
Key Sentry.init() Options
Option Type Default Purpose
dsn string — SDK disabled if empty; env: SENTRY DSN
environment string "production" e.g., "staging" ; env: SENTRY ENVIRONMENT
release string — e.g., "myapp@1.0.0" ; env: SENTRY RELEASE
dataCollection object See below Controls what data the SDK collects (SDK ≥ 10.57.0)
dataCollection.userInfo boolean true Include IP addresses and user context
dataCollection.httpHeaders object See below Capture HTTP headers for requests/responses
dataCollection.cookies boolean\ object true Capture cookies; use {allow: [...]} or {deny: [...]} for filtering
dataCollection.queryParams boolean\ object true Capture URL query parameters; use {allow: [...]} or {deny: [...]} for filtering
dataCollection.genAI object See below Control AI input/output recording
sendDefaultPii boolean false Deprecated — use dataCollection.userInfo instead
tracesSampleRate number — Transaction sample rate; undefined disables tracing
tracesSampler function — Custom per transaction sampling (overrides rate)
tracePropagationTarge