How do you read and write cookies from JavaScript?
Cookies are read and written through the document.cookie property. Writing is a string assignment, and reading gives you back a single string containing every cookie for the current page, formatted as name and value pairs separated by semicolons.
// document.cookie only exists in a browser.
if (typeof document !== "undefined") {
document.cookie = "theme=dark; path=/; max-age=3600; SameSite=Lax";
console.log(document.cookie); // "theme=dark"
// Cookies come back as one string, so you parse them.
const readCookie = (name) => {
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : null;
};
console.log(readCookie("theme")); // "dark"
} else {
console.log("No document in this runtime - open a browser console to try it.");
}Because the whole thing is one string, you need a helper to read a single cookie by name, and the regular expression in the example is the standard way to do it. The decodeURIComponent call matters because the cookie API encodes special characters automatically when you write them, so the value you read back is still percent encoded.
When you write a cookie, the attributes come after the value, separated by semicolons. The path attribute decides which paths on the site can see the cookie, and it defaults to the directory of the current page, which surprises people who then cannot find their cookie elsewhere. The max-age attribute gives it a lifetime in seconds, and the expires attribute does the same with a date. The SameSite attribute controls whether the cookie is sent on cross-site requests, and the Secure attribute restricts it to secure connections.
Two limitations to remember. A cookie set with the HttpOnly attribute is invisible to JavaScript, which is the correct choice for session tokens. And document.cookie cannot see those cookies at all, so they are simply not listed.