Skip to content

About

A request id for every HTTP request: accept or create it, send it back in a header, and read it anywhere in the request without passing it around.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

@sandsoftwaresolutions/request-id

CI

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.

Install

npm install @sandsoftwaresolutions/request-id

Works with import and require(), and ships TypeScript types for both.

Usage

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-id

Background 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() }) });

Which incoming ids are trusted

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.

Options

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

Not included

No logging, no tracing format (traceparent). It is one id, done safely.

MIT

About

A request id for every HTTP request: accept or create it, send it back in a header, and read it anywhere in the request without passing it around.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages