HttpOnly cookies are not to be read by JavaScript because they are made to be inaccessible or invisible to any script for security reasons. HttpOnly flags are an easy way of protecting the cookie content against Cross-Site Scripting (XSS) attacks. JavaScript cannot read HttpOnly cookies directly using document.cookie or any other JavaScript-based method.
Why can't I read HttpOnly cookies with JavaScript?
Security measure: HttpOnly cookies, it's designed to be accessible for the server only, that's the reason for making it impossible for the malicious javascript to access these sensitive data like session identifiers or authentication tokens, which are stored in cookies.
How Can You Access an HttpOnly Cookie?
JavaScript cannot read an HttpOnly cookie, but such cookies can still be sent with HTTP requests to the server where they can be interacted with as follows:
Server side access: An HttpOnly cookie will be sent automatically as part of the request headers while making any HTTP request (like a fetch or XMLHttpRequest). The server can analyze this and respond accordingly.
Setting HttpOnly cookies: The server may declare an HttpOnly cookie by setting the HttpOnly attribute of the cookie in the HTTP response header.
Example of setting an HttpOnly cookie by server (Node.js/Express):
// Example in Node.js (express)
app.get('/set-cookie', (req, res) => {
res.cookie('token', 'your-secret-token', { httpOnly: true });
res.send('HttpOnly cookie is set! ');
});
Sending HttpOnly Cookie Within HTTP Request-
// This is an example of fetch that sends with the HttpOnly cookie within the request.
fetch('/some-api', {
method: 'GET',
credentials: 'include' // Ensures that cookies are sent, including HttpOnly
})
.then(response => response.json())
.then(data => console.log(data));