How to use cookie in middleware of Nest JS ( Fastify )

2k views Asked by At

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)
}
1

There are 1 answers

0
Jay McDoniel On

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