Skip to content

docs(js): Review and update Nest.js Quick Start guide #13497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
May 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 109 additions & 3 deletions docs/platforms/javascript/guides/nestjs/index.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: Nest.js
description: "Learn about using Sentry with Nest.js."
description: "Learn how to set up Sentry in your Nest.js app and capture your first errors."
sdk: sentry.javascript.nestjs
fallbackGuide: javascript.node
categories:
Expand All @@ -9,6 +9,112 @@ categories:
- server-node
---

This guide explains how to set up Sentry in your Nest.js application.
<PlatformContent includePath="getting-started-prerequisites" />

<PlatformContent includePath="getting-started-node" />
## Step 1: Install

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

<OnboardingOptionButtons
options={["error-monitoring", "performance", "profiling"]}
/>

<PlatformContent includePath="getting-started-features-expandable" />

### Install the Sentry SDK

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

<PlatformContent includePath="getting-started-install" />

## Step 2: Configure

### Initialize the Sentry SDK

To import and initialize Sentry, create a file named `instrument.ts` in the root directory of your project and add the following code:

<PlatformContent includePath="getting-started-config" />

### Apply Instrumentation to Your App

Make sure to import the `instrument.ts` file before any other modules:

```typescript {filename: main.ts} {1-2}
// 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();
```

Afterward, add the `SentryModule` as a root module to your main module:

```typescript {filename: app.module.ts} {2, 8}
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 {}
```

## Step 3: Capture Nest.js Errors

<PlatformContent includePath="getting-started-capture-errors" />

## Step 4: Add Readable Stack Traces With Source Maps (Optional)

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:

```bash
npx @sentry/wizard@latest -i sourcemaps
```

## Step 5: Verify Your Setup

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

<PlatformContent includePath="getting-started-verify" />

### View Captured Data in Sentry

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

<PlatformContent includePath="getting-started-verify-locate-data" />

## Next Steps

At this point, you should have integrated Sentry into your Nest.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:

- Extend Sentry to your frontend using one of our [frontend SDKs](/)
- Learn how to [manually capture errors](/platforms/javascript/guides/nestjs/usage/)
- Continue to [customize your configuration](/platforms/javascript/guides/nestjs/configuration/)
- Get familiar with [Sentry's product features](/product) like tracing, insights, and alerts

<Expandable permalink={false} title="Are you having problems setting up the SDK?">

- Check out alternative <PlatformLink to="/install">installation methods</PlatformLink>
- Find various topics in <PlatformLink to="/troubleshooting">Troubleshooting</PlatformLink>
- [Get support](https://sentry.zendesk.com/hc/en-us/)

</Expandable>
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
By default, Sentry only captures unhandled exceptions that aren't caught by an error filter.
Additionally, `HttpException`s (including [derivatives](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)) aren't captured by default because they mostly act as control flow vehicles.

To make sure Sentry captures all your app's errors, configure error handling based on how your application manages exceptions:

### Using a Custom Global Filter

If you have a global catch-all exception filter, add a `@SentryExceptionCaptured()` decorator to the filter's `catch()` method:

```typescript {2, 6}
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
}
}
```

### Not Using a Custom Global Filter

If you don't have a global catch-all exception filter, add the `SentryGlobalFilter` to the providers of your main module, **before** any other exception filters:

```typescript {2-3, 7-10}
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 {}
```

### Using Error Filters for Specific Exception Types

If you have error filters for specific types of exceptions (for example, `@Catch(HttpException)`) and you want to report these errors to Sentry, you need to capture them in the `catch()` handler using `Sentry.captureException()`:

```typescript {4,9}
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);
}
}
```

<Expandable title="Are you using Microservices?">
If you're using `@nestjs/microservices` make sure to handle errors in RPC contexts correctly by providing your own `RpcExceptionFilter` (see [Nest.js Microservices documentation](https://docs.nestjs.com/microservices/exception-filters)).
`SentryGlobalFilter` in a [hybrid application](https://docs.nestjs.com/faq/hybrid-application) doesn't extend `BaseRpcExceptionFilter` since this depends on `@nestjs/microservices`.

Use `Sentry.captureException(exception)` in your custom filter in case you want to send these errors to Sentry:

```typescript
import { Catch, RpcExceptionFilter, ArgumentsHost } from "@nestjs/common";
import { Observable, throwError } from "rxjs";
import { RpcException } from "@nestjs/microservices";
import * as Sentry from "@sentry/nestjs";

@Catch(RpcException)
export class ExceptionFilter implements RpcExceptionFilter<RpcException> {
catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
Sentry.captureException(exception); // optional
return throwError(() => exception.getError());
}
}
```

</Expandable>
48 changes: 9 additions & 39 deletions platform-includes/getting-started-config/javascript.nestjs.mdx
Original file line number Diff line number Diff line change
@@ -1,39 +1,4 @@
```javascript {tabTitle:ESM} {filename: instrument.mjs}
import * as Sentry from "@sentry/nestjs";
// ___PRODUCT_OPTION_START___ profiling
import { nodeProfilingIntegration } from '@sentry/profiling-node';
// ___PRODUCT_OPTION_END___ profiling

// Ensure to call this before importing any other modules!
Sentry.init({
dsn: "___PUBLIC_DSN___",

// Adds request headers and IP for users, for more info visit:
// https://docs.sentry.io/platforms/javascript/guides/nestjs/configuration/options/#sendDefaultPii
sendDefaultPii: true,

// ___PRODUCT_OPTION_START___ profiling
integrations: [
// Add our Profiling integration
nodeProfilingIntegration(),
],
// ___PRODUCT_OPTION_END___ profiling
// ___PRODUCT_OPTION_START___ performance

// Add Tracing by setting tracesSampleRate
// We recommend adjusting this value in production
tracesSampleRate: 1.0,
// ___PRODUCT_OPTION_END___ performance
// ___PRODUCT_OPTION_START___ profiling

// Set sampling rate for profiling
// This is relative to tracesSampleRate
profilesSampleRate: 1.0,
// ___PRODUCT_OPTION_END___ profiling
});
```

```javascript {tabTitle:CommonJS} {filename: instrument.js}
```typescript {filename: instrument.ts}
const Sentry = require("@sentry/nestjs");
// ___PRODUCT_OPTION_START___ profiling
const { nodeProfilingIntegration } = require("@sentry/profiling-node");
Expand All @@ -50,16 +15,21 @@ Sentry.init({
// ___PRODUCT_OPTION_END___ profiling
// ___PRODUCT_OPTION_START___ performance

// Add Tracing by setting tracesSampleRate
// Set tracesSampleRate to 1.0 to capture 100%
// of transactions for tracing.
// We recommend adjusting this value in production
// Learn more at
// https://docs.sentry.io/platforms/javascript/guides/nestjs/configuration/options/#tracesSampleRate
tracesSampleRate: 1.0,
// ___PRODUCT_OPTION_END___ performance
// ___PRODUCT_OPTION_START___ profiling

// Set sampling rate for profiling
// Set profilesSampleRate to 1.0 to profile 100%
// of sampled transactions.
// This is relative to tracesSampleRate
// Learn more at
// https://docs.sentry.io/platforms/javascript/guides/nestjs/configuration/options/#profilesSampleRate
profilesSampleRate: 1.0,
// ___PRODUCT_OPTION_END___ profiling
});
```

1 change: 1 addition & 0 deletions platform-includes/getting-started-node/javascript.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ Our next recommended steps for you are:
<Expandable permalink={false} title="Are you having problems setting up the SDK?">

- Check out alternative <PlatformLink to="/install">installation methods</PlatformLink>
- Find various topics in <PlatformLink to="/troubleshooting">Troubleshooting</PlatformLink>
- [Get support](https://sentry.zendesk.com/hc/en-us/)

</Expandable>
91 changes: 6 additions & 85 deletions platform-includes/getting-started-use/javascript.nestjs.mdx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
```javascript {filename: main.ts}
Make sure to import the `instrument.ts` file before any other modules:

```typescript {filename: main.ts} {1-2}
// Import this first!
import "./instrument";

Expand All @@ -14,9 +16,9 @@ async function bootstrap() {
bootstrap();
```

Afterwards, add the `SentryModule` as a root module to your main module:
Afterward, add the `SentryModule` as a root module to your main module:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Afterward, add the `SentryModule` as a root module to your main module:
Afterwards, add the `SentryModule` as a root module to your main module:

I think? 😅

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both forms are correct, although the variant with “s” is used in British English and the one without in American English 👍


```javascript {filename: app.module.ts} {2, 8}
```typescript {filename: app.module.ts} {2, 8}
import { Module } from "@nestjs/common";
import { SentryModule } from "@sentry/nestjs/setup";
import { AppController } from "./app.controller";
Expand All @@ -33,85 +35,4 @@ import { AppService } from "./app.service";
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:

```javascript {2, 6}
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.
`HttpException`s (including [derivatives](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)) 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.

```javascript {3, 9}
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 {}
```

<Expandable title="Using Microservices?">

If you are using `@nestjs/microservices` make sure to handle errors in RPC contexts correctly by providing your own `RpcExceptionFilter` (see https://docs.nestjs.com/microservices/exception-filters).
`SentryGlobalFilter` in a [hybrid application](https://docs.nestjs.com/faq/hybrid-application) does not extend `BaseRpcExceptionFilter` since this depends on `@nestjs/microservices`.

Use `Sentry.captureException(exception)` in your custom filter in case you want to send these errors to Sentry:

```typescript
import { Catch, RpcExceptionFilter, ArgumentsHost } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { RpcException } from '@nestjs/microservices';
import * as Sentry from '@sentry/nestjs';

@Catch(RpcException)
export class ExceptionFilter implements RpcExceptionFilter<RpcException> {
catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
Sentry.captureException(exception); // optional
return throwError(() => exception.getError());
}
}
```


</Expandable>


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()`:

```javascript {9}
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)
}
}
```
<PlatformContent includePath="getting-started-capture-errors" />
Loading