fn

serializeCookie

v0.0.5

Builds a document.cookie assignment string from an already-encoded name and value (see encodeCookieName / encodeCookieValue) plus CookieAttributes. Path and SameSite are always emitted explicitly. Fails loudly on combinations browsers silently drop: SameSite=None or Partitioned without Secure, and name=value over 4096 UTF-8 bytes.

Examples

ts
document.cookie = serializeCookie('theme', 'dark', { maxAge: 3600 });
// 'theme=dark; Path=/; SameSite=Lax; Max-Age=3600'
ts
// Deleting reuses the same identity attributes with a non-positive maxAge
document.cookie = serializeCookie('theme', '', { maxAge: 0 });

Signature

ts
declare function serializeCookie(name: string, value: string, attributes?: CookieAttributes): string;

Parameters

ParameterTypeDescription
namestringThe encoded cookie name
valuestringThe encoded cookie value
attributes?CookieAttributesWrite-time attributes

Returns

stringThe string to assign to document.cookie