How to set and read a cookie
Short answer
Assigning to document.cookie adds or updates one cookie. max-age sets its lifetime in seconds:
document.cookie = `theme=${encodeURIComponent('dark')}; max-age=${60 * 60 * 24 * 30}; path=/`;Reading by name
document.cookie returns all cookies as one string like a=1; b=2. Split it and find the needed one:
function getCookie(name) {
const pair = document.cookie.split('; ').find((item) => item.startsWith(name + '='));
return pair ? decodeURIComponent(pair.slice(name.length + 1)) : null;
}
const theme = getCookie('theme');How the parsing works
The same code on an ordinary string:
const cookies = 'theme=dark; lang=en; cart=%5B1%2C2%5D';
const getCookie = (name) => {
const pair = cookies.split('; ').find((item) => item.startsWith(name + '='));
return pair ? decodeURIComponent(pair.slice(name.length + 1)) : null;
};
console.log(getCookie('lang'));
console.log(getCookie('cart'));
console.log(getCookie('token'));Output:
en
[1,2]
nullDeleting
To delete a cookie, set it again with max-age=0 and the same path:
document.cookie = 'theme=; max-age=0; path=/';Common mistake
document.cookie = ... does not overwrite all cookies, it changes only one. And cookies with the HttpOnly flag, usually the login session, are not visible to JavaScript at all.
document.cookie = 'a=1';
document.cookie = 'b=2';
// document.cookie is now 'a=1; b=2'Functions used in this recipe
- encodeURIComponent — Encodes text for safely putting it into part of a URL.