Nestjs
Learn about using Sentry with Nest.js.
This guide explains how to set up Sentry in your Nest.js application.
If you don't already have an account and a Sentry project established, sign up for Sentry for free, then return to this page.
In addition to capturing errors, you can monitor interactions between multiple services or applications by enabling tracing. You can also collect and analyze performance profiles from real users with profiling.
Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below.
Sentry captures data by using an SDK within your application’s runtime.
npm install @sentry/nestjs --save
npm install @sentry/nestjs @sentry/profiling-node --save
Sentry should be initialized in your app as early as possible. It's essential that you call Sentry.init
before you require any other modules in your application, otherwise, auto-instrumentation won't work for these modules.
Once this is done, Sentry's Node SDK will capture unhandled exceptions as well as tracing data for your application.
To import and initialize Sentry, you'll need to create a file named instrument.js
:
instrument.js
const Sentry = require("@sentry/nestjs");
const { nodeProfilingIntegration } = require("@sentry/profiling-node");
// Ensure to call this before requiring any other modules!
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
// Add our Profiling integration
nodeProfilingIntegration(),
],
// Add Tracing by setting tracesSampleRate
// We recommend adjusting this value in production
tracesSampleRate: 1.0,
// Set sampling rate for profiling
// This is relative to tracesSampleRate
profilesSampleRate: 1.0,
});
Once you set a tracesSampleRate
, performance instrumentation will be automatically enabled. Read about Automatic Instrumentation to learn more about what the SDK can automatically instrument for you.
You can also manually capture performance data - see Custom Instrumentation for details.
To ensure that Sentry can automatically instrument all modules in your application, you'll need to require or import the instrument.js
file before requiring any other modules in your application:
main.ts
// Import this first!
import "./instrument";
// Now import other modules
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
Afterwards, add the SentryModule
as a root module to your main module:
app.module.ts
import { Module } from "@nestjs/common";
import { SentryModule } from "@sentry/nestjs/setup";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
@Module({
imports: [
SentryModule.forRoot(),
// ...other modules
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
If you're using a global catch-all exception filter (which is either a filter registered with app.useGlobalFilters()
or a filter registered in your app module providers annotated with a @Catch()
decorator without arguments), add a @SentryExceptionCaptured()
decorator to the filter's catch()
method. This decorator will report all unexpected errors that are received by your global error filter to Sentry:
import { Catch, ExceptionFilter } from '@nestjs/common';
import { SentryExceptionCaptured } from '@sentry/nestjs';
@Catch()
export class YourCatchAllExceptionFilter implements ExceptionFilter {
@SentryExceptionCaptured()
catch(exception, host): void {
// your implementation here
}
}
Note that @SentryExceptionCaptured()
was called @WithSentry
in SDK versions 8.38.0
and prior.
If you don't have a global catch-all exception filter, add the SentryGlobalFilter
to the providers of your main module. This filter will report any unhandled errors that aren't caught by other error filters to Sentry. Important: The SentryGlobalFilter
needs to be registered before any other exception filters.
import { Module } from "@nestjs/common";
import { APP_FILTER } from "@nestjs/core";
import { SentryGlobalFilter } from "@sentry/nestjs/setup";
@Module({
providers: [
{
provide: APP_FILTER,
useClass: SentryGlobalFilter,
},
// ..other providers
],
})
export class AppModule {}
Note: If you have a NestJS + GraphQL application and you are using the @sentry/nestjs
SDK version 8.38.0
or earlier, replace the SentryGlobalFilter
with the SentryGlobalGenericFilter
. In SDK versions 8.39.0
and above, the SentryGlobalGenericFilter
is deprecated because the SentryGlobalFilter
will handle GraphQL contexts automatically.
By default, exceptions with status code 4xx are not sent to Sentry. If you still want to capture these exceptions, you can do so manually with Sentry.captureException()
:
import { ArgumentsHost, BadRequestException, Catch } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { ExampleException } from './example.exception';
import * as Sentry from '@sentry/nestjs';
@Catch(ExampleException)
export class ExampleExceptionFilter extends BaseExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
Sentry.captureException(exception);
return super.catch(new BadRequestException(exception.message), host)
}
}
Running with ESM
If you run your application with ESM, you'll need to import the Sentry Initialization file before importing any other modules. Read about running Sentry with ESM. If you're not sure about how you're running your application, see Installation Methods for more information.
Depending on how you've set up your project, the stack traces in your Sentry errors probably won't look like your actual code.
To fix this, upload your source maps to Sentry. The easiest way to do this is by using the Sentry Wizard:
npx @sentry/wizard@latest -i sourcemaps
The wizard will guide you through the following steps:
- Logging into Sentry and selecting a project
- Installing the necessary Sentry packages
- Configuring your build tool to generate and upload source maps
- Configuring your CI to upload source maps
For more information on source maps or for more options to upload them, head over to our Source Maps documentation.
This snippet includes an intentional error, so you can test to make sure that everything is working as soon as you set it up.
@Get("/debug-sentry")
getError() {
throw new Error("My first Sentry error!");
}
Learn more about manually capturing an error or message in our Usage documentation.
To view and resolve the recorded error, log into sentry.io and select your project. Clicking on the error's title will open a page where you can see detailed information and mark it as resolved.
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").