The Question

Can I set cookie to HttpOnly using JavaScript.

Answer

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

The HttpOnly is set in a HTTP Response, you have to set it in the server side using whatever server side language is using. If JavaScript is absolutely necessary in 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 a 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 JavaScript and thus make the HttpOnly on your cookie completely useless.

References & Resources

  • N/A