6.5 KiB
6.5 KiB
Cookie lib (packages/libs/src/cookie)
One small CookieAdapter class over document.cookie: get, set, and remove with encoding, safe defaults (path=/, SameSite=Lax, Secure), and per-call options. Browser only; framework-agnostic; no dependency (no js-cookie).
Contents: What cookies are for · Structure · Types · API · Keys · Browser only · Server side · Usage · Acceptance checklist
What cookies are for
- Only small values the server must see on the request:
locale,theme, and device preference (so the server renders the right version without a flash), and the consent choice. - Every cookie is sent with every request to its domain and path and holds about 4 KB. Anything the server doesn't need goes to local storage (lib-local-storage.md).
- Never auth tokens. Auth cookies are
HttpOnly, set and rotated by the server, and JavaScript can't and mustn't read them (see lib-http.md, Refresh token). Never secrets or personal data.
Structure
packages/libs/src/cookie/
├── cookie.ts # CookieAdapter class and the shared `cookie` instance
├── types.ts # CookieAdapterAbstraction, CookieOptions
├── constants.ts # DEFAULT_COOKIE_OPTIONS
└── index.ts
index.tsexportsCookieAdapter,cookie,DEFAULT_COOKIE_OPTIONS, and the typesCookieAdapterAbstractionandCookieOptions. Nothing goes inserver.ts: the lib is browser-only.- Import by subpath:
import { cookie } from '@project/libs/cookie'.
Types
interface CookieOptions {
path?: string; // default '/'
domain?: string; // default: none (current host only); set it to share with subdomains, e.g. '.example.com'
maxAgeDays?: number; // lifetime in days; omit for a session cookie
sameSite?: 'Strict' | 'Lax' | 'None'; // default 'Lax'
secure?: boolean; // default true; forced to true when sameSite is 'None'
}
interface CookieAdapterAbstraction {
get(key: string): string | null;
set(key: string, value: string, options?: CookieOptions): void;
remove(key: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void;
}
API
get(key)returns the decoded value, ornullwhen the cookie doesn't exist. It finds theencodeURIComponent(key)=entry indocument.cookiesplit by'; 'and decodes the rest, so values containing=stay whole. A value with broken percent-encoding (written by other code) is returned raw instead of throwing.set(key, value, options?)writeskey=valuewithencodeURIComponenton both, plus the attributes:- Options merge in this order:
DEFAULT_COOKIE_OPTIONS→configuredefaults → call options. maxAgeDaysbecomesmax-agein seconds (Math.floor(days * 24 * 60 * 60)); without it the cookie is a session cookie.sameSite: 'None'always addsSecure, because browsers reject it otherwise.
- Options merge in this order:
remove(key, options?)writes the cookie empty withmax-age=0. It must use the samepathanddomainthe cookie was set with, or the browser keeps the original. Defaults come fromconfigure, so keep them the same for set and remove.configure(defaults: CookieOptions)sets the defaults once, in the app's bootstrap. It only stores options and never touchesdocument, so it's safe inbootstrap.client.tsduring SSR. For example,cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE }), from the app's env, lets local development over plainhttpon a non-localhost host turnSecureoff.- There is no public mutable
optionsproperty: on a shared instance, any code could change every other caller's cookies at any time. Per-call differences go in the call's options. - The shared instance is
export const cookie = new CookieAdapter();. Create anotherCookieAdapteronly in tests.
Keys
- Cookie names are constants in the owning project's
constants.ts(LOCALE_COOKIE,THEME_COOKIE), never string literals at call sites. - Names are a contract with the server:
proxy.ts, Server Components, and the back end read the same names, so renaming one is a breaking change. - Names are not prefixed automatically (unlike local-storage keys), because the server reads them by their exact name.
Browser only
- Every method except
configurecheckstypeof document === 'undefined'and throws a clear error ("cookie is browser-only; on the server read cookies with next/headers") instead of the unclear "document is not defined". - Call it only in event handlers, effects, actions, and client bootstrap code. Never during render and never at module top level: client components also render on the server, and a value read during render differs between server and browser, which breaks hydration.
Server side
- Server code reads cookies with
cookies()fromnext/headers(Server Components, Route Handlers, Server Functions) orrequest.cookiesinproxy.ts, inside the app or platform. The lib never imports Next.js. - Server Components can't set cookies. Set them in
proxy.ts, a Route Handler, or a Server Function on the server, or withcookie.setin the browser. - A value the page needs while rendering (theme) is read on the server and passed down as a prop. The browser writes it with
cookie.setwhen the user changes it, then refreshes or updates the UI.
Usage
Bootstrap (bootstrap.client.ts):
cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE });
features/preferences/actions/change-theme/actions.ts
import { cookie } from '@project/libs/cookie';
import { usePreferencesStore } from '../../../../stores/preferences';
import { THEME_COOKIE, THEME_COOKIE_MAX_AGE_DAYS } from '../../constants';
import type { Theme } from '../../entities/theme';
export function changeTheme(theme: Theme): 'ok' {
cookie.set(THEME_COOKIE, theme, { maxAgeDays: THEME_COOKIE_MAX_AGE_DAYS });
usePreferencesStore.getState().setTheme(theme);
return 'ok';
}
Acceptance checklist
For building or changing the lib:
[ ] set, get, and remove round-trip a value, including values with "=", ";", spaces, and non-Latin text (e.g. Persian)
[ ] get returns null for a missing cookie and doesn't match a cookie whose name only starts with the key ("theme" vs "theme-v2")
[ ] A value with broken percent-encoding is returned raw, not thrown
[ ] maxAgeDays writes the right max-age; no maxAgeDays writes a session cookie
[ ] sameSite 'None' always writes Secure
[ ] Call options win over configure defaults, which win over DEFAULT_COOKIE_OPTIONS
[ ] remove with the configured path and domain deletes the cookie
[ ] get, set, and remove throw the clear browser-only error on the server; configure doesn't