I'm using
Nestjs CLI 9.0.0
Nestjs common - Nestjs Platform Fastify 9.0.11
Fastify - 4.4.0
@fastify/cookie - 8.0.0
I try to use cookie and set cookie in middleware. But it seems all about cookie is undefined.
this.logger.debug("cookies", request.cookies)
this.logger.debug("setCookie", response.setCookie)
this.logger.debug("cookie", response.cookie)
Log from Middleware
DEBUG [DeviceMiddleware] cookies
DEBUG [DeviceMiddleware] undefined
DEBUG [DeviceMiddleware] setCookie
DEBUG [DeviceMiddleware] undefined
DEBUG [DeviceMiddleware] cookie
DEBUG [DeviceMiddleware] undefined
Log from Controller
DEBUG [AppController] cookies
DEBUG [AppController] Object:
{}
DEBUG [AppController] setCookie
DEBUG [AppController] function setCookie (name, value, cookieOptions) {
const opts = Object.assign({}, options.parseOptions, cookieOptions)
return fastifyCookieSetCookie(this, name, value, opts, signer)
}
DEBUG [AppController] cookie
DEBUG [AppController] function setCookie (name, value, cookieOptions) {
const opts = Object.assign({}, options.parseOptions, cookieOptions)
return fastifyCookieSetCookie(this, name, value, opts, signer)
}
Coming back with a clear mind this isn't a bug at all, nor is it related to when parts of the code are ran. It's related to how middleware works in Nest and the
middiewrapper. To make the middleware compatible, Nest passes thereqandrestomiddie, but this req and res isIncomingMessageandServerResponse(the same values that an express middleware would have) whereas what the fastify plugins attachreq.cookie,res.setCookieandres.cookieto are theFastifyRequestandFastifyReplywrapper classes, which haveIncomingMessageandServerResponseavailable at the.rawproperty, but are actually more complex objects themselves.This is how middleware compatibility with fastify and middie was designed to work, as we are using express style middleware with fastify's plugin based architecture. I'd suggest if possible to move the code accessing
req.cookieto either a guard or an interceptor for better compatibility