Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

getAllCookies

Retrieves all cookies as a key-value object.

TypeScript
Copied!
1/**
2 * Retrieves all cookies as a key-value object.
3 *
4 * @returns An object with cookie names as keys and their corresponding values.
5 */
6export function getAllCookies(): Record<string, string> {
7  return document.cookie
8    .split('; ')
9    .filter(Boolean)
10    .reduce((acc, pair) => {
11      const [name, ...rest] = pair.split('=');
12      acc[decodeURIComponent(name)] = decodeURIComponent(rest.join('='));
13      return acc;
14    }, {} as Record<string, string>);
15}
  • Structured Output

    Transforms the flat cookie string into a key-value object, making it easier to work with cookies programmatically.

  • Handles Multi-Part Values

    Correctly joins values that contain = characters by using [...rest].join('='), avoiding truncation.

  • Safe Decoding

    Uses decodeURIComponent for both keys and values, ensuring cookies with encoded characters are accurately parsed.

  • Universal Usage

    Can be used in debugging, logging, or for building UI based on cookie state without needing to know specific keys in advance.

Tests | Examples

TypeScript
Copied!
1beforeEach(() => {
2  Object.defineProperty(document, 'cookie', {
3    writable: true,
4    configurable: true,
5    value: '',
6  });
7});
8
9test('returns all cookies as an object', () => {
10  document.cookie = 'theme=dark; token=abc123';
11  expect(getAllCookies()).toEqual({
12    theme: 'dark',
13    token: 'abc123',
14  });
15});
16
17test('handles encoded characters', () => {
18  document.cookie = 'user%20id=123%20456';
19  expect(getAllCookies()).toEqual({
20    'user id': '123 456',
21  });
22});
23
24test('returns an empty object if no cookies exist', () => {
25  document.cookie = '';
26  expect(getAllCookies()).toEqual({});
27});

Common Use Cases

  • Debugging & Developer Tools

    Display all browser cookies in dev tools or logs for inspection.

  • Settings or Preferences Loader

    Automatically populate user settings from cookies into application state.

  • Cookie Synchronization

    Compare or sync cookies across tabs, if combined with localStorage or BroadcastChannel.

  • Form Auto-Fill

    Prefill forms with saved values stored as cookies, especially for simple apps without localStorage.

Codebase: Utilities -> Storage -> getAllCookies | Yevhen Klymentiev