JavaScript

Cookie Helpers (Get / Set / Delete)

by @admin
9h ago
Apr 28, 2026
Public
Minimal cookie utilities: getCookie retrieves a value by name, setCookie writes a cookie with optional expiry days and path, deleteCookie removes it by setting an expired date. No library needed for simple first-party cookie management. For complex scenarios (SameSite, Secure, partitioned) extend the options object.
JavaScript
function getCookie(name) {
  const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
  return match ? decodeURIComponent(match[1]) : null;
}

function setCookie(name, value, days = 7, path = '/') {
  const expires = new Date(Date.now() + days * 864e5).toUTCString();
  document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=${path}; SameSite=Lax`;
}

function deleteCookie(name, path = '/') {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}`;
}

// Usage
setCookie('theme', 'dark', 30);
console.log(getCookie('theme')); // 'dark'
deleteCookie('theme');
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.