0

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)
}
armada45
  • 103
  • 9
  • Are you sending in any cookies? – Jay McDoniel Aug 15 '22 at 15:43
  • I tried it all, with cookie, without cookie, with postman, with Thunder Client – armada45 Aug 15 '22 at 15:47
  • Okay, then it seems like this is an issue with code order execution. Seems like the middleware is being ran before the cookie parser can. Any reason to stick with a middleware rather than using something like a guard or an interceptor? – Jay McDoniel Aug 15 '22 at 16:05
  • I report this in bug type to nestjs github. [Cookie in middleware not working only using fastify. · Issue #10121 · nestjs/nest](https://github.com/nestjs/nest/issues/10121) – armada45 Aug 16 '22 at 06:49

1 Answers1

1

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 middie wrapper. To make the middleware compatible, Nest passes the req and res to middie, but this req and res is IncomingMessage and ServerResponse (the same values that an express middleware would have) whereas what the fastify plugins attach req.cookie, res.setCookie and res.cookie to are the FastifyRequest and FastifyReply wrapper classes, which have IncomingMessage and ServerResponse available at the .raw property, 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.cookie to either a guard or an interceptor for better compatibility

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147