yaxx
yaxx

Reputation: 655

How to set and retrieved signed cookies in express

I am working with Express and setting signed cookies works by appearing in the browser, but when I try retrieving it back in Express, I get 'undefined' or empty object {} when viewing the signed cookie:

app.use(require('cookie-parser')('something secret')// header
res.cookie('e', 'mycookie', {signed:true})
req.signedCookies['e'] //returns undefined
req.signedCookies //returns {}

Any idea what's happening?

Upvotes: 3

Views: 824

Answers (1)

danday74
danday74

Reputation: 57006

Where's your middleware?

app.use(require('cookie-parser')('something secret') // header

app.use(function (req, res, next) {
  res.cookie('e', 'mycookie', {signed:true})
  req.signedCookies['e'] // returns undefined
  req.signedCookies // returns {}
  next()
})

Also, on res.cookie you are setting a cookie on the HTTP response from the Express server. Check your HTTP response to see if the cookie is there.

On req.signedCookies you are getting cookies from the incoming HTTP request. Is your cookie set on the incoming request? Does it have a valid signature?

Setting a cookie on the response will not suddenly make that cookie accessible on the request right? So setting 'e' on the response and then trying to get 'e' on the request would not work to my mind.

Upvotes: 1

Related Questions