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

buildCookieHeader

Builds a cookie header string from an object of key-value pairs.

TypeScript
Copied!
1/**
2 * Builds a cookie header string from an object of key-value pairs.
3 *
4 * @param cookies - An object with keys and values to be serialized into a cookie header.
5 * @returns A cookie header string (e.g. "key1=value1; key2=value2").
6 *
7 * @example
8 * buildCookieHeader({ token: "abc123", theme: "dark" })
9 * // => "token=abc123; theme=dark"
10 */
11export function buildCookieHeader(cookies: Record<string, string>): string {
12  return Object.entries(cookies)
13    .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
14    .join('; ');
15}
  • Standards-Compliant Serialization

    Produces output compatible with HTTP Cookie headers by using proper formatting and delimiters.

  • Automatic URI Encoding

    Encodes cookie values using encodeURIComponent, ensuring safe transmission of special characters.

  • Simple and Readable Logic

    Uses modern JavaScript (Object.entries, .map, .join) for concise and readable implementation.

  • Deterministic Output Order

    Cookies are serialized in the same order as object entries, making output predictable for debugging or caching.

Tests | Examples

TypeScript
Copied!
1test('builds cookie header from simple object', () => {
2  const result = buildCookieHeader({ token: 'abc123', theme: 'dark' });
3  expect(result).toBe('token=abc123; theme=dark');
4});
5
6test('encodes URI-unsafe characters', () => {
7  const result = buildCookieHeader({ name: 'John Doe', city: 'New York' });
8  expect(result).toBe('name=John%20Doe; city=New%20York');
9});
10
11test('handles empty values', () => {
12  const result = buildCookieHeader({ flag: '', token: 'abc' });
13  expect(result).toBe('flag=; token=abc');
14});
15
16test('returns empty string for empty input', () => {
17  const result = buildCookieHeader({});
18  expect(result).toBe('');
19});

Common Use Cases

  • Setting Cookies in Server-Side Responses

    Convert a cookie object into a header string for use in Set-Cookie or custom header handling.

  • Custom Fetch or Axios Wrappers

    Append serialized cookies to request headers when manually managing authentication.

  • Testing Cookie Headers

    Generate mock cookie headers for unit or integration testing of server behavior.

  • Manual HTTP Requests

    Build cookie headers when interacting with low-level APIs like http.request in Node.js.

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