Directly setting a Cookie with the HttpOnly flag in JavaScript is not possible because the HttpOnly flag is designed to prevent JavaScript from accessing Cookies marked with HttpOnly, thereby enhancing security and preventing Cross-Site Scripting (XSS) attacks. The HttpOnly flag must be set on the server side.
Server-Side Setup Examples
Node.js (using Express.js)
If you are using Node.js with Express.js, you can use the res.cookie() method to set a Cookie with the HttpOnly flag.
javascriptconst express = require('express'); const app = express(); app.get('/', (req, res) => { // Set HttpOnly Cookie res.cookie('id', '123456', { httpOnly: true }); res.send('HttpOnly cookie has been set!'); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
In this example, when a GET request is sent to the root directory of the server, the server sets a Cookie named id with the value 123456 and the HttpOnly flag. This means the Cookie cannot be accessed by client-side JavaScript.
PHP
In PHP, you can use the setcookie function to set a Cookie with the HttpOnly flag.
php<?php $value = '123456'; setcookie("id", $value, [ 'expires' => time() + 3600, // 1 hour 'path' => '/', 'domain' => '', 'secure' => true, 'httponly' => true, // HttpOnly set to true 'samesite' => 'Lax' // SameSite setting ]); echo 'HttpOnly cookie has been set!'; ?>
In this example, the httponly parameter is set to true, meaning the Cookie has the HttpOnly flag and cannot be accessed by JavaScript.
Summary
Although you cannot directly set a Cookie with the HttpOnly flag using pure JavaScript on the client side, you can set it using server-side scripts. This is a common practice to enhance web application security, particularly for protecting sensitive information from XSS attacks.