2

If I create the function:

function setCookie(name, value)
    {
      // this works:
      // document.cookie=name + "=" + escape(value) + "; path=/;";
      // this does not:
      // document.cookie=name + "=" + escape(value) + "; path=/; secure; HttpOnly; SameSite=strict";
    }
setCookie('my_cookie','some_random_value');

I am not 100% on why this second option is not working. Any ideas anyone?

Barmar
  • 741,623
  • 53
  • 500
  • 612
simlpymarkb
  • 335
  • 4
  • 11
  • You can't create an HTTP-only cookie on the client. By definition it can only be created using HTTP from the server. – Barmar Mar 31 '21 at 16:50
  • Does this answer your question? [Set a cookie to HttpOnly via Javascript](https://stackoverflow.com/questions/14691654/set-a-cookie-to-httponly-via-javascript) – Heretic Monkey Mar 31 '21 at 16:53

1 Answers1

3

See MDN:

A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it is sent only to the server. For example, cookies that persist server-side sessions don't need to be available to JavaScript, and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.

You can't set it with document.cookie because the entire point of the flag is to prevent it being set (or read) with document.cookie.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • OK that makes sense now. Thanks! – simlpymarkb Mar 31 '21 at 16:57
  • what about the developer tools/application/cookies, that should show the flag? it does have a column for it and it is showing the check for some of the cookies there but not for the one I am handling – Imran Bughio May 13 '22 at 09:23