Multiple Set-Cookie Headers in Node.js

Saturday, 31 July 2010

Sometimes you want to send the same header twice in the same response, such as setting two cookies at once. But how can this be achieved when HTTP headers are passed to writeHead as an object and it's not possible to have the same key twice? The answer seems to be an undocumented feature of writeHead, that allows you to pass an array of headers instead.

'Use an array' is a little ambiguous, so let me provide an example:

res.writeHead(200, [
    ['Set-Cookie', 'mycookie1=value1'],
    ['Set-Cookie', 'mycookie2=value2']

Simple enough. Another option is to attempt to combine multiple cookie key-value pairs in one Set-Cookie header, but in practice you'll be running into more browser incompatibilities this way.

There is, however, one important issue with this feature. If you author any middleware for Connect or any other frameworks, and you proxy calls to writeHead or modify headers in any other way, you need to support headers as an array! This change seemed to have passed me by, so I thought I'd spread the word a little.