Usage

Tracing and Middleware

Isolate request scopes, monitor performance traces, and set transaction names with SentryMiddleware.

Node.js executes concurrent asynchronous requests on a single event loop. Without proper request isolation, context data (such as user information or custom tags) from one request could accidentally leak into another.

@eienjs/adonisjs-sentry includes SentryMiddleware to ensure every incoming HTTP request runs within its own isolated scope while instrumenting transaction names and spans.

Middleware Registration

When you run node ace configure @eienjs/adonisjs-sentry, the middleware is automatically registered in your router middleware stack:

start/kernel.ts
router.use([
  () => import('@eienjs/adonisjs-sentry/middleware/sentry_middleware'),
  // ... other global middleware
]);

How It Works

Inside SentryMiddleware.handle(ctx, next):

  1. Initialization check: If Sentry is not active, the middleware passes directly to next() with zero overhead.
  2. Isolation scope: Wraps request handling in Sentry.withIsolationScope(...), ensuring all tags, breadcrumbs, and user context set during this request remain completely private to this request.
  3. Route resolution: Computes the parameterized route pattern:
    • Primary: ctx.route?.pattern (e.g. /users/:id/posts/:slug)
    • Fallback: ctx.routeKey or 'unknown' for unmatched requests
  4. Transaction naming: Constructs an expressive transaction name using ${method} ${pattern} (e.g. GET /users/:id).
  5. Span updates: Inspects the active root span and updates its name and http.route attribute to match the AdonisJS route.
  6. Request tagging: Sets route, http.method, and request_id (from ctx.request.id()) on the isolated scope.
// Example transaction generated in Sentry
Transaction: "GET /api/v1/projects/:id"
Tags:
  http.method: "GET"
  route: "/api/v1/projects/:id"
  request_id: "ckx9a8h1z000101mh25q1..."

Performance Tracing Sample Rate

To configure the proportion of HTTP transactions captured for performance monitoring, adjust tracesSampleRate in config/sentry.ts:

config/sentry.ts
export default defineConfig({
  // ...
  /**
   * Sample 20% of transactions in production
   */
  tracesSampleRate: 0.2,
});
For high-traffic production environments, consider setting tracesSampleRate between 0.05 (5%) and 0.2 (20%) to optimize quota usage while capturing representative performance data.

Auto-Instrumentation of Database & Third-Party Spans

By default, the service provider initializes Sentry during the provider register() lifecycle. If you need full auto-instrumentation for earlier-imported modules (like database drivers or external HTTP clients), see Early Preloading.