How to handle cookies in middleware


#1

Hi!

I’m trying to setup a cookies through a middleware but I’m encountering behavior I’m not sure how to control.

So basically what i want to do is:

  • Set expire-time on the cookie itself

  • Set path to /

So the way I’m trying to do this is in the downstream:

'use strict'

class CookieMonsterMiddleware {
  async handle ({ response }, next) {
    await next()

    if(request.request.headers.host === 'knownUrl.com') {
       response.plainCookie('my_cookie','randomValue');
    }

  }
}

module.exports = CookieMonsterMiddleware

First of, when doing this I get in result when routing to the host url everything is fine but the expire time on the cookie is ‘1969-12-31T23:59:59.000Z’ which i want to change.

Secondly if I set directly in the url let’s say ‘knownUrl.com/main/cars’ I get two cookies(want one) of the same name, basically ‘my_cookie’,‘randomValue’ where the first one has path ‘/’ and the second one has ‘/main’.

Any hints on how to approach this :)?


#2

So digging deeper you can set this by the third param options :slight_smile: and i Assume now in retrospective that the double cookies was most likely due expire time issues