React
This guide takes a fresh Vite + React project to a fully offline resilient, single bootstrap, realtime synced app, with user data encrypted at rest and a clear split between global and per user offline queues, using whichever state manager you already work with.
- An existing Vite + React project.
- (Optional)A backend you can subscribe to: Supabase, or any server that can speak Socket.io, SSE, or raw WebSocket.
- Node 18+.
- (Optional)For encrypted user data (Steps 17 to 20): a backend route that can verify your signed in user, so the key route knows who is asking.
Install the core package
Install the React integration
FluxProvider, HydrationGate, FluxErrorBoundary, fluxVitePlugin (the Vite plugin that injects your service worker at build time), and the useFlux() / useFluxTime() hooks, the same hooks flux-next ships, minus anything Next.js specific like RSC handling.Choose your realtime adapter
createPollingAdapter() still gets you full IDB caching, the offline queue, and the SW layer. You are only trading live push updates for a polling interval. Swap in a real adapter later with no changes to your register() calls. If you have no backend at all, such as static marketing pages or fully hardcoded data, choose the **No realtime backend** option above and use createNoopAdapter() instead. It disables the realtime layer entirely while keeping the rest of the stack.
Define your precache route manifest
Configure the Vite plugin
withFlux() in Next.js, this plugin has no server rendered build manifest to read for dynamic route chunk warming. Vite emits a client only dist/.vite/manifest.json, and fluxVitePlugin reads it in closeBundle to bake chunk hashes into the generated service worker.In a plain Vite SPA or CRA there is exactly one HTML document for every route. That means dynamicRoutePrefixes on its own already gets a dynamic route, and everything under it, tabs and nested subpages included, working offline: a hard miss just serves index.html and your client side router mounts the right screen from window.location, same as it does online. dynamicRouteShapes has nothing to add there, because there is no second document to precache, and dynamicRouteIdbKeys is never consulted, because the worker serves the one document without checking IDB first.
Remix is different: each route genuinely is its own server rendered document, so dynamicRouteShapes becomes meaningful there (see Step 13), and so does dynamicRouteIdbKeys, which tells the worker where to look to confirm it has data for a slug before serving a cached shell. fluxVitePlugin resolves which mode you are in automatically by checking your package.json for a @remix-run/* dependency and defaulting isSpa accordingly. You only need to set isSpa by hand if you are running Remix's own SPA mode (unstable_ssr: false), which is not detectable from package.json alone. An explicit value you set always overrides the detected default.
idbKey and listKey must be exactly the idbKey values you pass to flux.register() for the detail and list channels, and the keys of dynamicRouteIdbKeys must match dynamicRoutePrefixes exactly, trailing slash included. If they drift apart the service worker looks in the wrong place and refuses to open a route that has perfectly good cached data, with no error.
Add your manifest.json
public/manifest.json. Flux's service worker reads it during installation to configure the PWA shell. This step is required for every app, static sites included, because the SW uses the manifest icons and theme colors for the offline splash.Define your types (TypeScript only)
Create your state store
store on register() needs a setState(data) method with this exact signature, because dispatchToStore calls it directly on every IDB cold boot read, every bootstrap dispatch, every realtime event, and, as of Step 16, every confirmed local write too.Zustand: native, no adapter needed
Redux Toolkit
Jotai
createStore() since Flux dispatches outside of the React render tree:Stunk
Create the Flux engine singleton
ensureClusterBootOnce(), which starts the realtime layer, and Step 11 shows where to call it.Pick the tab matching the adapter you installed in Step 3. Vite modules execute once per page load, functioning naturally as singletons without Fast Refresh engine guards. Every tab exports ensureClusterBootOnce(), which starts the realtime layer, and Step 11 shows where to call it. This only covers 'global' scoped registration. If you also register 'user' scoped channels, see the callout in Step 11 about registering them through registerUserChannels() rather than inline here. If you store user data, add the encryption options from Step 17 to the same createFlux() call.
These engines are the minimal, public data versions. If your app has scope: 'user' channels or queues user writes offline, add the encryption and integrity options shown in Step 17 to the same createFlux() call, and build the key route in Step 18.
Wrap your app
The hydrate → bootstrap sequence
ensureClusterBootOnce().flux.bootstrap() only hydrates IndexedDB over a plain HTTP call. It never touches the realtime connection. Until ensureClusterBootOnce() runs, the realtime manager sits inert: channels are registered and the cache is full, but no leader tab is elected and no realtime channel is opened. Live push never fires, and neither does the catch up sync after a reconnect, with no error. With several tabs open, Flux elects one leader to hold the connection and fans updates out to the rest, so booting the cluster is also what avoids one connection per tab. This applies to every adapter: Supabase, Socket.io, SSE and WebSocket alike. Call it after hydrate() for global data, or after a confirmed successful bootstrap for user scoped data, as shown below.
Your bootstrap API route (Node / Express)
null, {} or [] when there is nothing yet, so "no data yet" is cached as a correct offline state instead of a permanently missing partition.Dynamic detail pages that work offline (optional)
isSpa from Step 5 actually forks behavior. Pick whichever matches your setup:With isSpa at its default of true, the dynamicRoutePrefixes entry from Step 5 already covers every subpath under /dashboard/items/: /dashboard/items/42, /dashboard/items/42/settings, anything. A hard miss on any of them serves the same cached index.html, and React Router or TanStack Router reads the real path from window.location and mounts the matching component, which then hydrates from IDB exactly like BlogSlugPage above. There is no shell document to configure per subpath because there is only ever the one document.
Your offline fallback page
precacheRoutes and offlineShell in your fluxVitePlugin() config (Step 5).Offline ready static images (optional)
flux.register(), use CachedImg to store them in Flux's image IndexedDB cache.Sync your own writes instantly (dispatchLocalUpdate)
flux.dispatchLocalUpdate(channel, data, options?) closes that gap: once your own mutation is confirmed, hand the result straight to Flux and it goes through the exact same intake gate as bootstrap and realtime data. The store's setState(), the scope aware IDB write (encrypted for user scope when Step 17 is on), the generation barrier, and the cross tab mirror all apply exactly as they do for server originated data.dispatchLocalUpdate(channel: string, data: any, options?: { persist?: boolean; broadcast?: boolean }). persist (default true) controls whether the write lands in IDB, and broadcast (default true) controls whether it is mirrored to other open tabs. Only call this after your write is confirmed by the server. It is a confirmed write dispatch, not an optimistic one, so it should never carry unsaved local state.
The store: same setState() contract as any other channel
Register the channel, like any other
scope: 'user' channel, put it inside your registerUserChannels() function from Step 11 rather than at module top level. Otherwise it falls into the same "empty after first logout" gap described there.Wrap the save: write, confirm, then dispatch
src/lib/flux.ts next to your other registrations. It is the one place that legitimately knows about both the engine and the store, so the store itself stays a plain store like every other example on this page:Call it from your form
preferencesAdapter for any registered adapter (Redux, Jotai, or Stunk) and the save action for whatever your own mutation is. See each adapter's own page under State Managers for the equivalent local write wiring. If the write fails, skip the dispatch entirely and let your existing error handling surface it. There is nothing confirmed yet to push into Flux.Deleting: dispatchLocalDelete for LRU detail entries
flux.dispatchLocalDelete(channel, id) removes it from IDB and from this tab, and signals every other open tab to drop it too. Skip it and a deleted item's detail page keeps rendering from cache.Encrypt user data at rest
encryption block to createFlux() and Flux seals that data with AES GCM before it touches disk. The key never lives in your code: Flux fetches a per user secret from your own backend through a key provider, unwraps (or creates) a random data key for that user, and keeps the unlocked key on the device for as long as the idle window allows.| Data | Scope | What is on disk |
|---|---|---|
| Cache entries (bootstrap, realtime, dispatchLocalUpdate) | 'user' | Ciphertext (AES GCM), bound to its key, timestamp and TTL |
| Cache entries | 'global' | Readable data plus a checksum. Detects edits and corruption, but is not a security boundary. |
| Queued offline writes | 'user' | Readable header (id, store, user, status, revision, timestamp) and an encrypted body (payload, endpoint, method, failure record) |
| Queued offline writes | 'global' | Readable body plus a checksum. userId is null. |
| Cached images | either | Not encrypted. Images from a user channel carry an owner id, are hidden from other users and swept at logout. |
The queue header stays readable on purpose, so your app can say "3 unsent changes" while the user's key is locked, and so replay can filter by user before decrypting anything. Every header field is also bound into the encryption tag, so editing status, revision or userId in DevTools makes the record fail verification instead of changing its behavior.
The first time a user unlocks on a device, Flux must call your key route. After that, the unlocked key is stored on the device (as a non extractable key) until the idle window passes or the user signs out, so offline cold starts keep working. A device that signs in for the first time while offline stays locked, and onLocked fires with offline-needs-login. While locked, queued user writes are refused with FluxLockedError instead of being stored as plaintext. See Step 19.
Encryption at rest protects data on a shared or lost device and from casual inspection in DevTools. It does not protect against script running on your own origin (an XSS bug can use the unlocked key), and whoever holds your FLUX_KEY_MASTERS can derive any user's key. If you need a design where your server can never derive a key, use the passphrase provider described in guides/encryption_key_route.
The key route and its environment variables
verifyAuthHeader helper as your user bootstrap route. For Hono, Workers, cookie sessions or other backends see guides/encryption_key_route.Authorization header, that your other API routes use..env and to your host's environment settings for every environment that serves the API, then restart the server (Node only reads the file at startup) and redeploy:Never prefix these variables with VITE_. Vite inlines every VITE_ variable into the browser bundle, which would ship the master to every visitor. Use a different master for development and production, keep a copy in a password manager or secrets vault (not in the repo), and remember that losing the master makes every user's encrypted offline data and queued writes unrecoverable.
FLUX_KEY_CURRENT at it, and keep the old one:Sign in and watch the network tab for one POST /api/flux/key answering 200. If it answers 500 with server-misconfigured, the server logs the reason: almost always a malformed FLUX_KEY_MASTERS (stray quotes, line breaks, invalid JSON) or a FLUX_KEY_CURRENT that names a version that is not in the object. A 401 means the Authorization header did not reach the route or the token was not accepted.
Queued writes: global queues and user queues
addQueueEntrySafe(): the scope and the userId. Get them right and Flux encrypts user writes and replays each kind at the right time. Get them wrong and the write is stored as a global record, which a signed in user's replay will never pick up.| Global queue | User queue | |
|---|---|---|
| Typical use | Public contact form, waitlist, anything with no signed in user | Support messages, settings, project edits, anything tied to an account |
| Write call | addQueueEntrySafe(entry, prefix, …, 'global', null) | addQueueEntrySafe(entry, prefix, …, 'user', userId) |
| Registration | scope: 'global' | scope: 'user' |
| On disk | Readable body plus checksum, userId null | Encrypted body, readable header with the user id |
| Replay filter | userId: null | userId: '<uuid>' |
| Needs sign in to replay | No | Yes, and an unlocked key |
| Locked key | Not applicable | Write refused with FluxLockedError |
| Dedupe scope | Global entries only | That user's entries only |
Resolving the user without the network
Writing a user queue entry
Writing a global queue entry
Register each queue with the matching scope
Replaying by hand: the filter decides what is sent
flux.replay(channel) picks the filter from the channel's registered scope, so the registration above is all it needs. If you call replayQueue() directly, you choose the filter yourself:Counters and cross tab sync
Some older examples posted { type: 'QUEUE_CLEARED' } after a successful replay so other tabs would flip a "queued" badge. Other tabs answer that message by clearing the entire IndexedDB queue and every localStorage key that starts with your storage prefix. That wipes every other queue, user and global, and the message cannot be filtered to one store. Flux already removes each entry as it succeeds and notifies other tabs by itself.
Logout, locked data and tamper detection
flux.clearUserSession() clears the user's cache but keeps their queued writes sealed on disk, and they replay at that user's next sign in. A user on a public computer can choose the opposite with clearUserSession({ discardQueue: true }), which also wipes the queue and destroys the key.signOutAndDiscardUnsent() before your auth sign out). Show getUnsentChangeCount() so the user knows what is waiting.| Situation | What Flux does |
|---|---|
| Signed out user's sealed writes | Stay on disk. Replayed at that user's next sign in. |
| Sealed writes of a user who never returns | Deleted after queueRetentionMs (default 30 days). |
| Another user signs in on the same device | Cannot read the first user's sealed writes and never replays them. |
| Sealed under a key that has since been replaced | Removed silently. It can never be opened and is not a tamper alarm. |
| Stored write or cache entry edited outside the app | Fails verification and is removed (or quarantined, per integrity.queueTamperAction). Reported to your integrity listener. |
| Memory only writes (every storage layer unavailable) | Plain, and lost on refresh. Rare, and reported through onStorageFallback. |
Telling the user when something was tampered with
Sign in and confirm one key request answering 200. Go offline and queue a user write, then check IndexedDB: the record should show your user id and an enc field, not body and sum. Sign out, sign in again, and it should replay. Then edit a cached value in DevTools and refocus the tab: the modal should appear.
If you have no data to sync, such as a marketing page, a static docs page, or anything with no register() calls, you do not need Steps 8 through 20 at all. Skip the engine, the adapter, the realtime cluster, the store, and the encryption setup entirely. You still need Steps 1 to 6 (install, precache routes, config, manifest). If the page has static images, add Step 15 too. All you need is:
Add every route you want available offline to precacheRoutes, plus your offline shell page from Step 14. The service worker generated by fluxVitePlugin() precaches these at build time regardless of whether createFlux() is called.
Every adapter shown here (Supabase, Socket.io, SSE, WebSocket, polling) and every state manager (Zustand, Redux, Jotai, Stunk) are interchangeable independently of each other and of the framework. Nothing in @tsworldtech/flux's core engine knows whether it is running inside Next.js, a plain Vite build, or Remix.