Give every HTTP request an id, send it back in a header, and read it anywhere in that request (also after await) without passing it around. When something fails, one id ties the log lines, the error report and the calls to other services together. No dependencies.
npm install @sandsoftwaresolutions/request-idWorks with import and require(), and ships TypeScript types for both.
Express (or any Connect-style framework):
import { requestId, currentRequestId } from "@sandsoftwaresolutions/request-id";
app.use(requestId());
app.get("/orders", async (req, res) => {
await loadOrders(); // currentRequestId() still works here
res.json({ id: req.id }); // also res.locals.requestId
});Plain node:http:
import { createServer } from "node:http";
import { withRequestId } from "@sandsoftwaresolutions/request-id";
createServer(withRequestId((req, res) => { /* ... */ })).listen(3000);Anywhere else in the request:
import { currentRequestId, propagate } from "@sandsoftwaresolutions/request-id";
currentRequestId(); // "8b1c…" or undefined outside a request
await fetch(url, { headers: propagate({ accept: "application/json" }) }); // adds x-request-idBackground work that outlives the request, or a queue worker:
runWithRequestId(job.requestId, () => handle(job));With the logger from this family (@sandsoftwaresolutions/log-kit) every line gets the id:
const log = createLogger({ mixin: () => ({ requestId: currentRequestId() }) });An x-request-id from the client is used only when it is 8 to 128 characters of letters, digits and . _ : -. Anything else (spaces, line breaks, HTML, too long) is replaced by a new id, so a client cannot inject text into your logs or headers. Trust only your own proxy with trustIncoming: (req) => req.headers["x-forwarded-for"] === ..., or turn it off with trustIncoming: false.
| Option | Default | |
|---|---|---|
header |
x-request-id |
Header to read and write |
generate |
crypto.randomUUID |
Makes a new id |
trustIncoming |
true |
Boolean or (req) => boolean |
setResponseHeader |
true |
Put the id on the response |
No logging, no tracing format (traceparent). It is one id, done safely.
MIT