Search code examples
node.jssentry

How to send request information with Sentry's new unified SDK?


The legacy Sentry Node SDK (raven) allowed sending HTTP request information along with the error, by passing the request object inside the options object (2nd argument):

Raven.captureException(someError, { req: req });

Line of code extracted from the documentation: https://docs.sentry.io/clients/node/usage/#raven-recording-breadcrumbs

With that we could get additional context about the error, such as what was the device being used.

Is there any way we can pass the request object with the new SDK? The context section of the new SDK explains how to send data such as user identification, custom tags, etc by using scopes, but no request option is available in there. Does this mean that the request information should now be manually sent inside tags and/or extra objects?


Solution

  • As @MarkusUnterwaditzer shared, the Express integration worked for me: https://docs.sentry.io/platforms/node/express/ The key parts are adding the Sentry.Handlers.requestHandler() middleware and then either the errorHandler middleware or doing Sentry.captureException(error) yourself (with no need to pass in {req: req}).

    Sample code:

    const express = require('express');
    const app = express();
    const Sentry = require('@sentry/node');
    
    Sentry.init({ dsn: 'https://[email protected]/280382' });
    
    // The request handler must be the first middleware on the app
    app.use(Sentry.Handlers.requestHandler());
    
    app.get('/', function mainHandler(req, res) {
      throw new Error('Broke!');
    });
    
    // The error handler must be before any other error middleware
    app.use(Sentry.Handlers.errorHandler());
    
    // Optional fallthrough error handler
    app.use(function onError(err, req, res, next) {
      // The error id is attached to `res.sentry` to be returned
      // and optionally displayed to the user for support.
      res.statusCode = 500;
      res.end(res.sentry + '\n');
    });
    
    app.listen(3000);