@gfx687/express-request-id
v1.0.3
Published
Express middleware to generate or propagate X-Request-ID request header.
Downloads
83
Readme
express-request-id
Middleware for express to generate or propagate X-Request-ID
(or other custom) request header.
Installation
Install @gfx687/express-request-id with:
npm install @gfx687/express-request-id
Peer dependencies:
Usage
Basic usage example:
import express from "express";
import { requestID } from "@gfx687/express-request-id";
const app = express();
const port = 3000;
app.use(requestID());
app.get("/", (req: express.Request, res: express.Response) => {
res.send(`Request with ID=${req.id} received!`);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
Accessing Request ID
Request ID is accessible via express.Request
object's id
field.
Example:
app.get("/", (req: express.Request, res: express.Response) => {
res.send(`Request with ID=${req.id} received!`);
});
Customizing Middleware
Middleware accepts options object of the following format:
type Options = {
// default = node's crypto.randomUUID()
generator?: (request: Request) => string;
// default = 'X-Request-ID'
headerName?: string;
// default = true
setResponseHeader?: boolean;
};
Usage example:
app.use(
requestID({
generator: (expressRequest) => customIdGenerator(expressRequest),
headerName: "correlation-id",
setResponseHeader: false,
})
);