@luwiostack/storage
v0.1.1
Published
Typed, observable single-slot stores over Web Storage, browser cookies, or memory — a React-free core plus reactive useStore / useLocalStorage / useSessionStorage / useCookie hooks.
Readme
@luwiostack/storage
Small, typed, single-slot stores over Web Storage, browser cookies, or memory. A Store<T> is a
read / write / clear slot for one value behind a stable key. Reads never throw: an empty,
unavailable or invalid slot reads as null. A write that doesn't land throws a typed
StorageError — or stays silent, or reports to you, if you choose (onError).
It's the storage layer loaders like @luwiostack/bootstrap and
@luwiostack/cookie-consent plug into, but it's generic —
use it for anything you want to persist behind a key.
npm i @luwiostack/storageimport { sessionStore, localStore, cookieStore, memoryStore } from '@luwiostack/storage'
const prefs = sessionStore<{ theme: string }>('my-app:prefs')
prefs.write({ theme: 'dark' })
prefs.read() // → { theme: 'dark' } (or null if empty/unavailable/invalid — never throws)
prefs.clear()[!WARNING] Values are stored as JSON by default, and JSON only handles plain data: objects, arrays, strings, numbers, booleans and
null. It silently breaksDate,Map,Set,bigint,undefinedand class instances (details in the table under Options). To store those, pass a serializer that handles them. We recommend superjson:localStore('k', { serializer: superjson }). In development, a store warns in the console the first time you write such a value with the JSON default.
The Store<T> interface
interface Store<T> {
read(): T | null // the stored value, or null when empty/unavailable/invalid
write(value: T | null): void // store a value; null clears the slot
clear(): void // remove the stored value
}nullmeans "empty", so it can't be stored as a value:write(null)(orundefined) clears.read()never throws. Missing, unavailable, unreadable or invalid all read asnull.- After a write,
read()returns the value as stored — serialized, parsed back and validated — not the object you passed in. You see exactly what a reload will see, right away, and mutating your object afterwards can't make the store lie. - A failed
write()/clear()throws aStorageErrorby default — see When a write fails.
Backings
| Factory | Scope |
| --- | --- |
| sessionStore(key, options?) | sessionStorage — per tab, survives a refresh (not a new tab). |
| localStore(key, options?) | localStorage — persists across tabs and restarts, synced between tabs. |
| cookieStore(name, options?) | a browser cookie (document.cookie) — with a lifetime, sent to your server, synced between tabs. |
| memoryStore() | in-memory, by reference — for tests or SSR. Each call is its own slot. |
| store(key, getStorage, options?) | any StorageLike — the escape hatch for a custom backing. |
They all implement the same ObservableStore<T>, so they're interchangeable.
All of them are browser storage. On the server (SSR) they read as empty; a write there fails
with reason unavailable (pass onError: 'ignore' for code that runs on both sides).
Options
Every storage-backed store (localStore, sessionStore, cookieStore, store) and every
keyed hook takes the same options. memoryStore takes none: it keeps your value by reference and
never turns it into a string — so treat its values as immutable, as React state.
localStore<Prefs>('my-app:prefs', {
serializer: superjson, // how the value becomes a string, and back (default: JSON)
validate: PrefsSchema, // what counts as a usable value on read (default: anything)
onError: 'throw', // what a failed write does: 'throw' (default), 'ignore', or a function
})A read runs through them in this order:
stored string ──parse──▶ value ──validate──▶ T (any step failing → null)A write runs the same chain on the string it is about to store, and only stores it if it passes:
value ──stringify──▶ string ──parse──▶ ──validate──▶ ✓ store it (a failing step → StorageError)Recommended partners
This package depends on neither of these. It accepts anything with the same shape, so you can swap them out, but these two work as-is and cover nearly every case:
| Job | Partner | Why | Plugs in as |
| --- | --- | --- | --- |
| Serialization | superjson | Round-trips everything JSON breaks: Date, Map, Set, bigint, undefined, RegExp, URL, Error, and registered classes. | serializer: superjson |
| Validation | Zod | Schemas you likely already have for forms and API responses. It's a Standard Schema, so Valibot and ArkType schemas work the same way. | validate: MySchema |
npm i superjson zodimport superjson from 'superjson'
import { z } from 'zod'
import { localStore } from '@luwiostack/storage'
const Visit = z.object({
at: z.date(), // a real Date, thanks to superjson
pages: z.set(z.string()), // a real Set
theme: z.enum(['light', 'dark']).default('light'),
})
const lastVisit = localStore('my-app:last-visit', { serializer: superjson, validate: Visit })
// ^? ObservableStore<{ at: Date; pages: Set<string>; theme: 'light' | 'dark' }>
lastVisit.write({ at: new Date(), pages: new Set(['/home']), theme: 'dark' })
lastVisit.read()?.at.getFullYear() // a Date — even after a reloadWith a schema, you don't need a type argument: the store's type comes from the schema.
serializer — how a value becomes a string
Storage only holds strings, so a store turns your value into one on write and back on read. By
default that's JSON.stringify / JSON.parse.
JSON is only right for plain data. Everything below breaks — most of it without an error. A store reads back what it stored right after each write, so you see the damage immediately, not after a reload:
| You write | JSON gives back | |
| --- | --- | --- |
| new Date() | an ISO string, not a Date | .getFullYear() is not a function |
| new Map([['a', 1]]) | {} | the contents are lost |
| new Set(['a']) | {} | the contents are lost |
| 10n (bigint) | nothing: JSON.stringify throws | the write fails (StorageError, reason serialize) |
| { a: undefined } | {} | the property is dropped ([undefined] becomes [null]) |
| new Point(3, 4) (any class) | { x: 3, y: 4 } | no prototype, no methods; instanceof fails |
| NaN, Infinity | null | |
In development (NODE_ENV !== 'production', as your bundler sets it), a store using the JSON
default warns in the console the first time you write one of the silent ones, naming where the
value sits (production builds skip the check entirely):
[@luwiostack/storage] "my-app:visit": value.at is a Date — it reads back as an ISO string, not a Date.
The default serializer is JSON, which only stores plain data. Pass a serializer that handles it —
e.g. superjson: { serializer: superjson }.The fix is a serializer that handles them. superjson does all of the above:
import superjson from 'superjson'
const visit = localStore<{ at: Date; pages: Set<string> }>('my-app:visit', { serializer: superjson })For class instances, register the class once so superjson can rebuild it:
superjson.registerClass(Point, { identifier: 'Point' })For a single type, a hand-written serializer is enough. Any { parse, stringify } object works:
// A Date on its own.
const lastSeen = localStore<Date>('my-app:last-seen', {
serializer: { stringify: (date) => date.toISOString(), parse: (raw) => new Date(raw) },
})How a serializer has to behave:
- It must round-trip.
parse(stringify(value))should equalvalue. The store checks nothing here, so a lossy serializer silently stores less than you wrote. - A throw is handled. If
parsethrows on a stored string (corrupt or foreign),read()returnsnull. Ifstringifythrows or returns no string, the write fails with reasonserialize: nothing is stored or announced. - Parse runs once per stored string. A store caches the result, so
read()returns the same object until the stored string changes.parseshould still be quick and have no side effects. - Every store over the same key needs the same serializer. The string format is what the
stores share. If one store uses superjson and another plain JSON, the second reads superjson's
{ json, meta }envelope instead of your value. - Mind the size where space is tight. superjson adds a small
metaenvelope next to your data, which counts against storage quota and, for a cookie, against its 4 KB.
validate — what counts as a usable value
parse only checks that the string can be read, not that the result has the shape you expect.
Storage outlives your code: the value under my-app:prefs may have been written by last month's
release, a browser extension, or someone poking at dev tools. Without validate, whatever is there
comes out typed as T and fails somewhere far away. With it, a value that fails reads as null,
and your code (or a hook's initialValue) takes over.
With Zod, or any other Standard Schema library (Valibot, ArkType…), pass the schema itself:
import { z } from 'zod'
const Prefs = z.object({
theme: z.enum(['light', 'dark']),
fontSize: z.number().default(16),
})
const prefs = localStore('my-app:prefs', { validate: Prefs })
prefs.read() // → { theme: 'dark', fontSize: 16 } — the schema's output, defaults filled inread() returns the schema's output, so defaults and transforms apply. The schema must
validate synchronously: a read can't wait, so an async schema (an async refine) makes every
value read as null (and every write fail), and warns in development.
Without a library, pass a TypeScript type guard, so the check and the type can't drift apart:
interface Prefs {
theme: 'light' | 'dark'
fontSize: number
}
const isPrefs = (v: unknown): v is Prefs =>
typeof v === 'object' &&
v !== null &&
((v as Prefs).theme === 'light' || (v as Prefs).theme === 'dark') &&
typeof (v as Prefs).fontSize === 'number'
const prefs = localStore<Prefs>('my-app:prefs', { validate: isPrefs })What to know:
It runs on read — that's its job: TypeScript already checks what you write,
validatechecks what someone else wrote.And it guards your writes. A write is serialized, parsed back and validated before it's stored. A value that wouldn't read back fails with reason
invalidand is not stored, so the previous value stays. That catches a schema that doesn't accept its own output — e.g.z.string().transform((s) => new Date(s)): its output is aDate, which is not a string, so it could never be read back.It runs once per stored string, like
parse, so an expensive schema check doesn't run on every render.A failing value is not deleted. It stays in storage and reads as
nulluntil something writes or clears the key. That's on purpose: an older tab, still running the previous release, may be using it.It catches serializer mistakes too.
z.date()rejects the ISO string plain JSON gives back, instead of letting it through as a "Date".To upgrade old data instead of dropping it, use a schema that accepts both shapes and converts the old one. With Zod, that's a union plus a
transform:const PrefsV2 = z.object({ theme: z.enum(['light', 'dark']), fontSize: z.number() }) const PrefsV1 = z.object({ dark: z.boolean() }) const Prefs = z.union([ PrefsV2, PrefsV1.transform((v1) => ({ theme: v1.dark ? ('dark' as const) : ('light' as const), fontSize: 16 })), ])For a clean break, change the key instead (
my-app:prefs:v2) and clear the old one.
When a write fails
A write or clear that doesn't land throws a StorageError — by default. Its reason says why:
| reason | When | Typical cause |
| --- | --- | --- |
| unavailable | There is no storage to write to. | Server rendering; the browser blocks storage (cookies disabled). |
| serialize | The serializer can't make a string of the value. | A bigint or a circular reference with plain JSON. |
| invalid | The value wouldn't read back. | validate rejects the stored form — a schema whose input and output differ. |
| refused | The storage refused the write. | Quota exceeded; a cookie over 4 KB; a cookie path that excludes this page. |
error.key is the store's key, and error.cause the underlying error, if any. A failed write
changes nothing: the previous value stays, and subscribers aren't notified.
Some of these are bugs in your code (serialize, invalid), others are the environment you run in
(unavailable, refused). The onError option lets you decide per store:
import { localStore, StorageError } from '@luwiostack/storage'
// 'throw' (default): fail loudly.
const prefs = localStore<Prefs>('my-app:prefs')
try {
prefs.write(next)
} catch (error) {
if (error instanceof StorageError && error.reason === 'refused') showStorageFullNotice()
else throw error
}
// 'ignore': a nice-to-have, like a remembered counter — if it can't be kept, so be it.
const visits = localStore<number>('my-app:visits', { onError: 'ignore' })
// A function: keep going, but report it.
const draft = localStore<Draft>('my-app:draft', {
onError: (error) => reportError(error), // e.g. Sentry; the write doesn't throw
})Reads never throw, whatever onError says: an empty, unreadable or invalid slot is null.
With the hooks
The keyed hooks (useLocalStorage, useSessionStorage, useCookie) take the same options as
their third argument. They read them once per key, so an inline object doesn't rebuild the
store on every render, but changing a serializer while mounted has no effect until the key
changes. Define schemas at module scope:
import superjson from 'superjson'
const Prefs = z.object({ theme: z.enum(['light', 'dark']), fontSize: z.number() })
const DEFAULT_PREFS: z.infer<typeof Prefs> = { theme: 'light', fontSize: 16 }
function Settings() {
const [prefs, setPrefs] = useLocalStorage('my-app:prefs', DEFAULT_PREFS, {
serializer: superjson,
validate: Prefs,
})
// prefs is DEFAULT_PREFS while the stored value is missing or invalid
}Browser cookies
cookieStore keeps the value in a cookie, through document.cookie. Use it instead of
localStore when the value needs what only a cookie has: a lifetime you choose, sharing
across subdomains, or being sent to your server with every request (a locale or theme the
backend should see).
import { cookieStore } from '@luwiostack/storage'
const theme = cookieStore<'light' | 'dark'>('theme', {
maxAge: 365 * 24 * 60 * 60 * 1000, // a year, in milliseconds; omit for a session cookie
})
theme.write('dark') // → document.cookie: theme=%22dark%22; Path=/; Max-Age=31536000; SameSite=Lax
theme.read() // → 'dark'
theme.clear() // deletes the cookie| Option | Default | |
| --- | --- | --- |
| maxAge | — | Lifetime in milliseconds, written as Max-Age in seconds. |
| expires | — | Absolute expiry as epoch milliseconds. maxAge wins when both are set. Neither: a session cookie, gone when the browser closes. |
| path | '/' | The cookie is visible (and sent) under this path. |
| domain | the current host | Set example.com to share with subdomains. Omitting it is safer. |
| sameSite | 'lax' | 'strict': never sent on cross-site requests. 'none': always (forces secure). |
| secure | true on https: | Only sent over HTTPS. |
| serializer, validate | JSON, none | The same options as every store. |
- Browser-only. On the server it reads as empty and writes nothing, like
localStore. (Your server receives the cookie in the request'sCookieheader, but reading it there is your server framework's job, not this package's.) - Synced. Stores over the same cookie name stay in sync, and other tabs hear about a write
over a
BroadcastChannel. A change made by the server (Set-Cookie) or another script isn't announced; it's seen on the next read. - Keep it small. A browser refuses a cookie over 4 KB; the write then fails with reason
refused(nothing is stored or announced), as it does when cookies are disabled or the cookie'spath/domainexcludes the current page (it could never be read back here). Every cookie is also sent with every request, so big cookies slow every request down. superjson's envelope counts too. - Not for secrets. A cookie script can write, any script can read. Tokens belong in an
HttpOnlycookie, and only a server'sSet-Cookieheader can create one: browsers refuseHttpOnlyfrom script. PassinghttpOnlyhere throws aTypeError. - The value is JSON, URI-encoded:
'dark'is stored astheme=%22dark%22. If your server reads the cookie, it sees that. For a plaintheme=dark, pass a pass-through serializer:serializer: { stringify: (v) => v, parse: (raw) => raw as 'light' | 'dark' }. - Consent. A preference cookie is subject to consent like any other storage. Gate it with
@luwiostack/cookie-consentwhere your policy requires. - An invalid cookie name,
pathordomainthrows aTypeErrorwhen the store is created.
Custom backings
store takes any StorageLike — just getItem, setItem and removeItem. Pass it through a
lazy factory rather than eagerly, so a store built at module scope stays SSR-safe and only
touches storage on access. Stores over the same backing object and key stay in sync.
import { store, type StorageLike } from '@luwiostack/storage'
const backing: StorageLike = createMyIndexedDbMirror()
const prefs = store('my-app:prefs', () => backing)setItem may throw (quota, read-only backing) — the write then fails with reason refused. Or write
your own Store<T> from scratch by implementing the methods directly.
Subscribing to changes
Every store is observable: subscribe(onChange) fires on each change to its slot — from this
document, and for localStorage and browser cookies from other tabs too — and returns an
unsubscribe.
read() returns the same reference until the value changes, so a store can drive
useSyncExternalStore directly. A subscriber that throws never breaks the write that triggered it.
const theme = localStore<string>('my-app:theme')
const off = theme.subscribe(() => console.log('now', theme.read()))React hooks
@luwiostack/storage/react turns any store into useState-shaped state that stays in sync across
every component using it. React is an optional peer; the root entry never imports it.
import { localStore } from '@luwiostack/storage'
import { useLocalStorage, useStore } from '@luwiostack/storage/react'
function ThemeToggle() {
const [theme, setTheme, removeTheme] = useLocalStorage('my-app:theme', 'light')
return (
<button type="button" onClick={() => setTheme((t) => (t === 'light' ? 'dark' : 'light'))}>
{theme}
</button>
)
}
// Any store — build it once, at module scope.
const session = localStore<User>('my-app:session')
function Avatar() {
const [user] = useStore(session, null)
return user ? <img src={user.avatarUrl} alt="" /> : null
}| Hook | |
| --- | --- |
| useStore(store, initialValue) | [value, setValue, remove] over any ObservableStore. |
| useLocalStorage(key, initialValue, options?) | The same over localStore(key). |
| useSessionStorage(key, initialValue, options?) | The same over sessionStore(key). |
| useCookie(name, initialValue, options?) | The same over cookieStore(name). |
value falls back to initialValue while the slot is empty; setValue takes a value or an
updater, and like write throws a StorageError on failure unless the store's onError says
otherwise. The keyed hooks build their store once per key — inline options don't rebuild it.
Server rendering. Browser storage can't be read on the server, so these hooks render
initialValue on the server and during hydration, then switch to the stored value right after.
With the bootstrap loader
@luwiostack/bootstrap's createBootstrap loader takes any Store:
import { createBootstrap, httpSource } from '@luwiostack/bootstrap'
import { sessionStore } from '@luwiostack/storage'
createBootstrap({ fetch: httpSource('/api/config'), storage: sessionStore('my-app:bootstrap') })