How do I set the HttpOnly flag of a cookie with javascript?
Asked Answered
E

1

27

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 -

Eward answered 15/2, 2011 at 2:23 Comment(7)
Isn't the whole point of HttpOnly to prevent Javascript from accessing it? I would question the use case.Nun
As far as I know, HTTP-only cookies cannot be accessed/created by JavaScript. That is the point, right?Negress
Wouldn't setting a httponly flag by JavaScript defeat the purpose?Doorstep
3 comments saying the same thing :) cool we all think the same way!Negress
I would have thought you could have created one, just not read it?Eward
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.Tutorial
@Nun Set =\= Access. In any case, the question is answered here #14692154Lorusso
L
26

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.

Lira answered 19/6, 2012 at 9:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.