JavaScript - add, remove, get, set and list cookies (using document.cookie property)
In this article, we want to show a simple way how to manage cookies using document.cookie
property avaialble under JavaScript web borowser API.
Overview
The cookies are placed in the document.cookie
property as string, that lets us read and write cookies associated with the document.
1. Add / set / update cookie
In this section, we present how to add or set cookie.
document.cookie = 'cookie_name=cookie_value'; // cookie lives in sessions time scope
document.cookie = 'cookie_name=cookie_value;domain=pl.dirask.com'; // cookie available only under pl.dirask.com
document.cookie = 'cookie_name=cookie_value;path=/posts'; // cookie available only under /posts
document.cookie = 'cookie_name=cookie_value;secure'; // cookie available only under https connection
document.cookie = 'cookie_name=cookie_value;HttpOnly'; // cookie available only on server (in web browser not available)
// e.g. used to protect sessions ids that may be stolen from injected JavasSript source code
document.cookie = 'cookie_name=cookie_value;max-age=31536000'; // cookie that expires after 1 year (31536000s = 60*60*24*365)
// Complex examples:
document.cookie = 'cookie_name=cookie_value;expires=Wed, 31 Dec 2025 22:59:59 GMT';
// or:
const date = new Date(2025, 11, 31, 23, 59, 59);
document.cookie = 'cookie_name=cookie_value;expires=' + date.toGMTString();
// Full example:
document.cookie = 'cookie_name=cookie_value;domain=pl.dirask.com;path=/posts;secure;max-age=31536000';
Note: adding a cookie with an existing name updates the cookie.
2. Remove cookie
To remove the cookie, we need assign string with cookie name and max-age
attribute set to 0
to document.cookie
property so it will expire immediately.
document.cookie='cookie_name=;max-age=0';
3. Get cookie
document.cookie
property returns a string containg all cookies in format cookie_name=cookie_value
separated by ;
. To get specific cookie value it is necessary to extract it from the string.
const name = 'cookie_name';
const cookies = document.cookie.split(/;\s*/g);
for (const cookie of cookies) {
const parts = cookie.split('=', 2);
if (name === parts[0]) {
const value = parts[1];
console.log(`${name}=${value}`);
break;
}
}
4. List cookies
document.cookie
property returns a string containg all cookies in format cookie_name=cookie_value
separated by ;
. To iterate trhough cookies it is necessary to split the string by ;
and then each one part by =
getting name and value.
const cookies = document.cookie.split(/;\s*/g);
for (const cookie of cookies) {
const parts = cookie.split('=', 2);
const name = parts[0];
const value = parts[1];
console.log(`${name}=${value}`);
}