112 lines
7.5 KiB
Markdown
112 lines
7.5 KiB
Markdown
# Local-storage lib (`packages/libs/src/local-storage`)
|
|
|
|
One `LocalStorageAdapter` class over `window.localStorage` that puts every key under the app's prefix (`shop.cart`), so apps and third-party scripts on the same origin never overwrite each other. It implements the native `Storage` interface, so it drops into anything that expects `localStorage`, including zustand's `createJSONStorage`. Browser only; framework-agnostic; no dependency.
|
|
|
|
Contents: What local storage is for · Structure · API · Keys · Blocked storage · Browser only · Persisted zustand stores · Usage · Acceptance checklist
|
|
|
|
## What local storage is for
|
|
|
|
- Client-only data that should survive a reload and that the server never needs: UI preferences (table page size, collapsed sidebar), form drafts, recently viewed items, the last used phone number, persisted zustand stores.
|
|
- Data the server needs while rendering goes in a cookie ([lib-cookie.md](lib-cookie.md)). Server state goes in the TanStack Query cache, not here.
|
|
- Never tokens, secrets, or personal data that would hurt if leaked: any script on the page, including an XSS payload, can read local storage. Auth uses HttpOnly cookies ([lib-http.md](lib-http.md)).
|
|
- About 5 MB per origin, shared by every app on it. Keep values small and never cache large API responses here.
|
|
|
|
## Structure
|
|
|
|
```
|
|
packages/libs/src/local-storage/
|
|
├── local-storage.ts # LocalStorageAdapter class and the shared `storage` instance
|
|
├── types.ts # LocalStorageOptions
|
|
├── constants.ts # DEFAULT_STORAGE_PREFIX, STORAGE_KEY_SEPARATOR ('.')
|
|
└── index.ts
|
|
```
|
|
|
|
- `index.ts` exports `LocalStorageAdapter`, `storage`, `DEFAULT_STORAGE_PREFIX`, and the type `LocalStorageOptions`. Nothing goes in `server.ts`: the lib is browser-only.
|
|
- Import by subpath: `import { storage } from '@project/libs/local-storage'`.
|
|
- The instance is named `storage`, never `localStorage`, so it never shadows the global.
|
|
|
|
## API
|
|
|
|
```ts
|
|
interface LocalStorageOptions {
|
|
prefix: string; // the app's namespace, e.g. 'shop'; default DEFAULT_STORAGE_PREFIX
|
|
}
|
|
```
|
|
|
|
- Every key a caller passes is stored as `<prefix>.<key>`. Callers always use the short key; only the adapter knows the full one.
|
|
- `getItem(key)` returns the value or `null`; `setItem(key, value)` stores a string; `removeItem(key)` removes one key.
|
|
- The rest of `Storage` works inside the prefix only, so the adapter behaves like its own storage:
|
|
- `length` counts the keys under the prefix.
|
|
- `key(index)` returns the short key at that index among the prefixed keys, or `null`.
|
|
- `clear()` removes only the keys under the prefix. It never calls `window.localStorage.clear()`, which would delete other apps' and libraries' data.
|
|
- `clearByPrefix(subPrefix)` removes every key under `<prefix>.<subPrefix>`, for example `storage.clearByPrefix('session.')` on logout. Collect the matching keys first, then remove them, because removing while iterating shifts the indexes.
|
|
- `getJSON<T>(key)` parses the stored JSON and returns `null` for a missing key or invalid JSON (removing the broken value). The result is untrusted, since the data may be old or edited by the user, so callers that depend on its shape validate it with a valibot schema.
|
|
- `setJSON(key, value)` runs `JSON.stringify`, then `setItem`.
|
|
- `configure(options: LocalStorageOptions)` sets the prefix once, in the app's bootstrap. It only stores options and never touches `window`, so it's safe in `bootstrap.client.ts` during SSR. Changing a prefix later leaves the old keys behind, so pick it once per app.
|
|
- The shared instance is `export const storage = new LocalStorageAdapter();`. Create another `LocalStorageAdapter` only in tests.
|
|
|
|
## Keys
|
|
|
|
- Keys are constants in the owning project's `constants.ts` (`LAST_PHONE_STORAGE_KEY` in the auth feature), never string literals at call sites.
|
|
- Group keys by lifetime with a sub-prefix. `session.*` holds data that belongs to the logged-in user (drafts, recent items), and the logout action clears it with `storage.clearByPrefix('session.')`. Other keys are device preferences that survive logout.
|
|
- When the shape of a stored value changes, change the key (`cart.v2`) or use zustand persist's `version` and `migrate`, and remove the old key, so old data never breaks new code.
|
|
- Data written through the adapter isn't readable with `window.localStorage.getItem(key)` and the short key. Always read it back through `storage`.
|
|
|
|
## Blocked storage
|
|
|
|
- Browsers can block or limit storage: Safari private mode, storage disabled by the user or a policy, or a full quota. Access then throws `SecurityError` or `QuotaExceededError`.
|
|
- The adapter catches these: `getItem` returns `null`, `setItem` and `removeItem` do nothing, and a warning is logged in development only. Persisted data is a convenience, so the app keeps working without it.
|
|
- Features never depend on local storage for correctness. Anything that must not be lost goes to the server.
|
|
|
|
## Browser only
|
|
|
|
- Every method except `configure` checks `typeof window === 'undefined'` and throws a clear error ("storage is browser-only; never read it during render or on the server") instead of the unclear "window is not defined". Server access is a programming mistake, so it throws; blocked storage is the user's environment, so it's handled quietly.
|
|
- 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.
|
|
- Repositories never use it, so they stay server-safe.
|
|
|
|
## Persisted zustand stores
|
|
|
|
- Use the adapter as the storage: `persist(creator, { name: 'cart', storage: createJSONStorage(() => storage), version: 1, migrate })`. The name becomes the key, stored as `<prefix>.cart`; put it under `session.` when it belongs to the logged-in user.
|
|
- Persist only what must survive a reload, with `partialize`. Never loading flags or server data.
|
|
- Set `skipHydration: true` and call `useCartStore.persist.rehydrate()` in an effect of the platform's `AppShell`, so the server render and the first browser render match. Stores are never written during server render, so storage is never touched on the server.
|
|
|
|
Code: [code-patterns.md](code-patterns.md#persisted-store).
|
|
|
|
## Usage
|
|
|
|
Bootstrap (`bootstrap.client.ts`):
|
|
|
|
```ts
|
|
storage.configure({ prefix: 'shop' });
|
|
```
|
|
|
|
A model reading a preference in an effect, `features/catalog/models/products/use-products-page.ts`:
|
|
|
|
```ts
|
|
useEffect(() => {
|
|
const stored = storage.getJSON<number>(PRODUCTS_PAGE_SIZE_STORAGE_KEY);
|
|
if (stored !== null && PAGE_SIZES.includes(stored)) setPageSize(stored);
|
|
}, []);
|
|
```
|
|
|
|
The logout action:
|
|
|
|
```ts
|
|
storage.clearByPrefix(SESSION_STORAGE_PREFIX); // 'session.'
|
|
```
|
|
|
|
## Acceptance checklist
|
|
|
|
For building or changing the lib:
|
|
|
|
```
|
|
[ ] setItem('token', 'abc') writes '<prefix>.token'; getItem('token') reads it; window.localStorage.getItem('token') is null
|
|
[ ] removeItem removes only the prefixed key
|
|
[ ] length, key(index), and clear work inside the prefix only; keys of other prefixes and unprefixed keys survive clear
|
|
[ ] clearByPrefix('session.') removes every '<prefix>.session.*' key and nothing else
|
|
[ ] getJSON returns the parsed value, and null (removing the value) for a missing key or invalid JSON
|
|
[ ] With storage blocked or full, getItem returns null and setItem doesn't throw
|
|
[ ] Every method except configure throws the clear browser-only error on the server
|
|
[ ] zustand createJSONStorage(() => storage) persists and rehydrates a store under '<prefix>.<name>'
|
|
```
|