Next.js Middleware
Automatic request logging and correlation ID propagation.
Overview
The vestig middleware:
- Generates correlation IDs — requestId, traceId, spanId
- Logs requests/responses — Method, path, status, duration
- Propagates context — IDs flow to Server Components and Route Handlers
- Supports W3C Trace Context — Compatible with distributed tracing
Setup
typescript
Configuration
typescript
Skip Paths
Exclude paths from logging:
typescript
Request Logging
Each request is logged with:
json
Response Logging
Each response is logged with:
json
Correlation Headers
The middleware sets response headers:
text
Using Upstream Request IDs
If a request comes with a request ID header, vestig uses it:
typescript
bash
W3C Trace Context
For distributed tracing, vestig supports the traceparent header:
text
typescript
Custom Middleware Logic
Extend the middleware with custom logic:
typescript
Accessing Context in Components
The middleware stores correlation context that's available in Server Components:
typescript
Edge Runtime
The middleware works in both Node.js and Edge runtimes:
typescript
Performance
The middleware is designed to be fast:
- Minimal overhead — Sub-millisecond logging
- Async logging — Doesn't block responses
- Efficient ID generation — Uses crypto.randomUUID()
- Path matching — Fast skip path checks