Read and write cookies
document.cookie is awkward, so wrap it. Anything sensitive belongs in an HttpOnly cookie set by the server.
JavaScript · Read and write cookiesIntermediate
function setCookie(name, value, days = 365) {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; expires=${expires}; path=/; SameSite=Lax`;
}
function getCookie(name) {
const match = document.cookie.split('; ').find((c) => c.startsWith(encodeURIComponent(name) + '='));
return match ? decodeURIComponent(match.split('=').slice(1).join('=')) : null;
}
function deleteCookie(name) { setCookie(name, '', -1); }
setCookie('theme', 'dark');cookiedocument.cookieexpires