Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite / update browser cookie

I have an Express 4.x app, and I pass a cookie to the browser with

res.cookie('foo','bar1', {maxAge:99999999999});

it expires in the distant future. However, 5 minutes later, I get another request from the same user, and I want to give them a new cookie.

 res.cookie('foo','bar2', {maxAge:99999999999});

From my debugging, it looks like the new cookie doesn't overwrite the old cookie? Is that the case? How can I update/overwrite the old cookie with the new one?

like image 677
Alexander Mills Avatar asked Jun 07 '17 00:06

Alexander Mills


1 Answers

I am about 99% certain that using the {overwrite: true} property will do the trick - from here:

https://www.npmjs.com/package/cookies

it says:

cookies.set( name, [ value ], [ options ] ) This sets the given cookie in the response and returns the current context to allow chaining.

If the value is omitted, an outbound header with an expired date is used to delete the cookie.

If the options object is provided, it will be used to generate the outbound cookie header as follows:

maxAge: a number representing the milliseconds from Date.now() for expiry expires: a Date object indicating the cookie's expiration date (expires at the end of session by default). ... overwrite: a boolean indicating whether to overwrite previously set cookies of the same name (false by default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie.

So that would be, in Node.js Express parlance:

res.cookie('cdt_app_token', encoded, {maxAge: 90000000, httpOnly: true, secure: false, overwrite: true});

Note that if you are using a non SSL or non TLS connection, cookies may not work if secure is true.

like image 82
Alexander Mills Avatar answered Oct 08 '22 10:10

Alexander Mills