Skip to main content

Overview

The request utilities module provides comprehensive functions for working with HTTP cookies, including parsing, serialization, encryption, and header manipulation. Represents an HTTP cookie with all standard attributes.
interface Cookie {
  name: string;
  value: string;
  domain?: string;
  expires?: Date;
  httpOnly?: boolean;
  maxAge?: number;
  path?: string;
  priority?: "low" | "medium" | "high";
  sameSite?: "strict" | "lax" | "none";
  secure?: boolean;
  partitioned?: boolean;
  extra?: Record<string, string>;
}
name
string
required
The cookie name
value
string
required
The cookie value
domain
string
The domain the cookie applies to
expires
Date
When the cookie expires
httpOnly
boolean
Whether the cookie is HTTP-only (not accessible via JavaScript)
maxAge
number
Maximum age in seconds
path
string
The path the cookie applies to
priority
'low' | 'medium' | 'high'
Cookie priority for resource budgeting
sameSite
'strict' | 'lax' | 'none'
SameSite attribute for CSRF protection
secure
boolean
Whether the cookie requires HTTPS
partitioned
boolean
Whether the cookie is partitioned (CHIPS)
extra
Record<string, string>
Additional custom cookie attributes

Basic operations

parseCookie

Parses a Set-Cookie header value into a Cookie object.
function parseCookie(source: string): Cookie | undefined
source
string
required
The Set-Cookie header value
result
Cookie | undefined
The parsed cookie, or undefined if invalid
Example:
import { parseCookie } from "@temelj/request";

const cookie = parseCookie("session=abc123; Path=/; HttpOnly; Secure");
console.log(cookie);
// {
//   name: "session",
//   value: "abc123",
//   path: "/",
//   httpOnly: true,
//   secure: true
// }

serializeCookie

Serializes a Cookie object into a Set-Cookie header value.
function serializeCookie(cookie: Cookie): string
The cookie to serialize
result
string
The Set-Cookie header value
Example:
import { serializeCookie } from "@temelj/request";

const cookie: Cookie = {
  name: "session",
  value: "abc123",
  path: "/",
  httpOnly: true,
  secure: true,
  sameSite: "strict",
  maxAge: 3600
};

const headerValue = serializeCookie(cookie);
console.log(headerValue);
// "session=abc123; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Strict"

Header operations

parseCookieHeader

Parses a Cookie header value into an array of cookies.
function parseCookieHeader(header: string): Cookie[]
header
string
required
The Cookie header value (semicolon-separated)
result
Cookie[]
Array of parsed cookies
Example:
import { parseCookieHeader } from "@temelj/request";

const header = "session=abc123; user_id=42; theme=dark";
const cookies = parseCookieHeader(header);
console.log(cookies);
// [
//   { name: "session", value: "abc123" },
//   { name: "user_id", value: "42" },
//   { name: "theme", value: "dark" }
// ]

serializeCookieHeader

Serializes an array of cookies into a Cookie header value.
function serializeCookieHeader(cookies: Cookie[]): string
cookies
Cookie[]
required
Array of cookies to serialize
result
string
The Cookie header value
Example:
import { serializeCookieHeader } from "@temelj/request";

const cookies: Cookie[] = [
  { name: "session", value: "abc123" },
  { name: "user_id", value: "42" }
];

const header = serializeCookieHeader(cookies);
console.log(header); // "session=abc123; user_id=42"

Encryption

encryptCookieValue

Encrypts a cookie value using AES-CBC encryption.
function encryptCookieValue(
  value: string,
  options: CookieEncryptionOptions
): Promise<string>
value
string
required
The value to encrypt
options
CookieEncryptionOptions
required
Encryption configuration including password
result
Promise<string>
The encrypted value as a base64-encoded string with signature
Example:
import { encryptCookieValue } from "@temelj/request";

const encrypted = await encryptCookieValue("sensitive-data", {
  password: "your-secure-password-at-least-32-chars-long!"
});
console.log(encrypted); // "1|iv_base64|salt_base64|encrypted_base64|signature|salt"

decryptCookieValue

Decrypts a cookie value encrypted with encryptCookieValue.
function decryptCookieValue(
  value: string,
  options: CookieEncryptionOptions
): Promise<string | undefined>
value
string
required
The encrypted value to decrypt
options
CookieEncryptionOptions
required
Decryption configuration with the same password used for encryption
result
Promise<string | undefined>
The decrypted value, or undefined if decryption fails
Example:
import { encryptCookieValue, decryptCookieValue } from "@temelj/request";

const options = {
  password: "your-secure-password-at-least-32-chars-long!"
};

const encrypted = await encryptCookieValue("secret", options);
const decrypted = await decryptCookieValue(encrypted, options);
console.log(decrypted); // "secret"

parseEncryptedCookie

Parses and decrypts an encrypted Set-Cookie header.
function parseEncryptedCookie(
  source: string,
  options: CookieEncryptionOptions
): Promise<Cookie | undefined>
source
string
required
The Set-Cookie header value with encrypted value
options
CookieEncryptionOptions
required
Decryption configuration
result
Promise<Cookie | undefined>
The parsed cookie with decrypted value, or undefined if invalid
Example:
import { parseEncryptedCookie } from "@temelj/request";

const headerValue = "session=1|...|...|...|...|...; Path=/; HttpOnly";
const cookie = await parseEncryptedCookie(headerValue, {
  password: "your-secure-password-at-least-32-chars-long!"
});

if (cookie) {
  console.log(cookie.value); // Decrypted value
}

serializeEncryptedCookie

Encrypts a cookie value and serializes it as a Set-Cookie header.
function serializeEncryptedCookie(
  cookie: Cookie,
  options: CookieEncryptionOptions
): Promise<string>
The cookie to encrypt and serialize
options
CookieEncryptionOptions
required
Encryption configuration
result
Promise<string>
The Set-Cookie header value with encrypted cookie value
Example:
import { serializeEncryptedCookie } from "@temelj/request";

const cookie: Cookie = {
  name: "session",
  value: "sensitive-data",
  path: "/",
  httpOnly: true,
  secure: true
};

const headerValue = await serializeEncryptedCookie(cookie, {
  password: "your-secure-password-at-least-32-chars-long!"
});

console.log(headerValue);
// "session=1|...|...|...|...|...; Path=/; HttpOnly; Secure"

Configuration

CookieEncryptionOptions

Options for cookie encryption and decryption.
interface CookieEncryptionOptions {
  password: string;
  algorithm?: string;
  integrityAlgorithm?: string;
  ivBits?: number;
  keyBits?: number;
  saltsBits?: number;
}
password
string
required
The encryption password (must be at least 32 characters)
algorithm
string
The encryption algorithm. Defaults to “AES-CBC”.
integrityAlgorithm
string
The HMAC signature algorithm. Defaults to “SHA-256”.
ivBits
number
Number of bits for the initialization vector. Defaults to 128.
keyBits
number
Number of bits for the encryption key. Defaults to 256.
saltsBits
number
Number of bits for the salt. Defaults to 256.

Common use cases

Express.js middleware

import { parseCookieHeader } from "@temelj/request";
import type { Request, Response, NextFunction } from "express";

function cookieParser(req: Request, res: Response, next: NextFunction) {
  const header = req.headers.cookie;
  if (header) {
    req.cookies = parseCookieHeader(header).reduce(
      (acc, cookie) => ({ ...acc, [cookie.name]: cookie.value }),
      {} as Record<string, string>
    );
  }
  next();
}

Secure session cookies

import { serializeEncryptedCookie } from "@temelj/request";

async function setSecureSession(userId: string): Promise<string> {
  return await serializeEncryptedCookie(
    {
      name: "session",
      value: userId,
      path: "/",
      httpOnly: true,
      secure: true,
      sameSite: "strict",
      maxAge: 86400 // 24 hours
    },
    {
      password: process.env.COOKIE_SECRET!
    }
  );
}
import { Cookie, serializeCookie } from "@temelj/request";

class CookieManager {
  private cookies = new Map<string, Cookie>();

  set(name: string, value: string, options: Partial<Cookie> = {}) {
    this.cookies.set(name, { name, value, ...options });
  }

  delete(name: string) {
    this.cookies.set(name, {
      name,
      value: "",
      maxAge: 0
    });
  }

  serialize(): string[] {
    return Array.from(this.cookies.values()).map(serializeCookie);
  }
}

Build docs developers (and LLMs) love