Bogdan M. Bogdan M. - 23 days ago 6
HTTP Question

Chrome only sets the first cookie from the 'Set-Cookie' header

I have a dead simple http nodejs server:

require('http').createServer(function(req, res) {
res.statusCode = 200;
res.setHeader('Set-Cookie', 'age=44; name=ok; something=else; path=/');
res.end('ok ok ok', 'utf8');
}).listen(9999);


Upon visiting the page in the latest version of Chrome, these are the Response Headers sent from the server:

server response headers

So, the server sends the correct cookies. However, the browser only seems to store the first one (
age=44
). If I refresh the page again, these are the Request Headers being sent to the server:

server request headers

Only the first cookie (
age=44
) is sent. Logging
document.cookie
in the console also returns just
'age=44'
.

When inspecting the cookies from the Chrome's UI, I can also see that only the first one is saved:

What's the problem here?

chrome ui cookies

Answer

If you're just using vanilla Node then you can simply pass an array as the second parameter to res.setHeader(field, value):

res.setHeader('Set-Cookie', [
  'age=44; path=/',
  'name=ok; path=/',
  'something=else; path=/'
])

If using Express 4.11.0+ you can use res.append(field [, value]):

res.append('Set-Cookie', 'age=44; path=/');
res.append('Set-Cookie', 'name=ok; path=/');
res.append('Set-Cookie', 'something=else; path=/');