3

When setting a cookie with client-side javascript document.cookie=..., the secure attribute forces the cookie "to only be transmitted over secure protocol as https" see MDN spec.

I set a cookie in my SPA, client-side (ie in code run by the browser) as follows:

document.cookie = 'myCookie=myValue;expires=Sun, 31 Dec 2017 23:00:00 GMT;path=/;secure;';

where Sun, 31 Dec 2017 23:00:00 GMT is obtained with the javascript Date method toUTCString(), and could be any date in the distant future (there have been report with expires issues when the date is less than 2 hours in the future, but this is not at stake here).

This works for Chrome on macOS and on android, but the cookie is not set on neither for Chrome nor Safari on iOS. After poking around, I figured that removing the secure attribute allows the cookie to be set:

document.cookie = 'myCookie=myValue;expires=Sun, 31 Dec 2017 23:00:00 GMT;path=/;';

Does anyone know how I can set my cookie for Chrome and Safari on iOS for it to be transmitted only over https?

There surely must be a way, and I researched many SO questions to no avail. Thx

MDH
  • 125
  • 3
  • 11

1 Answers1

2

I was having the same issue and it started working when I added the domain parameter.

document.cookie = 'myCookie=myValue;expires=Sun, 31 Dec 2017 23:00:00 GMT;domain=www.mydomain.com;path=/;secure;';

More can be found here: How to set cookie secure flag using javascript

Dr. Aaron Dishno
  • 1,859
  • 1
  • 29
  • 24
  • Thanks for the answer, it does not seem to work, I added my domain as `domain=my-domain-name.herokuapp.com;` and cookie is still not set. Am getting something wrong? – MDH Jul 18 '17 at 02:04
  • Pls how did you solve this problem? – Paulliano Jul 19 '22 at 11:03
  • Not sure, it may be browser specific. I use it on Google Chrome. Seems to still work for me. But there is more information on the referred link above. Hope that helps. – Dr. Aaron Dishno Jul 26 '22 at 20:42