73

I have this real strange problem with client side javascript setting cookies. I'm developing a little 1 page demo at the moment to use cookies to store some 'preferences'. Please note that I can't use a server side language for this demo or any 3rd party jQuery plugins.

So I've written a javascript object to set a cookie:

var cookie = {
  set: function (name,value,exdays) {

    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var value = escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=name + "=" + value;
    console.log(document.cookie);
  }
}

cookie.set('foo','bar',2);
console.log(document.cookie);

It just returns an empty string. I've gone into Chrome console to see if I can do it via directly modifying document.cookie

> document.cookie = "foo=bar";
"foo=bar"
> document.cookie
""

How do you set a cookie via client side javascript?

Edit: I am not in incognito mode and cookies are enabled.

John
  • 258
  • 1
  • 5
  • 21
Menztrual
  • 40,867
  • 12
  • 57
  • 70
  • Also see https://developer.mozilla.org/en-US/docs/DOM/document.cookie – Aram Kocharyan Apr 10 '13 at 00:13
  • 1
    Having a similar (but not same) problem. We can read and write cookies, just not all of them. Specifically the session cookie (JSESSIONID) can not be read... It looks like this is a security feature but having a hard time finding info on it... Anyone knows about this? – Stijn de Witt Aug 15 '13 at 11:31
  • 2
    @StijndeWitt: That's a different question, please ask it on its own instead of adding a bounty to this. Btw, the answer probably are [`http-only` cookies](http://en.wikipedia.org/wiki/HTTP_cookie#HttpOnly_cookie) – Bergi Aug 15 '13 at 12:14

6 Answers6

125

HttpOnly cookies cannot be accessed from Javascript and session cookies are usually set as HttpOnly cookies. See also this StackOverflow question: How to read a secure cookie using JavaScript

So... check whether the cookie you want to read has the 'HttpOnly' flag set... If so, you know the culprit. It's not a bug, it's a feature!

Community
  • 1
  • 1
Stijn de Witt
  • 40,192
  • 13
  • 79
  • 80
  • 6
    it's puzzling to me why did "answer" got so many upvotes since it's impossible to set HttpOnly on a cookie written in javascript. – No Idea For Name Jul 05 '16 at 12:17
  • 4
    Title: `Javascript document.cookie always empty string`. Answer: Can happen when there are only cookies with the `HttpOnly` flag set. No you can't *write* these cookies from JS, but you can *attempt to* read cookies from JS and it will return... empty string... even though you see the cookie in the HTTP headers and in the browser inspector, JS won't allow you to read it. – Stijn de Witt Jul 05 '16 at 18:53
  • 7
    I think it got upvotes because: `1)` people actually often try to read e.g. the session cookie from JS. `2)` They get empty string as a result. `3)` They google and come here. `4)` They see this answer and darn it, that's exactly what's happening. `5)` Thanks man +1. :) – Stijn de Witt Jul 05 '16 at 18:55
  • 4
    well, that's too bad, because the answer doesn't answer the QUESTION which is clearly for when writing cookies in js – No Idea For Name Jul 05 '16 at 20:30
  • 1
    Yup but the title beats the question in terms of seo... It *is* the question as far as Google ranking is concerned. People find it and my answer actually answers their question (not OP's, but he has already gotten his answer anyway) so they upvote. – Stijn de Witt Jul 05 '16 at 22:53
  • 2
    What if the cookie is *not* HttpOnly. Is there any other cause for this problem? – alayor Aug 02 '17 at 17:01
  • 1
    @alayor Not that I am aware of, no. If you do find such a cause I think this would actually be a good place to add an answer, as the current answers seem to be getting upvotes regularly (so many people seem to have these issues) – Stijn de Witt Sep 21 '17 at 10:54
62

You can't set cookies by the look of things if its not running in a web server.

file:///C:/Users/me/Desktop/demo/demo.html

however:

http://localhost/demo/demo.html works.

Menztrual
  • 40,867
  • 12
  • 57
  • 70
  • 2
    This caught me out a few times before I knew about it. – Jordan Gray Aug 20 '13 at 10:38
  • 18
    actually cookies won't work properly with `localhost`, you will need a "valid" domain, even if it is the IP, like 127.0.0.1 or 0.0.0.0 for example. check http://stackoverflow.com/questions/1134290/cookies-on-localhost-with-explicit-domain/1188145#1188145 – Felipe Sabino Aug 21 '13 at 02:31
  • 1
    it got me rly confused as well and ofc in the most tutorials they think we should know it somehow – Все Едно Jun 13 '17 at 14:42
  • 2
    Actually Firefox does allow the cookies to be read from a file page. Chrome and IE don't – NicolasZ Sep 01 '18 at 19:28
  • 1
    For Python users, you can go to the working directory where the files located, then run the command: ``python3 -m http.server``. – Carson Jun 08 '20 at 05:48
1

This worked for me when ran from localhost, running chrome 28.0.1472.0 canary:

<!DOCTYPE html>
<html>
<head>
  <title>localhost cookie</title>
</head>
<body>
  <script type="text/javascript">
    console.log(document.cookie);
    var myCookie = "mycookie=hellocookie";
    document.cookie = myCookie;
  </script>
</body>
</html>

Run it in a server, visit the page and look at your cookie store, refresh the page and look at your console.

It did not set a cookie when opened as a file but worked every time when opened from the server.

poida
  • 3,403
  • 26
  • 26
0

For usage and docs, see here:

https://developer.mozilla.org/en-US/docs/DOM/document.cookie

If you are in Incognito Mode or have cookies disabled, it won't work.

Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96
0

You might have set a wrong path for the cookie.

In my case I'd set the path in the cookie to /foo because the application is normally on address http://example.org/foo. However, during tests I'd opened the application on the default address http://localhost:3000 which allowed me to create cookies with the path /foo but not read them. The solution was to test the application on address http://localhost:3000/foo.

Piotr Siupa
  • 3,929
  • 2
  • 29
  • 65
-2
  1. cookie will not work if you directly open your file, let's say index.html

    file:///C:/Users/me/Desktop/index.html

  2. however: cookie will work if page (index.html) is opened using a light weight server or local server

    http://localhost/demo/demo.html works. or http://127.0.0.1:5500/temp6.html

  3. For live sever in VS Code you can use Live Serve by Ritwick Dey enter image description here