Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set multiple cookies with res.cookie(key , value) on NodeJS?

I'm working with cookies on NodeJS and I wonder how set multiple cookies to send on client.

I have tried :

1-

     var headers = {
      Cookie: 'key1=value1; key2=value2'
  }
  res.cookie(headers)

2-

res.cookie("isStillHere" , 'yes it is !').send('Cookie is set');
res.cookie("IP" , ip).send('Cookie is set');

3-

  var setMultipleCookies =  []
 setMultipleCookies.push('key1=value1','key2=value2')
  res.cookie(setMultipleCookies)

Seems nothing works. What is going wrong ? Any hint would be great,

thanks

like image 258
Webwoman Avatar asked Aug 25 '18 16:08

Webwoman


People also ask

Can you have multiple set cookie headers?

The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.

How do you add multiple cookies?

To set more than one, you just set document. cookie more than once. The ; separator is used to specify the additional info, not to add more different cookies.

Can a request have multiple cookies?

When the user agent generates an HTTP request, the user agent MUST NOT attach more than one Cookie header field. It looks like the use of multiple Cookie headers is, in fact, prohibited!


2 Answers

You simply call cookie more than once without calling send in between them. Call send only after you've done all the cookies, since send sends the response body, and cookie headers are...well...in the header. :-)

res.cookie("isStillHere" , 'yes it is !');
res.cookie("IP" , ip);
res.send('Cookie is set');
like image 75
T.J. Crowder Avatar answered Sep 22 '22 13:09

T.J. Crowder


You have to set all cookies before you call res.send()

res.cookie("isStillHere" , 'yes it is !');
res.cookie("IP" , ip);
res.send('Cookie is set');
like image 32
m1ch4ls Avatar answered Sep 19 '22 13:09

m1ch4ls