#How to log all request responses including the requests that rejected in guards using fastify

1 messages · Page 1 of 1 (latest)

opaque apex
#

Hi team
We have a requirement to log all requests including headers, body, url, query and the response including body and headers.

Our application has some gurads and interceptor
Also we are using nestjs + express adaptor.

So we developed a middleware and we are able to achieve what we want.

Now because of performance issue we want to use fastify adapter, the issue is in middleware because of how middie is handling the middlewares we don't have access to the body of the request.

We can do the same using interceptors but issue is the requests that are rejected in guards don't reach to interceptor.

I opened a bug in nestjs but seems this is what it is. https://github.com/nestjs/nest/issues/10466

My question is how we can develop such thing to log all req and res including the req that are rejected in guards?

GitHub

Is there an existing issue for this? I have searched the existing issues Current behavior Value of request.body in undefined in middleware when using fastify Minimum reproduction code https://githu...

stark ginkgo
#

I'm working on figuring out an extension to Ogma to allow for logging the requests in exception filters that didn't get logged via the interceptor. I'm close, but I'll probably need a few more weeks to hash it out properly

Otherwise, you could try to add an onRequest and onResponse hook to fastify to log these things out.

The "big" problem with fastify and middleware is that the middleware are executed before the content parsers, so you can't read req.body because it doesn't yet exist. Super annoying kind of feature, I know (p.s. sorry if I came off rude in the issue)

opaque apex
#

@stark ginkgo thanks for the response, would you please link me to read more about OnRequest OnResponse please

opaque apex
#

Yeah, that doesn't work in my case as I need to inject nesjs services (as I already injected in my current middle ware) , services for masking data and ...

stark ginkgo
#

You can still inject (kinda), just gotta know how to set it up 🙂

#

Technically you could inject into the module and use the onModuleInit to set up the hook as I do here, and then have access to the injections of the class

opaque apex
#

Thank you @stark ginkgo I get what you were doing there will try it

opaque apex
opaque apex
#

@stark ginkgo just a friendly reminder in case you missed this ^^