Async Context

You can use the runWithAsyncContext method to isolate Sentry scope and breadcrumbs to a single request if you are using SDK v7.48.0 or higher. This is useful if you are finding that breadcrumbs and scope are leaking across requests.

Copied
const Sentry = require("@sentry/node");

function requestHandlerMiddleware(req, res, next) {
  // Any breadcrumbs or tags added will be isolated to the request
  return Sentry.runWithAsyncContext(() => {
    return next(req, res);
  });
}

Under the hood, the SDK uses Node's AsyncLocalStorage API to perform the isolation.

On lower SDK versions you'll have to use domains to isolate Sentry scope and breadcrumbs to a single request.

Copied
const domain = require("domain");

function myRequestHandler(req, res, next) {
  const localDomain = domain.create();
  return localDomain.bind(() => {
    return next(req, res);
  })();
}
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").