Cookie Get/Set/Delete Utilities
Cookie Get/Set/Delete Utilities is a reusable JavaScript snippet. Simple utilities for managing browser cookies: set with expiry, get by name, and delete. The full implementation: const cookie = { set(name, value, days = 7, path = '/') { const expires = new Date(Date.now() + days * 864e5).toUTCString() document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; expires=${expires}; path=${path}; SameSite=Lax` }, get(name) { return document.cookie.split('; ') .find(row => row.startsWith(encodeURIComponent(name) + '=')) ?.split('=')[1] ?.split(';')[0] ? decodeURIComponent(_.split('=')[1]) : null }, delete(name, path = '/') { document.cookie = `${encodeURIComponent(name)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${path}` } } // Usage cookie.set('theme', 'dark', 30) cookie.get('theme') // "dark" cookie.delete('theme') This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.