NextJs - Logging - correlationId - headers - how?

756 views Asked by At

This is a tough one to explain, but I'll try and I'm hoping someone can help. The work required:

Using pino as a logger, for every request on the server , a unique ID generated client side in the headers, so a log may be something like:

level: 30,
name: 'my-app',
msg: 'generated xyz page'
correlationId: <unique-id from request>

This will ultimately end up in kibana, but that makes no difference - the important thing is that there's a unique ID that originates from a client request - correlationId - that's what I'm after.

Currently using NextJS 12.x for this.

In middleware.ts I can generate a cookie very easily - doing a check to see if the correlationId cookie is set - if it is, use it, if not, use something like nanoid to generated a unique ID.

The problem is, how do I access that header request in my app? I want something along the lines of (pseudo code here) :

request.cookies('correlationId')

In Next 12.x there is zero access to the bulk of the request headers in getStaticProps or getServerSideProps - the best that can be done is the URL parameters.

I cannot use params for this, it has to be in the request header. I want to be able to set that cookie and then use it server side in logging, providing a unique ID for each visitor in logging.

I'm fine with having to repeat code for each log message, but ideally, I want to wrap that up in a method that automatically includes the correlationId in a pino log.

Pino provides all sorts of great methods to facilitate this ... but Next.js ? - the request once it gets beyond middleware, is just ... hobbled, cut down, stripped. I know that in 13.x with server components, we get access to the request data - but as a team, we're not ready for 13.x yet - still many beta features.

Does this explain what I really need?

Like I said, complex.

0

There are 0 answers