Overview
The request utilities module provides comprehensive functions for working with HTTP cookies, including parsing, serialization, encryption, and header manipulation.
Cookie interface
Cookie
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>;
}
The domain the cookie applies to
Whether the cookie is HTTP-only (not accessible via JavaScript)
The path the cookie applies to
priority
'low' | 'medium' | 'high'
Cookie priority for resource budgeting
sameSite
'strict' | 'lax' | 'none'
SameSite attribute for CSRF protection
Whether the cookie requires HTTPS
Whether the cookie is partitioned (CHIPS)
Additional custom cookie attributes
Basic operations
parseCookie
Parses a Set-Cookie header value into a Cookie object.
function parseCookie(source: string): Cookie | undefined
The Set-Cookie header value
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 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"
Parses a Cookie header value into an array of cookies.
function parseCookieHeader(header: string): Cookie[]
The Cookie header value (semicolon-separated)
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" }
// ]
Serializes an array of cookies into a Cookie header value.
function serializeCookieHeader(cookies: Cookie[]): string
Array of cookies to serialize
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>
options
CookieEncryptionOptions
required
Encryption configuration including password
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>
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>
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
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;
}
The encryption password (must be at least 32 characters)
The encryption algorithm. Defaults to “AES-CBC”.
The HMAC signature algorithm. Defaults to “SHA-256”.
Number of bits for the initialization vector. Defaults to 128.
Number of bits for the encryption key. Defaults to 256.
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!
}
);
}
Cookie management
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);
}
}