Nest.js

Learn about using Sentry with Nest.js.

This guide explains how to set up Sentry in your Nest.js application.

You need:

Choose the features you want to configure, and this guide will show you how:

Want to learn more about these features?

Run the command for your preferred package manager to add the Sentry SDK to your application:

Copied
npm install @sentry/nestjs @sentry/profiling-node --save

To import and initialize Sentry, create a file named instrument.(js|mjs) in the root directory of your project and add the following code:

instrument.mjs
Copied
import * as Sentry from "@sentry/nestjs";
import { nodeProfilingIntegration } from '@sentry/profiling-node';

// Ensure to call this before importing 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,
});

Make sure to initialize Sentry before you require or import any other modules in your app. Otherwise, auto-instrumentation won't work for these modules.

Require the instrument.js file before any other modules:

main.ts
Copied
// 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
Copied
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:

Copied
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
  }
}

By default, only unhandled exceptions that are not caught by an error filter are reported to Sentry. HttpExceptions (including derivatives) are also not captured by default because they mostly act as control flow vehicles.

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.

Copied
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 {}

If you have error filters for specific types of exceptions (for example @Catch(HttpException), or any other @Catch(...) with arguments) and you want to capture errors caught by these filters, capture the errors in the catch() handler with Sentry.captureException():

Copied
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)
  }
}

When running your application in ESM mode, use the --import command line option and point it to instrument.mjs to load the module before the application starts:

Copied
# Note: This is only available for Node v18.19.0 onwards.
node --import ./instrument.mjs app.mjs

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:

Copied
npx @sentry/wizard@latest -i sourcemaps

Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.

Copied
@Get("/debug-sentry")
getError() {
  throw new Error("My first Sentry error!");
}

Now, head over to your project on Sentry.io to view the collected data (it takes a couple of moments for the data to appear).

Need help locating the captured errors in your Sentry project?

At this point, you should have integrated Sentry into your Node.js application and should already be sending data to your Sentry project.

Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are:

Are you having problems setting up the SDK?
Was this helpful?
Help improve this content
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").