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

getCookieHeader

Parses a cookie string (typically from a request header) into an object.

TypeScript
Copied!
1/**
2 * Parses a cookie string (typically from a request header) into an object.
3 *
4 * @param cookieHeader - The raw cookie header string.
5 * @returns An object with key-value pairs of cookies.
6 *
7 * @example
8 * getCookieHeader("token=abc123; theme=dark")
9 * // => { token: "abc123", theme: "dark" }
10 */
11export function getCookieHeader(cookieHeader: string): Record<string, string> {
12  return cookieHeader
13    .split(';')
14    .map(part => part.trim().split('='))
15    .filter(([key]) => key)
16    .reduce<Record<string, string>>((acc, [key, value]) => {
17      acc[key] = decodeURIComponent(value ?? '');
18      return acc;
19    }, {});
20}
  • Header-Friendly Parsing

    Specifically designed for parsing raw Cookie headers from HTTP requests, aligning with server-side use cases.

  • Whitespace and Format Tolerant

    Trims segments to handle inconsistent spacing and malformed cookie strings gracefully.

  • Decodes Encoded Values

    Applies decodeURIComponent to ensure accurate decoding of URL-encoded values in cookies.

  • Minimal Footprint

    Achieves its goal with a compact and efficient implementation, using native JavaScript methods.

Tests | Examples

TypeScript
Copied!
1test('parses simple cookie string', () => {
2  const result = getCookieHeader('token=abc123; theme=dark');
3  expect(result).toEqual({ token: 'abc123', theme: 'dark' });
4});
5
6test('handles extra spaces and empty segments', () => {
7  const result = getCookieHeader('  token=abc123 ; theme=dark ;  ');
8  expect(result).toEqual({ token: 'abc123', theme: 'dark' });
9});
10
11test('decodes URI-encoded values', () => {
12  const result = getCookieHeader('name=John%20Doe');
13  expect(result).toEqual({ name: 'John Doe' });
14});
15
16test('handles missing value gracefully', () => {
17  const result = getCookieHeader('flag=; token=abc');
18  expect(result).toEqual({ flag: '', token: 'abc' });
19});
20
21test('returns empty object for empty string', () => {
22  const result = getCookieHeader('');
23  expect(result).toEqual({});
24});

Common Use Cases

  • Server-Side Cookie Extraction

    Parse req.headers.cookie in frameworks like Express or Next.js middleware.

  • API Gateway or Edge Functions

    Read authentication tokens or preferences from cookie headers in edge environments (e.g., Cloudflare Workers, Vercel Edge).

  • Manual HTTP Request Handling

    Useful when building custom HTTP clients or middleware that don't rely on cookie libraries.

  • Testing or Mocking Headers

    Parse cookie headers in unit or integration tests to simulate real-world scenarios.

Codebase: Utilities -> Network -> getCookieHeader | Yevhen Klymentiev