fn

createDocumentCookieAdapter

v0.0.14testeddemo

CookieStorageLike adapter over document.cookie: synchronous reads/writes that work in every browser and can express non-Secure cookies. Changes are observed through the Cookie Store API change event when the browser has one (covering other tabs, server responses, and expiry even though writes stay on document.cookie); otherwise every write pings a BroadcastChannel by cookie name and receivers re-read their own document.cookie (same-tab and cross-tab, ordering-proof since no value travels), with a same-tab CustomEvent as the last resort. Without the Cookie Store API, changes made outside the adapter (server Set-Cookie, other libraries) are not observed.

Example

ts
const store = createDocumentCookieAdapter(document);

Demo

Loading demo…

Signature

ts
export function createDocumentCookieAdapter(document: Document, options: DocumentCookieAdapterOptions ={ ... }

Parameters

ParameterTypeDescription
documentDocumentThe document whose cookies to read/write
options?DocumentCookieAdapterOptionsOptions (window)

Returns

CookieStorageLikeThe adapter
PropertyTypeDescription
getItem(name: string) => string | null | Promise<string | null>Read the raw (encoded) cookie value, null when absent.
setItem(name: string, value: string, attributes: CookieAttributes) => void | Promise<void>Write the raw value. Attributes carry the cookie's scope and lifetime.
removeItem(name: string, attributes: CookieAttributes) => void | Promise<void>Delete the cookie. Attributes carry the identity (path/domain) the deletion must repeat to match.
onChange?(name: string, callback: (newValue: string | null) => void) => () => voidOptional: observe changes of the given cookie (other tabs, server Set-Cookie responses, other instances). The callback receives the new raw value (null = deleted). Returns an unsubscribe function.
echoesOwnWrites?booleanWhether onChange also reports this context's own writes (e.g. the Cookie Store API change event does, a BroadcastChannel does not). The composable uses this to know when an own write will come back as a notification that must be swallowed instead of re-applied.