25

I'm trying to create a cookie, with the HttpOnly flag enabled.

While there seems to be a plethora of resources about how to do it in Java and .Net, I need to do it in javascript.

Here is my (currently failing) function

createCookie = function(name,value,days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; domain=my.domain.com; path=/; HttpOnly;";

Thanks -

user617136
  • 293
  • 1
  • 3
  • 7
  • 4
    Isn't the whole point of HttpOnly to prevent Javascript from accessing it? I would question the use case. – Steven Feb 15 '11 at 02:25
  • 4
    As far as I know, HTTP-only cookies cannot be accessed/created by JavaScript. That is the point, right? – JCOC611 Feb 15 '11 at 02:25
  • 3
    Wouldn't setting a `httponly` flag by JavaScript defeat the purpose? – alex Feb 15 '11 at 02:26
  • 3 comments saying the same thing :) cool we all think the same way! – JCOC611 Feb 15 '11 at 02:26
  • 9
    I would have thought you could have created one, just not read it? – user617136 Feb 15 '11 at 02:28
  • Just a small nuance: `HttpOnly` cookies can not be set *from the browser*, but it's perfectly possible from JS running *on the server*... in a Node JS based Express app for example. – Stijn de Witt Jan 20 '17 at 21:03

1 Answers1

24

You cannot access an HttpOnly cookie in JavaScript.

The following quotation is borrowed from the Wikipedia material:

The HttpOnly cookie is supported by most modern browsers. On a supported browser, an HttpOnly session cookie will be used only when transmitting HTTP (or HTTPS) requests, thus restricting access from other, non-HTTP APIs (such as JavaScript).

In other words, HttpOnly cookies are made to be used only on the server side.

I wrote an example in PHP:

<?php
$name = 'foo';
$value = 'bar';
$expirationTime = 0;    // Session cookie.
$path = '/';
$domain = 'localhost';
$isSecure = false;
$isHttpOnly = false;
setcookie($name, $value, $expirationTime, $path, $domain, $isSecure, $isHttpOnly);
?>
<script>
alert(document.cookie);
</script>

It alerts foo=bar.

Remove the cookie, change $isHttpOnly to true, reload the page, and you'll see an empty alert. But at the same time the browser stores the cookie to send it during a request to the server.

Yevhen Pavliuk
  • 555
  • 4
  • 13