Cookie StoreLoading saved progress…

Cookie Store

document.cookie is one of the web's more awkward APIs: reading it gives you a single string of "a=1; b=2" pairs, while writing it takes one "key=value; attr=…" string at a time (assigning doesn't replace everything — it adds or updates just that cookie). And values must be URL-encoded, since a raw ; or = would corrupt the string. A tiny cookieStore wrapper hides all of that behind get/set/remove/getAll.

Implement cookieStore(). Return { get, set, remove, getAll } that encode/decode values, serialize attributes (path, max-age), and delete cookies by expiring them.

Signature

function cookieStore() {
  // returns { get(name), set(name, value, options), remove(name, options), getAll() }
}

Examples

const cookies = cookieStore();
cookies.set('theme', 'dark');
cookies.get('theme');            // 'dark'
cookies.set('token', 'a=b; c', { maxAge: 3600 }); // value is encoded
cookies.getAll();                // { theme: 'dark', token: 'a=b; c' }
cookies.remove('theme');         // gone

Notes

  • Encode / decodeencodeURIComponent the name and value on write, decodeURIComponent on read, so ;/=/spaces survive.
  • Reading is parsing — split document.cookie on '; ', then each pair on its first = (values can contain encoded =).
  • Writing is one cookiedocument.cookie = 'name=value; path=/; max-age=…' adds/updates that one; it doesn't clear others.
  • Removing = expiring — there's no delete; re-set the cookie with max-age=0 (same path) so the browser drops it.
Loading editor…