0
votes

I'm creating a simple cookie and want to set sameSite to "Lax.. However, whenever I set this in my funciton, sameSite isn't actually being set.

I understand this needs to be set, alongside secure...? Where am I going wrong?

function setCookie(name, value, expirydays) {
 var d = new Date();
 d.setTime(d.getTime() + (expirydays*24*60*60*1000));
 var expires = "expires="+ d.toUTCString();
 document.cookie = name + "=" + value + "" + expires + "sameSite=Lax; Secure";
}

seCookie("ejOptExp", "Fkh3wu6USS-7HjQMGoRnDw.2", 7);

I'm using EditThisCookie chrome extension, to view my cookie data. And it looks like samesite is always set to none?

enter image description here

Thank you.

1
From what i read, "Lax" is the new default? Not sure, if it not setting it explicitly is a bug, or the intended behavior though. - ASDFGerte
@ASDFGerte Thank you very much! I did read this too, but also read so many other answers/solutions, got highly confused - Reena Verma

1 Answers

1
votes

Where am I going wrong?

This issue here is that your cookie's attributes don't have semicolons between them.

If I add console.log(name + "=" + value + "" + expires + "sameSite=Lax; Secure"); to your function and run it I see

ejOptExp=Fkh3wu6USS-7HjQMGoRnDw.2expires=Mon, 05 Apr 2021 17:20:08 GMTsameSite=Lax; Secure

which isn't what you want.

Add some semicolons and that'll solve your issue. document.cookie = name + "=" + value + "; " + expires + "; " + "sameSite=Lax; Secure";

I understand this needs to be set, alongside secure...?

SameSite=Lax does not require Secure, only SameSite=None does. But it's still good practice to mark your cookies as Secure when possible anyway!

And it looks like samesite is always set to none?

The empty field there means that the browser didn't recognize any SameSite attribute for your cookies (because of the lack of semicolons) and so the attribute is unspecified. As mentioned by ASDFGerte, when SameSite is unspecified the cookie will be treated as "Lax" in most browsers.