-
Hi, I want to be able to add correlation ids to my app using express-zod-api. My initial idea was to use
This middleware would be added to my custom endpoint
The problem is that the console output is
The ultimate goal is to have a custom formatter in my winston that would send the request id to Loki. One suggestion is that it is caused by https://stackoverflow.com/questions/55611335/node-js-express-unable-to-retrieve-value-from-http-context-for-post-and-put-re/58546037#58546037 But i am not able to change the order of middleware's here :( @RobinTail any idea what to do here, or how to achieve the ability to have a request id in my log classes? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
Hello @pupca . Before I get to your actual question, I noticed something I'd like to suggest. .addExpressMiddleware(cors({ credentials: true })) with an option in your config: createConfig({
cors: ({ defaultHeaders }) => ({ ...defaultHeaders, "Access-Control-Allow-Credentials": true })
}) It's acts the same, according to documentation and specification, but this way you can reduce your dependencies and keep the control on CORS headers in one place. Regarding |
Beta Was this translation helpful? Give feedback.
-
They recommend to place body parser before, but it's already before every |
Beta Was this translation helpful? Give feedback.
-
@RobinTail first of all, thank you very much for looking into that! I have modified the cors settings, thank you! Perhaps you can think of any other solution that would make correlation id available from within logger classes... |
Beta Was this translation helpful? Give feedback.
-
@pupca , here is what I found out. import { v4 } from "uuid";
import * as httpContext from "express-http-context";
app.use(httpContext.middleware).use(({}, res, next) => {
const requestId = v4();
httpContext.set("requestId", requestId);
console.log("the id", httpContext.get("requestId"));
res.setHeader("x-request-id", requestId);
next();
}); I tested it and it works. |
Beta Was this translation helpful? Give feedback.
@pupca , here is what I found out.
This solution works fine, when you apply the
express-http-context
middleware directly to express app (not by using.addExpressMiddleware
).Therefore, consider going with custom express app approach and
attachRouting()
method, described in the documentation, and applying the following lines to your ownapp
:I tested it and it works.