Cookies

suggest change

Setting a cookie

document.cookie uses a serialized string. Encode names and values, and set an explicit path and SameSite policy:

function setCookie(name, value, {
  maxAge,
  path = '/',
  sameSite = 'Lax',
  secure = location.protocol === 'https:',
} = {}) {
  const parts = [
    `${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
    `Path=${path}`,
    `SameSite=${sameSite}`,
  ];

  if (maxAge !== undefined) parts.push(`Max-Age=${maxAge}`);
  if (secure) parts.push('Secure');

  document.cookie = parts.join('; ');
}

setCookie('theme', 'dark', { maxAge: 60 * 60 * 24 * 30 });

Client-side JavaScript cannot create an HttpOnly cookie. Authentication cookies should normally be set by the server with HttpOnly, Secure, and an appropriate SameSite policy.

Reading cookies

function getCookie(name) {
  const encodedName = encodeURIComponent(name);

  for (const item of document.cookie.split(';')) {
    const [key, ...valueParts] = item.trim().split('=');
    if (key === encodedName) {
      return decodeURIComponent(valueParts.join('='));
    }
  }

  return undefined;
}

Removing cookies

Expire the cookie using the same path and domain attributes with which it was created:

setCookie('theme', '', { maxAge: 0, path: '/' });

Cookie availability

navigator.cookieEnabled is only a general capability hint. Browser privacy policies may still block particular cookies, especially in third-party contexts. When availability matters, write a short-lived test cookie and verify that it can be read.

The asynchronous Cookie Store API can be preferable in supporting environments, especially in service workers, but document.cookie remains necessary when that API is unavailable.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents