Diagathe Josué
Diagathe Josué

Reputation: 11976

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

Upvotes: 9

Views: 21891

Answers (3)

Leonardo Lima
Leonardo Lima

Reputation: 140

ShortHand (not so short), piping the functions.

res.cookie('cookie1' : { name: 'Leo' }).cookie('cookie2' : 'Teste').send()

Upvotes: 2

m1ch4ls
m1ch4ls

Reputation: 3435

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');

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074268

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');

Upvotes: 16

Related Questions