I'm trying to set cookie using res.cookie like below:
res.cookie('userId',req.user._id); //set cookie here
console.log(req.user._id); //returned correct value, eg abc
then I'm seeing j:"abc" in my cookie, why does this happens?
I'm trying to set cookie using res.cookie like below:
res.cookie('userId',req.user._id); //set cookie here
console.log(req.user._id); //returned correct value, eg abc
then I'm seeing j:"abc" in my cookie, why does this happens?
Share Improve this question asked Jul 3, 2016 at 7:17 Alicia BrandonAlicia Brandon 5752 gold badges6 silver badges13 bronze badges 2- How are you checking the cookie value? – robertklep Commented Jul 3, 2016 at 8:37
- @robertklep not sure why it's not working properly, I manage to solve it using a cookie npm package to parse it. – Alicia Brandon Commented Jul 3, 2016 at 8:49
4 Answers
Reset to default 16I know this is a bit late, but I came across this issue myself and have been digging around a bit. It seems they're prefixing any JSON strings with "j:" so they know it's a JSON string when parsing it back. What this basically means is that you have to manually remove the "j:" if you're using some other way of parsing it.
According the the Express 4 docs, res.cookie(name, value [, options])
sets a cookie name to a value. The value parameter may be a string or object converted to JSON.
In this instance, req.user._id
is an object so you would set the cookie as res.cookie('userId', JSON.stringify(req.user._id))
Cookies are encrypted to the client side. You need a cookie-parser to correctly get the user.id from your cookie. See its documentation for use.
So I'm using cookie-parser & express-session on the NodeJS side, ng2-cookies on the client side. I was also expecting to read userId as i.e. 59bca61b74d1cac10ce50d0c
rather than j:59bca61b74d1cac10ce50d0c
:(
So, rather than have to do some magic on the client side I just did res.cookie('cookieName', cookieValue.toString(), cookieOptions)
and this gave me what I was looking for.
Doing a console.log('cookies', req.cookies)
shows things are fine, although req.headers.cookie shows 2 userId cookies (still testing)