ericjeker / nestjs-sentry-example

Explanations and example project on how to setup Sentry in a Nest.js project
MIT No Attribution
83 stars 16 forks source link

Description

Example of a Sentry setup for Nest.js framework.

Just read this doc and explore the code for more details. If you want a more basic example or add Sentry in an existing project just follow the Step by Step below.

Sentry provides their own Nest.js example here and you can read their documentation here.

Below I mark a few differences between their example and mine:

Migration from v2.0 to v3.0

The previous version of this example was using Sentry SDK v7.x. The new version uses Sentry SDK v8.0. In v8.0, the SDK is doing pretty much everything for you, so it's more a matter of configuration than coding.

We removed the SentryInterceptor, SentryService, SentryModule classes and added a instrument.ts file. The main.ts file has changed and include the Sentry.init(...) call through the instrument.ts file and the Sentry.setupNestErrorHandler() call.

Installation

To run this example, clone this repository and install the dependencies. Then copy .env.sample to .env and insert your own Sentry DSN. You can find the DSN for your project on Sentry.io in Project Setting / Client Keys.

Then run Nest using the usual command:

npm run start:debug

Sample Error

Note: by default the error and tracing are disabled in DEVELOPMENT environment. You can change this in the instrument.ts

Once the Nest.js server is running you can go to http://localhost:3000/throw, it will create a sample error in your Sentry project.

Testing

You can run the E2E test like so:

npm run test:e2e

In the test/load directory you will find two Artillery scripts to test the performance of your application. You can run them using the following commands:

npx artillery run test/load/smoke-test.yml

Be careful not to eat up your quota on Sentry.

Step by step

Below are some explanations on how to do a clean setup from scratch or in an existing project.

Installation

If you start from scratch, create a new Nest app using the CLI

nest new sentry-setup
cd sentry-setup

Then install dotenv and Sentry Node.js SDK

npm i --save dotenv @sentry/node

Add the SENTRY_DSN to your .env file.

Create the instrument.ts file and call Sentry.setupNestErrorHandler() in the main.ts file. This will automatically catch all errors in your application and send them to Sentry.

Below is a very basic example of the instrument.ts file:

import * as Sentry from '@sentry/node';
import 'dotenv/config';

// Ensure to call this before importing any other modules!
Sentry.init({
  dsn: process.env.SENTRY_DSN, 

  // Add Performance Monitoring by setting tracesSampleRate
  // We recommend adjusting this value in production
  tracesSampleRate: 1.0,
});