This commit was merged in pull request #87.
This commit is contained in:
18
artifacts/api-server/src/middlewares/request-id.ts
Normal file
18
artifacts/api-server/src/middlewares/request-id.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import crypto from "crypto";
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
|
||||
const HEADER = "X-Request-Id";
|
||||
|
||||
/**
|
||||
* Assigns a unique request ID to every incoming request.
|
||||
* If the client (or a reverse proxy) already sent X-Request-Id, reuse it;
|
||||
* otherwise generate a short random hex string.
|
||||
* The ID is stored on `res.locals.requestId` for downstream middleware/routes
|
||||
* and echoed back via the X-Request-Id response header.
|
||||
*/
|
||||
export function requestIdMiddleware(req: Request, res: Response, next: NextFunction): void {
|
||||
const id = (req.headers[HEADER.toLowerCase()] as string | undefined) ?? crypto.randomUUID();
|
||||
res.locals["requestId"] = id;
|
||||
res.setHeader(HEADER, id);
|
||||
next();
|
||||
}
|
||||
Reference in New Issue
Block a user