21

I am trying to set SameSite attribute using javascript on my site . The code is

<script type="text/javascript">

    document.cookie = "AC-C=ac-c;expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;HttpOnly;SameSite=Lax";
  </script>

The cookie is being set but the SameSite attribute is not being set. Any idea where am I missing?

Thanks

Satya
  • 8,693
  • 5
  • 34
  • 55

2 Answers2

21

Your problem is not with SameSite, but with HttpOnly. HttpOnly and SameSite are 2 independent things, if you remove HttpOnly it will be working… and cookie will be set with SameSite.

<script>
    document.cookie = "AC-C=ac-c;expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;SameSite=Lax";
    alert( document.cookie );
</script>
iiic
  • 1,366
  • 2
  • 15
  • 23
10

You can not set HttpOnly flag via JavaScript API document.cookie. Flag HttpOnly can be set only via cookie header in server response. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies Cookies created via JavaScript cannot include the HttpOnly flag.

You wrote The cookie is being set but the SameSite attribute is not being set but I think it is not truth. Cookie set via JS with attribute HttpOnly is rejected at all or maybe some browser set it but ignore HttpOnly flag - so finally your cookie is not HTTP only.

mikep
  • 5,880
  • 2
  • 30
  • 37
  • You're right, my apologies. While I'd still argue that setting samesite on client-side is not very useful considering its purpose, my answer to OP's actual question is wrong and I'm withdrawing it. As you say, it *is* possible to set it from client-side. – Vasan Nov 14 '19 at 03:05
  • @Vasan You are right that setting SameSite=Strict/Lax is not very useful considering its purpose but consider SameSite=None... it is useful. Since Chrome v80 3rd parties (e.g. iframes) must set SameSite=None for cookie that is not Strict/Lax because chrome will not send it with CORS requests. Btw. in 3rd party iframe it is not possible to set SameSite=Strict/Lax, but only SameSite=None so in this use case enabling SameSite flag for JS API is not in conflict with SameSite purpose. – mikep Nov 15 '19 at 14:37
  • Yes, setting SameSite=None is not just useful but required when loaded as a third party iframe, and unfortunately it is not possible to set it from javascript. – Matt Cosentino Mar 31 '20 at 17:06