Next.js Flux Guide
This Flux guide takes your Next.js app to a fully offline capable experience. You get a single bootstrap call, realtime sync, protected user data, and a clear split between global and per user offline queues.
- An existing Next.js 13+ App Router project.
- (Optional)A backend you can subscribe to, such as 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 server side session you can read in a route handler, so the key route knows who is asking.
Install the core package
Install the Next.js integration
withFlux() (the next.config wrapper that generates and injects your service worker), FluxProvider, HydrationGate, ServiceWorkerRegistrar, and the useFlux() and useFluxTime() hooks.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 withFlux() in next.config
dynamicRoutePrefixes tells the service worker which URL prefixes are dynamic detail routes at all. dynamicRouteShapes tells it exactly which subpaths under each of those prefixes need their own offline navigable shell document. dynamicRouteIdbKeys tells it where to look to decide whether it actually has data for a given route. A single page dynamic route only needs a prefix with one empty string subpath. A dynamic route with tabs (settings, activity and so on) needs one subpath entry per tab.When a dynamic route can't be reached, the service worker only serves its cached shell if it also finds data for that slug, otherwise the user would land on an empty page. With dynamicRouteIdbKeys set, the check is two cheap steps: an exact key lookup on the detail channel ({scope}:{idbKey}:{slug}), then, only if that misses, a single read of the list channel, matching the URL slug against each field in listFields. The list fallback is what makes public slugs work when the detail entry is keyed by a different id. Without an entry, every offline navigation to that prefix falls back to a full scan of IndexedDB.
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. The Flux 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 (including arrays, delta objects, sparse updates, and deletions) 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
window so hot reloads and duplicate imports never create a second one. This file also exports ensureClusterBootOnce(), which starts the realtime layer. Step 11 shows where to call it.This engine is the minimal, public data version. 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 then bootstrap sequence
ensureClusterBootOnce().flux.bootstrap() only hydrates IndexedDB over a plain HTTP call and 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
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 routes that work offline
ingestionType: 'LRU' so unvisited detail pages can still hydrate from IDB, plus fluxDynamicRoute handling the build time static params:idbGet() on mount. See core_concepts/idb_ttl and ingestion/lru for the full pattern. The idbKey of that LRU channel (and of the list channel, if you have one) is what you give dynamicRouteIdbKeys in Step 5, so the service worker can tell whether it has data for the route while offline.dynamicRouteShapes in Step 5 was configuring.A detail route could have any number of real slugs. Precaching every one at build time isn't possible for user generated content, and precaching none of them means an item the user never visited online can't render offline at all. The sentinel slug (__flux_shell__) is a real, static page Next.js CAN build and the SW CAN precache. When a real slug 404s from both the network and the page cache while offline, the SW serves the sentinel's cached HTML back with the real slug rewritten in, and the client view then hydrates the actual data for that slug from IDB, the same way any LRU detail page does.
fluxDynamicRoute export from the blog example above goes on every page in the route, including every subpath:dataReady flag your store initializer sets once bootstrap or IDB hydration actually completes. This is what stops a hard refresh from briefly rendering a 404 for an item that genuinely exists but just hasn't hydrated into the store yet:config/precache-routes.ts from Step 4 never needs to list them:Your offline fallback page
precacheRoutes and offlineShell in your withFlux() config (Step 5). Otherwise the service worker has nothing to fall back to when a page is neither cached nor reachable.Offline ready static images (optional)
flux.register(), use CachedImg to store them in the Flux image IDB cache. The first render fetches normally and caches in the background. Every render after that reads straight from IDB via a blob URL, completely independent of whether the image was ever part of a register() payload.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, 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 }). The persist option (default true) controls whether the write lands in IDB, and broadcast (default true) controls whether it's mirrored to other open tabs. Only call this after your write is confirmed by the server. It's 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
Wrap the save: write, confirm, then dispatch
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 and the save action for whatever your own mutation is. If the write fails, skip the dispatch entirely and let your existing error handling surface it, because 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 logs out, so offline cold starts keep working. A device that logs 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
guides/encryption_key_route..env.local and to your host's environment settings for every environment that serves the app, then restart next dev (Next only reads the file at startup) and redeploy:Never prefix these variables with NEXT_PUBLIC_. That would ship the master to every browser. Use a different master for development and production, keep a copy in a 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:Log in and watch the network tab for one POST /api/flux/key answering 200. If it answers 500 with server-misconfigured, the terminal logs the reason. It is 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.
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 an authenticated user's replay will never pick up.| Global queue | User queue | |
|---|---|---|
| Typical use | Public contact form, waitlist, anything with no authenticated 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 + checksum, userId null | Encrypted body, readable header with the user id |
| Replay filter | userId: null | userId: '<uuid>' |
| Needs an authenticated user 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 login. 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 |
|---|---|
| Logged out user's sealed writes | Stay on disk. Replayed at that user's next login. |
| Sealed writes of a user who never returns | Deleted after queueRetentionMs (default 30 days). |
| Another user logs 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 stored data was altered
Log 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. Log out, log 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 don't 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 withFlux() precaches these at build time regardless of whether createFlux() is ever called. The SW level page caching and the data sync engine are independent systems.