Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / Pages and UI / Browser storageRead Markdown
    On this page

    Use typed browser storage helpers

    Read, write, remove, validate, and test JSON-serialized browser values outside component render lifecycles.

    Storage is persisted client state. For in-memory coordination across Preact island roots on one page, use stores instead.

    Use raw helpers outside components

    #
    src/features/preferences/visits.ts
    import { getLocalStorageItem, removeLocalStorageItem, setLocalStorageItem } from "brix/storage";
    import { profileKey } from "./storage-keys.ts";
    
    setLocalStorageItem(profileKey, { displayName: "Ada", visits: 3 });
    const profile = getLocalStorageItem(profileKey);
    removeLocalStorageItem(profileKey);
    

    profileKey is the key defined in keys and bindings. After the write, profile is { displayName: "Ada", visits: 3 }; after removal, a new read returns null. The local/session wrappers also return null during SSR, so use them for optional browser state rather than required server data. Call them from event handlers, effects, or other browser code; components should use the reactive hooks.

    The helpers come in three families:

    • Local storage: getLocalStorageItem, setLocalStorageItem, and removeLocalStorageItem.
    • Session storage: getSessionStorageItem, setSessionStorageItem, and removeSessionStorageItem.
    • Generic: getStorageItem, setStorageItem, and removeStorageItem take a supplied Storage first, so they work with compatible in-memory or platform implementations.

    Each read and write accepts a StorageKey or an inline (key, schema) pair; removals accept a StorageKey or the key string. Writes made through these helpers notify mounted hooks for the same storage object and key.

    All values are JSON encoded, including strings. Do not read the underlying item and assume its stored text equals the logical string value.

    Validation and errors

    #

    Reads are lenient because browser data may be malformed or from an older schema:

    • Valid JSON is parsed through Zod and returns schema output, including transformations and object-key stripping.
    • Malformed JSON or schema-invalid data returns null.
    • A storage object that throws on access also reads as null.

    Exceptions thrown by application transforms or refinements propagate from reads; they are programmer callback failures, not ordinary Zod validation issues. This also applies when a hook parses data during rendering. Express expected rejections as Zod validation issues rather than throwing.

    Raw writes are strict about the schema. They validate both the supplied input and its JSON-normalized snapshot, and throw Zod's error if either fails, before anything is written. They persist that validated input JSON rather than the parsed output, so transformed schemas remain readable when the same schema is applied later. This also means extra object fields that a read would strip are retained in storage.

    Other write failures are silent, because the setters return nothing:

    • If serialization fails or produces no JSON text, the stored value and subscribers stay unchanged. This covers values such as a BigInt or a cyclic object, and top-level undefined even with an optional or defaulted schema: Brix persists input, not the schema's default or transformed output. Use a remove helper to delete an item. Normal JSON rules still apply to nested values, including omitted undefined object fields.
    • If the browser rejects the write, for example because of a quota or privacy policy, the previous value stays in place.
    • Without available local or session storage, including during SSR, the local and session setters still validate and throw for an invalid value, then skip the write.

    Read the value back when you must confirm that it was persisted. Hook writes are more forgiving still: they never throw, and invalid input leaves both storage and rendered state unchanged.

    Storage schemas describe JSON wire input, unlike the richer island-prop serializer. A z.date() input becomes a string in JSON and is rejected before it can overwrite saved data. Use an ISO string input with a transform when components need a Date output:

    src/features/drafts/saved-at.ts
    import { createStorageKey, getLocalStorageItem, setLocalStorageItem } from "brix/storage";
    import { z } from "brix/zod";
    
    const savedAtKey = createStorageKey(
      "saved-at",
      z.iso.datetime().transform((value) => new Date(value)),
    );
    
    setLocalStorageItem(savedAtKey, new Date().toISOString());
    const savedAt = getLocalStorageItem(savedAtKey); // Date | null
    

    Existing JSON-native inputs need no migration. Domain objects must be projected to wire input before writing. Keep schema callbacks pure: writes validate twice and reads parse again.

    Do not use storage for secrets, authorization decisions, or trustworthy server state. Browser users can inspect and modify it. Validate again at every API or server boundary.

    SSR and unavailable storage

    #

    The local and session convenience APIs do not access window during SSR:

    • Reads return null.
    • Writes and removals are no-ops, though setters still throw for invalid values.
    • Local and session hooks initially render with null on both server and browser, then read storage in an effect after mounting.

    Browser privacy settings, sandboxing, and quota failures degrade similarly: reads return null, and writes or removals do not break rendering. Account for server-to-client changes when persisted data affects visible markup; keep the server fallback deterministic to avoid hydration surprises. See islands for serialization and hydration boundaries.

    Test behavior

    #

    Use browser component tests for hooks, events, and cross-tab behavior. Node tests have no window, so local and session helpers there behave as on the server. For raw logic, use the generic helpers with an injected test Storage implementation and cover valid values, malformed JSON, data from an older schema, removal, and write failures. Include a transforming schema, such as string input to numeric output, to catch code that stores parsed output instead of input. Reset keys between tests to prevent state leakage.

    brix test --project browser
    brix test --project node
    brix check
    

    See testing for selecting browser and node projects. Persisted values are independent of Brix's server-side data caching.