Cookie
How to define a preference such as display density as cookie state, and which attributes the browser writes. A cookie travels with every request to the server.
On this page
Defining a cookie state
src/state.tsimport { defineCookieState } from '@k8ordo/state';
import * as z from 'zod';
export const density = defineCookieState(
'density',
z.object({
density: z
.enum(['comfortable', 'compact'])
.default('comfortable'),
}),
);Hand defineCookieState a key and a schema. It is written like defineLocalState, and the schema follows the rules on Storage and memory.
The values are kept in one cookie named k8ordo-state.density, as the JSON of the declared fields. The definition exposes the name as cookieName.
A cookie name is an HTTP token, so a key may hold only letters, digits and a few symbols. A key with a space, a : or a ; throws a TypeError saying cannot name a cookie as the module loads.
Writes from the browser
update() writes the cookie with the Cookie Store API. It sets these four attributes, again on every write.
Path=/: it goes with a request to any path on the site.SameSite=Lax: it goes with the first request arriving from a link on another site. Under the API’s defaultStrict, the server would render the defaults on that request.Max-Age: 400 days, the longest a browser keeps a cookie, renewed by every write.Secure: the API always sets it, so serve the page over HTTPS. Chromium and Firefox keep the cookie onhttp://localhost, but Safari does not store it, so develop over HTTPS to check in Safari.
Reads go through document.cookie, synchronously, because a render cannot wait for the API’s promise. Writes from other tabs, and cookies a server response set, come in through the API’s change event.
The cookie goes with every request, so keep it small. Over 4 KB, name and value together, the browser refuses the write: the update() handle rejects with the API’s TypeError, and the rendered value stays.
Secrets
A cookie the browser writes can never be HttpOnly. Any script on the page can read and rewrite it, and a visitor can edit it as freely as a URL.
Pitfall
Keep out anything that must not leak or be forged, such as sessions and tokens. The server writes such cookies as HttpOnly, and this package never reads them.