IMAD EDDINE NOUALI

BY IMAD EDDINE NOUALI  - DEC 4, 2026

Designing React Storage Persist: an Open-Source Case Study

react-storage-persist is an open-source, type-safe browser storage library for React and TypeScript that I author and maintain. This post is less about how to use it and more about the decisions behind it: the API shape, how it degrades when storage is unavailable, what a bug-fix release taught me, and how I version it.


The problem

Persisting a bit of UI state looks like a one-liner: localStorage.setItem(key, JSON.stringify(value)). In production it rarely stays that simple:

  • window does not exist during server rendering, so naive code crashes in Next.js.
  • Storage can exist but still throw on write (private browsing, quota exceeded, blocked cookies).
  • Values never expire, so stale data quietly outlives the feature that wrote it.
  • Two tabs of the same app drift out of sync.
  • Large or structured data belongs in IndexedDB, which has a completely different, asynchronous API.

Each app ends up with its own half-finished wrapper. I wanted one well-tested layer that handles these cases once, with an API that feels native to React.

Design goals

  • One API for every engine: localStorage, sessionStorage, IndexedDB and in-memory.
  • Never crash the app because storage is missing; degrade instead.
  • React ergonomics: hooks that read like useState and useReducer.
  • Type safety end to end, with inference from default values.
  • Extensible without growing the core: features such as compression or encryption are opt-in.

API design: an async core, synchronous-feeling hooks

The first real decision was making the core API asynchronous. localStorage is synchronous, but IndexedDB is not, and a single interface has to fit the slowest engine. Promises everywhere cost a little ceremony for simple cases, but they mean switching engines never changes calling code.

import { createStorage } from 'react-storage-persist/core';

const storage = createStorage({
  engine: 'localStorage',
  prefix: 'myapp_',
  ttl: 3600, // seconds
});

await storage.set('user', { name: 'John' });
const user = await storage.get<User>('user');

The React layer hides that asynchrony. Hooks mirror the built-ins they replace, so adoption is a rename rather than a refactor:

const [name, setName] = useStorage('user.name', 'Guest');
const [state, dispatch] = useStorageReducer('counter', reducer, { count: 0 });
const [theme, setTheme] = useStorageSync('theme', 'light'); // shared across tabs

There are seven hooks in total (useStorage, useStorageState, useStorageReducer, useStorageList, useStorageSync, useStorageEvent, useStorageInstance) plus a StorageProvider for configuring an instance per subtree. Entry points are split into /core, /react and /middleware so an app only bundles what it imports.

Fallback strategy

Checking that window.localStorage exists is not enough: some browsers expose it and then throw on the first write. Each engine therefore proves it works by writing and removing a probe key. If the primary engine fails, the configured fallbacks are tried in order:

const storage = createStorage({
  engine: 'localStorage',
  fallback: ['sessionStorage', 'memory'],
});

The in-memory engine is always available, which is also what makes the library safe during server rendering: on the server there is no window, availability checks fail, and the app keeps working with an ephemeral store instead of crashing. Only when every option fails does the library throw a typed StorageError.

Expiry with a storage envelope

Values are not stored raw. Each write is wrapped in a small envelope that carries metadata:

{
  value: <your data>,
  metadata: { createdAt: 1733300000000, expiresAt: 1733303600000 }
}

Reads check expiresAt and treat expired entries as missing, and a periodic cleanup removes them so they do not take up quota. A default TTL can be set per instance and overridden per write.

Middleware: ordering is the whole design

Compression, encryption, validation and logging are middleware rather than core features. A middleware can transform values on the way in (beforeSet) and on the way out (afterGet).

The subtle part is order. If you compress then encrypt on write, you must decrypt then decompress on read. So beforeSet hooks run in registration order and afterGet hooks run in reverse, like layers of an onion. Any stack of transforms then inverts correctly without the user having to think about it.

storage.use(compressionMiddleware({ threshold: 1024 })); // native CompressionStream
storage.use(encryptionMiddleware({ key, algorithm: 'aes-gcm' })); // Web Crypto

I also try to be honest in the docs about what a client-side library can promise. AES-GCM through the Web Crypto API is real encryption, but any key shipped in a client bundle can be read by whoever can read the page. It protects data at rest from other scripts and casual inspection, not from a determined attacker, and the README says so.

Cross-tab sync and events

Every write emits a typed change event (set, remove, clear, ...) that apps can subscribe to per key or globally. For localStorage and sessionStorage the library also listens to the browser's storage event, so a change in one tab updates hooks in the others.

What a patch release taught me

Version 1.2.1 was a focused bug-fix release. A few of the fixes are worth sharing because they are exactly the kind of bug that unit tests of the happy path never catch:

  • Infinite recursion on expired keys. Reading an expired entry triggered its removal, and the removal path read the entry again, so get → remove → get looped forever and froze the page. The periodic cleanup could trigger it too.
  • Leaking the envelope across tabs. Cross-tab events delivered the internal { value, metadata } wrapper instead of the value, and skipped decryption. They now go through the same read pipeline as normal reads.
  • Tabs echoing each other. useStorageReducer wrote state it had just received from storage back to storage, so two open tabs bounced the same write forever.
  • A mount-time race. useStorage subscribed to changes only after its first read resolved, so a write landing in between was lost. It now subscribes on mount.
  • Middleware order. afterGet originally ran in registration order, which broke compression combined with encryption. That is where the onion rule above came from.

The common thread: storage is shared, asynchronous state, and most bugs live at the boundaries between tabs, between reads and writes in flight, and between layers of middleware.

Testing strategy

  • 300+ unit tests with Vitest, using a DOM environment and an in-memory IndexedDB implementation so every engine runs in CI.
  • End-to-end tests with Playwright in real browsers, where storage quirks actually show up.

Versioning and deprecations

For a library, the release process is part of the API. I follow semantic versioning and keep a human-written changelog with Added, Fixed, Deprecated and Upgrade notes sections.

Breaking changes go through a deprecation first. For example, the old base64 and simple-xor "encryption" modes only obfuscate data. Removing them in a patch would break existing users, so 1.2.1 added real AES-GCM, kept the old modes readable, shows a one-time console warning when they are used, and documents that the default changes in the next major version.

What's next

I am working on v2, which moves to a framework-neutral core and adds Vue support, so the same storage engine can power more than React.

The code is on GitHub and the package on npm. Issues and feedback are welcome.


YOU MIGHT ALSO LIKE...