110 lines
6.5 KiB
Markdown
110 lines
6.5 KiB
Markdown
# 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](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](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.ts` exports `CookieAdapter`, `cookie`, `DEFAULT_COOKIE_OPTIONS`, and the types `CookieAdapterAbstraction` and `CookieOptions`. Nothing goes in `server.ts`: the lib is browser-only.
|
|
- Import by subpath: `import { cookie } from '@project/libs/cookie'`.
|
|
|
|
## Types
|
|
|
|
```ts
|
|
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, or `null` when the cookie doesn't exist. It finds the `encodeURIComponent(key)=` entry in `document.cookie` split 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?)` writes `key=value` with `encodeURIComponent` on both, plus the attributes:
|
|
- Options merge in this order: `DEFAULT_COOKIE_OPTIONS` → `configure` defaults → call options.
|
|
- `maxAgeDays` becomes `max-age` in seconds (`Math.floor(days * 24 * 60 * 60)`); without it the cookie is a session cookie.
|
|
- `sameSite: 'None'` always adds `Secure`, because browsers reject it otherwise.
|
|
- `remove(key, options?)` writes the cookie empty with `max-age=0`. It must use the same `path` and `domain` the cookie was set with, or the browser keeps the original. Defaults come from `configure`, 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 touches `document`, so it's safe in `bootstrap.client.ts` during SSR. For example, `cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE })`, from the app's env, lets local development over plain `http` on a non-localhost host turn `Secure` off.
|
|
- There is no public mutable `options` property: 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 another `CookieAdapter` only 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 `configure` checks `typeof 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()` from `next/headers` (Server Components, Route Handlers, Server Functions) or `request.cookies` in `proxy.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 with `cookie.set` in 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.set` when the user changes it, then refreshes or updates the UI.
|
|
|
|
## Usage
|
|
|
|
Bootstrap (`bootstrap.client.ts`):
|
|
|
|
```ts
|
|
cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE });
|
|
```
|
|
|
|
`features/preferences/actions/change-theme/actions.ts`
|
|
|
|
```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
|
|
```
|