requestId function

Middleware requestId({
  1. String headerName = 'X-Request-Id',
  2. String generator()?,
})

Request ID middleware — assigns a unique identifier to each request.

Honors an incoming headerName value when present (useful behind a proxy that already injects one); otherwise generates a UUID v4. The id is stored in the context (read it with requestIdOf or c.get<String>('requestId')) and echoed back in the response header.

import 'package:darto/request_id.dart';

app.use(requestId());

app.get('/', [], (c) => c.ok({'id': requestIdOf(c)}));

Implementation

Middleware requestId({
  String headerName = 'X-Request-Id',
  String Function()? generator,
}) {
  return (Context c, Next next) async {
    final incoming = c.req.header(headerName);
    final id = (incoming != null && incoming.isNotEmpty)
        ? incoming
        : (generator ?? _uuidV4)();
    c.set('requestId', id);
    c.header(headerName, id);
    await next();
  };
}