I have been working on a node js project, and I need to set two different cookies. But when I set them, the second one always overwrites the first one. here is the code I am using below
res.setHeader('set-cookie', [
'x-authsession=' + cookieParsed['x-authsession']
+ '; Path=' + cookieParsed['Path'] + '; Expires='
+ cookieParsed['Expires']
+ `; `, ]
);
res.setHeader('set-cookie', [
'x-device=' + cookieParsed['x-device']
+ '; Path=' + cookieParsed['Path'] + '; Expires='
+ cookieParsed['Expires']
+ `; `,
]);
but only x-device gets stored on the browser. Anyone knows how to fix this please?
Instead of explicitly modifying the set-cookie header you can use res.cookie.
res.cookie(
'x-authsession',
cookieParsed['x-authsession'],
{
path: cookieParsed['Path'],
expires: cookieParsed['Expires']
}
);
res.cookie(
'x-device',
cookieParsed['x-device'],
{
path: cookieParsed['Path'],
expires: cookieParsed['Expires']
}
);
Also, as said here,
To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.
Side thoughts, looks like you are trying to use session cookies manually. That isn't a good idea to do. Instead checkout the express-session package on npm.
this works fine for me:
res.setHeader("Set-Cookie",
[
cookie.serialize("cookie1", "data1"),
cookie.serialize("refreshToken", refreshToken)
]
)
res.end()