16 lines
577 B
TypeScript
16 lines
577 B
TypeScript
// api/src/plugins/request-id.ts
|
|
import type { FastifyPluginCallback } from "fastify";
|
|
import { randomUUID } from "crypto";
|
|
|
|
const requestIdPlugin: FastifyPluginCallback = (app, _opts, done) => {
|
|
app.addHook("onRequest", async (req, reply) => {
|
|
const incoming = (req.headers["x-request-id"] as string | undefined)?.trim();
|
|
const id = incoming && incoming.length > 0 ? incoming : randomUUID();
|
|
(req as any).id = id; // attach to request
|
|
reply.header("x-request-id", id); // echo on response
|
|
});
|
|
done();
|
|
};
|
|
|
|
export default requestIdPlugin;
|