(JavaScript) Cookie is not being created

Viewed 422

I'm trying to use cookies for a project I have, so I looked for a method to create them using JavaScript and found, looking on some websites, a function (it looks like a function) called document.cookie. Using the following code on the console:

var value = "testCookie";
document.cookie = "testCookie=" + value + ";";
alert(document.cookie);

The alert, which should contain the cookie, appears blank, as if the cookie had not been created. What am I doing wrong? If you can tell me, I will be immensely grateful!

2 Answers

There is nothing wrong with your code. It works. You can test it right on this page by hitting F12 to open a console in Chrome, pasting your code in it, and hitting ENTER.

enter image description here

Also, after doing that, you can click on the "LOCK" symbol to the left of the "https://stackoverflow.com/questions/65348915/javascript-cookie-is-not-being-created" address in the address bar => Cookies => Stackoverflow => Cookies enter image description here

Now, in order to set cookies, you need to serve your static (HTML+JS) files from a web server, even when you want to do it locally. Just opening a file from the disk won't let you set cookies.

The easiest way to do it is to install Node JS and use one of many web servers available there, like in this example https://stackoverflow.com/a/54690795/9805867

Your code is correct (although + ";" is redundant). As mentioned by @blex, cookies set on a file:/// URL will be rejected. You will need to serve the page from a webserver. You can also use JSFiddle.

Related