102
votes

I have a cookie that is NOT HttpOnly Can I set this cookie to HttpOnly via JavaScript?

1
How would it be possible to set a cookie by JavaScript which JavaScript itself isn't supposed to be able to manipulate? Just set it in the server side.BalusC
The Cookie is NOT HttpOnly and i want to set it to HttpOnly via Javascript.user887983
I think you miss the point of HttpOnly.BalusC
Great question. There really isn't any downside to setting an HttpOnly cookie from the client as far as security goes. So you'd think that it would be allowed. But of course it isn't.PHP Guru

1 Answers

206
votes

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.