Getting Started

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.

Package manager
Language
Prerequisites
  • 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.
1

Install the core package

bash
npm install @tsworldtech/flux
This is the framework agnostic engine: IDB caching, the offline queue, the mutation pipeline, encryption at rest, the license system, job tracking. Every other package below is a thin adapter on top of this one.
2

Install the React integration

bash
npm install @tsworldtech/flux-react
This gives you 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.
3

Choose your realtime adapter

bash
npm install @tsworldtech/flux-supabase

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.

4

Define your precache route manifest

Centralize the offline application shell routes in a dedicated config file. Flux uses this list to warm the service worker cache on first load and guarantee instant offline navigation across your primary UI sections. Keep this file to static, hand picked routes only. Remix's dynamic route shell documents are generated separately, see Step 5 and Step 13.
src/config/precache-routes.ts
1// src/config/precache-routes.ts
2//
3// Static, hand picked routes only. If you are on Remix with dynamicRouteShapes
4// configured (see Step 5), the __flux_shell__ sentinel URLs it produces are
5// NOT listed here. They are derived automatically and folded into the SW's
6// precache list, so do not add them to this file by hand.
7export const PRECACHE_ROUTES = [
8 '/',
9 '/docs',
10 '/docs/getting-started',
11 '/dashboard',
12 '/dashboard/analytics',
13 '/dashboard/settings',
14 '/offline',
15] as const;
5

Configure the Vite plugin

vite.config.ts
1// vite.config.ts
2import { defineConfig } from 'vite'
3import react from '@vitejs/plugin-react'
4import { fluxVitePlugin } from '@tsworldtech/flux-react/plugin'
5import { PRECACHE_ROUTES } from './src/config/precache-routes'
6
7export default defineConfig({
8 plugins: [
9 react(),
10
11 // Reads dist/.vite/manifest.json in closeBundle and bakes the SW
12 // template with your build's actual chunk hashes.
13 fluxVitePlugin({
14 // Routes to precache into the service worker on first load
15 precacheRoutes: [...PRECACHE_ROUTES],
16
17 // The fallback route when a page is neither cached nor reachable
18 offlineShell: '/offline',
19
20 // Namespaces every IDB store and SW cache this app creates.
21 // Must match the storagePrefix you pass to createFlux().
22 storagePrefix: 'my_react_app',
23
24 // Names for the SW's background sync tags used by the queue
25 syncTags: ['flux:sync:default'],
26
27 // Dynamic route offline coverage
28 // dynamicRoutePrefixes: which URL prefixes are dynamic detail routes
29 // at all. When a hard navigation under one of these prefixes misses
30 // both the page cache and the network, the SW falls back instead of
31 // going straight to the offline error page.
32 dynamicRoutePrefixes: ['/dashboard/items/'],
33
34 // isSpa: not set here on purpose. It defaults to true for this
35 // package, and fluxVitePlugin auto detects Remix (a '@remix-run/*'
36 // dependency in package.json) and flips the default to false for
37 // you, logging a line confirming it. You only need to set this
38 // by hand if you are running Remix's own SPA mode
39 // (unstable_ssr: false), which cannot be detected from package.json.
40 // See the callout below and the Remix example after this block.
41
42 // dynamicRouteShapes and dynamicRouteIdbKeys: intentionally absent
43 // here. In plain Vite or CRA there is exactly one HTML document for
44 // every route, so there is nothing distinct to precache per subpath,
45 // and the SW serves that one document without checking IDB.
46 // dynamicRoutePrefixes alone already covers every subpath under a
47 // dynamic route. See the callout below and Step 13.
48
49 // Route prefixes that bypass the service worker completely (auth callbacks, webhooks)
50 bypassRoutePrefixes: ['/auth/callback'],
51 }),
52 ],
53 server: {
54 port: 5173,
55 },
56})
Unlike 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.
isSpa, dynamicRouteShapes and dynamicRouteIdbKeys: what actually changes between Vite or CRA and Remix

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.

On Remix, the config looks the same shape as above with three additions:
vite.config.ts (Remix)
1// vite.config.ts: Remix app, auto detected as isSpa: false
2import { defineConfig } from 'vite'
3import { vitePlugin as remix } from '@remix-run/dev'
4import { fluxVitePlugin } from '@tsworldtech/flux-react/plugin'
5import { PRECACHE_ROUTES } from './app/config/precache-routes'
6
7export default defineConfig({
8 plugins: [
9 remix(),
10
11 fluxVitePlugin({
12 precacheRoutes: [...PRECACHE_ROUTES],
13 offlineShell: '/offline',
14 storagePrefix: 'my_remix_app',
15 syncTags: ['flux:sync:default'],
16
17 // isSpa is left unset on purpose. fluxVitePlugin finds the
18 // '@remix-run/dev' dependency in package.json and defaults isSpa to
19 // false for you. Pass isSpa: true explicitly only if this app runs
20 // Remix's own SPA mode (unstable_ssr: false).
21
22 // Same meaning as the plain Vite case: which URL prefixes are
23 // dynamic detail routes at all.
24 dynamicRoutePrefixes: ['/items/'],
25
26 // Now meaningful, because isSpa resolved to false: Remix renders a
27 // real, distinct document per route, so this detail route gets its
28 // own precached shell instead of falling back to a generic one.
29 // subpaths: [''] means just the bare detail page. See Step 13 for
30 // a route with tabs or subpages.
31 dynamicRouteShapes: [
32 {
33 prefix: '/items/',
34 subpaths: [''],
35 },
36 ],
37
38 // Route prefix to where the SW looks to decide "do we have data for
39 // this route offline?". Only used when isSpa is false: the SW only
40 // serves a cached shell if it also finds data for that slug,
41 // otherwise the user would land on an empty page. Without this the
42 // check falls back to a slow full scan of IndexedDB. Keys must match
43 // dynamicRoutePrefixes exactly (trailing slash included).
44 //
45 // idbKey: the idbKey of the per item detail (LRU) channel you
46 // pass to flux.register(). Tried first, as an exact
47 // key get: '{scope}:{idbKey}:{slug}'.
48 // listKey: the idbKey of the whole list channel. Fallback used
49 // when the URL slug is not the key the detail entry is
50 // stored under. One get on the list, then an
51 // in memory match.
52 // listFields: item fields compared against the URL slug.
53 //
54 // These strings must match your flux.register() idbKey values
55 // exactly. A plain string ('/items/': 'item_detail') also works
56 // when the slug is always the detail key.
57 dynamicRouteIdbKeys: {
58 '/items/': {
59 idbKey: 'item_detail',
60 listKey: 'items:list',
61 listFields: ['slug', 'id'],
62 },
63 },
64
65 bypassRoutePrefixes: ['/auth/callback'],
66 }),
67 ],
68})
Keep these strings in sync with flux.register()

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.

6

Add your manifest.json

Place this file at 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.
public/manifest.json
1{
2 "name": "Flux React App",
3 "short_name": "FluxApp",
4 "description": "Offline first realtime web application.",
5 "start_url": "/",
6 "display": "standalone",
7 "background_color": "#0B1519",
8 "theme_color": "#156A80",
9 "icons": [
10 { "src": "/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" },
11 { "src": "/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" }
12 ]
13}
7

Define your types (TypeScript only)

Optional, but recommended: keep your registered data shapes in one place per store, imported by both your state manager file (Step 8) and your engine file (Step 9) rather than declared inline in either. JavaScript users can skip straight to Step 8.
src/types/flux.ts
1// src/types/flux.ts
2export interface DashboardMetric {
3 id: string
4 label: string
5 value: string
6 status: 'operational' | 'syncing' | 'offline'
7}
8

Create your state store

The one non negotiable contract, regardless of which state manager you pick: whatever you pass as 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

src/store/dashboardStore.ts
1// src/store/dashboardStore.ts
2import { create } from 'zustand'
3import type { DashboardMetric } from '../types/flux'
4
5interface DashboardStore {
6 metrics: DashboardMetric[]
7 isHydrated: boolean
8 setState: (data: any) => void
9}
10
11export const useDashboardStore = create<DashboardStore>((set, get) => ({
12 metrics: [],
13 isHydrated: false,
14 setState: (data: any) => {
15 if (!data) return
16
17 // 1. Array payload: bootstrap, IDB hydration, or full sync
18 if (Array.isArray(data)) {
19 set({ metrics: [...data], isHydrated: true })
20 return
21 }
22
23 // 2. Object payload: single delta frame from the live stream
24 if (typeof data === 'object') {
25 const current = get().metrics
26
27 // DELETE
28 if (data.op === 'DELETE' || data.eventType === 'DELETE') {
29 const id = String(data.id ?? data._id ?? data.data?.id ?? '')
30 if (id) set({ metrics: current.filter((m) => m.id !== id) })
31 return
32 }
33
34 const rawRecord = data.data ?? data.new ?? data
35 const recordId = String(rawRecord?.id ?? rawRecord?._id ?? data.id ?? '')
36
37 if (!recordId) return
38
39 const idx = current.findIndex((m) => m.id === recordId)
40 if (idx !== -1) {
41 // Sparse UPDATE: shallow merge onto the existing record
42 const next = [...current]
43 next[idx] = { ...next[idx], ...rawRecord, id: recordId }
44 set({ metrics: next, isHydrated: true })
45 } else {
46 // CREATE: prepend the new record
47 set({
48 metrics: [{ id: recordId, ...rawRecord }, ...current],
49 isHydrated: true,
50 })
51 }
52 }
53 },
54}))

Redux Toolkit

src/store/itemsSlice.ts
1// src/store/itemsSlice.ts
2import { createSlice, type PayloadAction } from '@reduxjs/toolkit'
3
4export interface Item {
5 id: string
6 name: string
7 description: string
8 status: string
9 price: number
10 createdAt: string
11 updatedAt: string
12}
13
14interface ItemsState {
15 list: Item[]
16}
17
18const initialState: ItemsState = { list: [] }
19
20const itemsSlice = createSlice({
21 name: 'items',
22 initialState,
23 reducers: {
24 setItems(state, action: PayloadAction<Item[]>) {
25 state.list = Array.isArray(action.payload) ? action.payload : []
26 },
27 addOptimisticItem(state, action: PayloadAction<Item>) {
28 state.list.unshift(action.payload)
29 },
30 upsertItem(state, action: PayloadAction<Item>) {
31 const incoming = action.payload
32 const optimisticIdx = state.list.findIndex(
33 (item) =>
34 item.status === 'optimistic_pending' &&
35 item.name === incoming.name
36 )
37 if (optimisticIdx !== -1) {
38 state.list[optimisticIdx] = incoming
39 return
40 }
41 const existingIdx = state.list.findIndex((item) => item.id === incoming.id)
42 if (existingIdx !== -1) {
43 state.list[existingIdx] = { ...state.list[existingIdx], ...incoming }
44 return
45 }
46 state.list.unshift(incoming)
47 },
48 removeItem(state, action: PayloadAction<string>) {
49 state.list = state.list.filter((item) => item.id !== action.payload)
50 },
51 },
52})
53
54export const { setItems, addOptimisticItem, upsertItem, removeItem } = itemsSlice.actions
55export default itemsSlice.reducer
src/store/reduxStore.ts
1// src/store/reduxStore.ts
2import { configureStore } from '@reduxjs/toolkit'
3import itemsReducer from './itemsSlice'
4
5export const reduxStore = configureStore({
6 reducer: {
7 items: itemsReducer,
8 },
9})
10
11export type RootState = ReturnType<typeof reduxStore.getState>
12export type AppDispatch = typeof reduxStore.dispatch
Redux needs an adapter to handle single live delta frames, sparse merges, and optimistic placeholder resolution:
src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): bridging Redux into Flux
2import { reduxStore } from '../store/reduxStore'
3import { setItems, upsertItem, removeItem, type Item } from '../store/itemsSlice'
4
5export const itemsAdapter = {
6 getState: () => reduxStore.getState().items.list,
7 setState: (data: any) => {
8 if (!data) return
9
10 if (Array.isArray(data)) {
11 const current = reduxStore.getState().items.list
12 const hasOptimistic = current.some((i) => i.status === 'optimistic_pending')
13
14 if (hasOptimistic) {
15 const resolved = data.map((item) => {
16 if (item.status !== 'optimistic_pending') return item
17 const confirmed = data.find(
18 (i) => i.status !== 'optimistic_pending' && i.name === item.name
19 )
20 return confirmed ? null : item
21 }).filter(Boolean) as Item[]
22
23 reduxStore.dispatch(setItems(resolved))
24 return
25 }
26
27 reduxStore.dispatch(setItems(data))
28 return
29 }
30
31 if (typeof data === 'object') {
32 if (data.op === 'DELETE' || data.eventType === 'DELETE') {
33 const idToRemove = String(data.id ?? data._id ?? data.data?.id ?? '')
34 if (idToRemove) reduxStore.dispatch(removeItem(idToRemove))
35 return
36 }
37
38 const rawRecord = data.data ?? data.new ?? data
39 const recordId = String(rawRecord?.id ?? rawRecord?._id ?? data.id ?? '')
40
41 if (recordId) {
42 const normalizedItem = { id: recordId, ...rawRecord } as Item
43 reduxStore.dispatch(upsertItem(normalizedItem))
44 }
45 }
46 },
47};

Jotai

src/store/notificationsAtom.ts
1// src/store/notificationsAtom.ts
2import { atom, createStore } from 'jotai'
3
4export interface Notification {
5 id: string
6 title: string
7 message: string
8 type: string
9 read: boolean
10 createdAt: string
11}
12
13export const notificationsAtom = atom<Notification[]>([])
14export const jotaiStore = createStore()
Jotai atoms require a standalone createStore() since Flux dispatches outside of the React render tree:
src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): bridging Jotai into Flux
2import { notificationsAtom, jotaiStore, type Notification } from '../store/notificationsAtom'
3
4export const notificationsAdapter = {
5 getState: () => jotaiStore.get(notificationsAtom),
6 setState: (data: any) => {
7 if (!data) return
8
9 if (Array.isArray(data)) {
10 jotaiStore.set(notificationsAtom, data as Notification[])
11 return
12 }
13
14 if (typeof data === 'object') {
15 if (data.op === 'DELETE' || data.eventType === 'DELETE') {
16 const idToRemove = String(data.id ?? data._id ?? data.data?.id ?? '')
17 if (idToRemove) {
18 const current = jotaiStore.get(notificationsAtom)
19 jotaiStore.set(notificationsAtom, current.filter((n) => n.id !== idToRemove))
20 }
21 return
22 }
23
24 const rawRecord = data.data ?? data.new ?? data
25 const recordId = String(rawRecord?.id ?? rawRecord?._id ?? data.id ?? '')
26 if (!recordId) return
27
28 const current = jotaiStore.get(notificationsAtom)
29 const existingIdx = current.findIndex((n) => n.id === recordId)
30
31 if (existingIdx !== -1) {
32 const merged = [...current]
33 merged[existingIdx] = { ...merged[existingIdx], ...rawRecord, id: recordId }
34 jotaiStore.set(notificationsAtom, merged)
35 } else {
36 const normalized = { id: recordId, ...rawRecord } as Notification
37 jotaiStore.set(notificationsAtom, [normalized, ...current])
38 }
39 }
40 },
41};

Stunk

src/store/itemsChunk.ts
1// src/store/itemsChunk.ts
2import { chunk } from 'stunk'
3
4export interface Item {
5 id: string
6 name: string
7 description: string
8 status: string
9 price: number
10}
11
12export const itemsChunk = chunk<Item[]>([])
src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): bridging Stunk into Flux
2import { createStunkStoreAdapter } from '@tsworldtech/flux'
3import { itemsChunk } from '../store/itemsChunk'
4
5export const itemsAdapter = createStunkStoreAdapter(itemsChunk)
9

Create the Flux engine singleton

Vite modules only execute once per page load, so createFlux naturally acts as a singleton without dev singleton guards. Every tab below also exports ensureClusterBootOnce(), which starts the realtime layer, and Step 11 shows where to call it.
bash
// src/lib/flux.ts
import { createFlux } from '@tsworldtech/flux'
import { createSupabaseAdapter } from '@tsworldtech/flux-supabase'
import { supabase } from './supabase-client'
import { useDashboardStore } from '../store/dashboardStore'
export const flux = createFlux({
adapter: createSupabaseAdapter(supabase),
storagePrefix: 'my_react_app',
ttl: {
short: 1000 * 60 * 5, // 5 minutes
medium: 1000 * 60 * 60, // 1 hour
long: 1000 * 60 * 60 * 24, // 24 hours
},
onStorageFallback: (layer, reason) => {
console.warn('[flux] Storage degraded to', layer, ':', reason)
},
})
// Starts leader election across open tabs and activates the realtime
// connection. Without it the engine is registered and IDB is populated,
// but the realtime manager stays inert: no leader is elected, no channel
// is opened, so live push AND the catch up sync after a reconnect never
// fire. Guarded by a window flag so any number of callers trigger it
// only once per tab. Call it from your store initializer, see Step 11.
const CLUSTER_BOOT_KEY = '__flux_cluster_booted__'
declare global {
interface Window {
__flux_cluster_booted__?: boolean
}
}
export function ensureClusterBootOnce(): void {
if (typeof window === 'undefined') return
if (window[CLUSTER_BOOT_KEY]) return
window[CLUSTER_BOOT_KEY] = true
flux.realtime.ensureClusterBoot()
}
export const dashboardStoreAdapter = {
setState: (data: any) => useDashboardStore.getState().setState(data),
getState: () => useDashboardStore.getState().metrics,
}
flux.register({
channel: 'dashboard_metrics',
table: 'dashboard_metrics',
idbKey: 'dashboard_metrics:latest',
ttl: 'long',
ingestionType: 'COLLECTION_ALL',
diffBeforeUpdate: true,
event: 'UPDATE',
scope: 'global',
store: dashboardStoreAdapter,
})

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.

Storing user data? Add encryption to this 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.

10

Wrap your app

src/components/FluxClientWrapper.tsx
1// src/components/FluxClientWrapper.tsx
2import React from 'react'
3import { FluxProvider, HydrationGate, OfflineIndicator } from '@tsworldtech/flux-react'
4import { flux } from '../lib/flux'
5import { PRECACHE_ROUTES } from '../config/precache-routes'
6import { FluxStoreInitializer } from './storeInitializer'
7
8export function FluxClientWrapper({ children }: { children: React.ReactNode }) {
9 return (
10 <FluxProvider engine={flux} precacheRoutes={PRECACHE_ROUTES}>
11 <FluxStoreInitializer />
12 <HydrationGate>
13 {children}
14 </HydrationGate>
15 <OfflineIndicator />
16 </FluxProvider>
17 )
18}
11

The hydrate → bootstrap sequence

Configure the client side store initializer. Use the Global tab for public data that persists across user sessions, or the User (Auth Aware) tab for multi tenant state isolated per user account. Both end by starting the realtime cluster with ensureClusterBootOnce().
Don't forget 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.

src/components/storeInitializer.tsx
1// src/components/storeInitializer.tsx (Global Scope)
2import { useEffect } from 'react'
3import { flux, dashboardStoreAdapter, ensureClusterBootOnce } from '../lib/flux'
4import { useDashboardStore } from '../store/dashboardStore'
5
6export function FluxStoreInitializer() {
7 useEffect(() => {
8 if (typeof window === 'undefined') return
9
10 const SESSION_KEY = 'flux_bootstrap_executed_session'
11
12 async function init() {
13 try {
14 // Step 1: always hydrate first from local IndexedDB (2000ms max timeout)
15 await flux.hydrate()
16
17 // Step 2: start leader election and realtime. The data is public,
18 // so there is nothing to wait for. Boot right after hydrate and
19 // BEFORE the early return below, so a tab that skips bootstrap
20 // (already seeded this session) still gets live updates.
21 ensureClusterBootOnce()
22
23 const isEmpty = useDashboardStore.getState().metrics.length === 0
24 if (isEmpty) sessionStorage.removeItem(SESSION_KEY)
25
26 if (!isEmpty && sessionStorage.getItem(SESSION_KEY) === 'true') {
27 return // already bootstrapped this session, disk is warm
28 }
29 sessionStorage.setItem(SESSION_KEY, 'true')
30
31 // Step 3: single network seed call for public app data
32 await flux.bootstrap({
33 endpoint: 'http://localhost:3001/api/bootstrap/public',
34 cooldownMs: 30_000,
35 scope: 'global',
36 map: {
37 dashboard_metrics: dashboardStoreAdapter,
38 },
39 })
40 } catch (err) {
41 console.warn('[FluxStoreInitializer] Failed:', err)
42 sessionStorage.removeItem(SESSION_KEY)
43 }
44 }
45
46 init()
47 }, [])
48
49 return null
50}
12

Your bootstrap API route (Node / Express)

The single backend endpoint that replaces fragmented network fetches on initial app load. Always return 200 HTTP responses with partial payloads when non critical query errors occur to allow Flux to ingest available data offline. Every registered channel's key should always be present in the payload, as null, {} or [] when there is nothing yet, so "no data yet" is cached as a correct offline state instead of a permanently missing partition.
server/routes/bootstrapPublic.ts
1// server/routes/bootstrapPublic.ts
2import express, { Router, Request, Response } from 'express'
3import Metric from '../models/Metric'
4
5const router: Router = express.Router()
6
7// GET /api/bootstrap/public
8router.get('/', async (req: Request, res: Response) => {
9 try {
10 const metrics = await Metric.find({})
11
12 res.json({
13 ok: true,
14 data: {
15 dashboard_metrics: metrics.map((m) => ({ ...m.toObject(), id: m._id.toString() })),
16 },
17 assets: [],
18 })
19 } catch (err: any) {
20 res.status(500).json({ ok: false, error: err.message })
21 }
22})
23
24export default router
server/server.ts
1// server/server.ts (excerpt)
2import bootstrapPublicRoute from './routes/bootstrapPublic'
3import bootstrapUserRoute from './routes/bootstrapUser'
4import fluxKeyRoute from './routes/fluxKey' // Step 18, only if you encrypt user data
5
6app.use('/api/bootstrap/public', bootstrapPublicRoute)
7app.use('/api/bootstrap/user', bootstrapUserRoute)
8app.use('/api/flux/key', fluxKeyRoute)
13

Dynamic detail pages that work offline (optional)

Only needed if you registered an LRU ingested channel (for example blog posts or product detail pages) and want an unvisited slug to still render offline after the one bootstrap call seeded it.
src/store/blogStore.ts
1// src/store/blogStore.ts
2import { create } from 'zustand'
3
4export interface BlogPost {
5 id: string
6 slug: string
7 title: string
8 excerpt: string
9 author: string
10 body: any[]
11}
12
13export type BlogCard = Omit<BlogPost, 'body'>
14
15interface BlogListStore {
16 posts: BlogCard[]
17 isHydrated: boolean
18 setState: (data: any) => void
19}
20
21export const useBlogListStore = create<BlogListStore>((set, get) => ({
22 posts: [],
23 isHydrated: false,
24 setState: (data: any) => {
25 if (!data) return
26 const incoming = Array.isArray(data) ? data : get().posts
27 set({ posts: incoming, isHydrated: true })
28 },
29}))
30
31interface BlogDetailStore {
32 activePost: BlogPost | null
33 isHydrated: boolean
34 setHydrated: () => void
35 setState: (data: any) => void
36}
37
38export const useBlogDetailStore = create<BlogDetailStore>((set) => ({
39 activePost: null,
40 isHydrated: false,
41 setHydrated: () => set({ isHydrated: true }),
42 setState: (data: any) => {
43 const post: BlogPost | null =
44 data && typeof data === 'object' && !Array.isArray(data) ? data : null
45 set({ activePost: post, isHydrated: true })
46 },
47}))
src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): registering the list and detail channels
2import { useBlogListStore, useBlogDetailStore } from '../store/blogStore'
3
4export const blogListStoreAdapter = {
5 setState: (data: any) => useBlogListStore.getState().setState(data),
6 getState: () => useBlogListStore.getState().posts,
7}
8
9export const blogDetailStoreAdapter = {
10 setState: (data: any) => {
11 if (Array.isArray(data)) return
12 if (data && typeof data === 'object') {
13 useBlogDetailStore.getState().setState(data)
14 }
15 },
16 getState: () => {
17 const active = useBlogDetailStore.getState().activePost
18 return active ? [active] : []
19 },
20}
21
22flux.register({
23 channel: 'blog_posts',
24 table: 'blog_posts',
25 idbKey: 'blog_posts:list',
26 ttl: 'long',
27 ingestionType: 'COLLECTION_ALL',
28 diffBeforeUpdate: true,
29 event: 'UPDATE',
30 store: blogListStoreAdapter,
31})
32
33flux.register({
34 channel: 'blog_post_detail',
35 table: 'blog_posts',
36 idbKey: 'blog_post_detail',
37 ttl: 'long',
38 ingestionType: 'LRU',
39 cacheStrategy: {
40 type: 'LRU',
41 maxBytes: 15 * 1024 * 1024,
42 trackAccessTime: true,
43 },
44 store: blogDetailStoreAdapter,
45 event: 'UPDATE',
46})
src/pages/BlogSlugPage.tsx
1// src/pages/BlogSlugPage.tsx
2import { useEffect } from 'react'
3import { useParams, Link } from 'react-router-dom'
4import { idbGet } from '@tsworldtech/flux'
5import { useBlogDetailStore } from '../store/blogStore'
6
7export default function BlogSlugPage() {
8 const { slug } = useParams<{ slug: string }>()
9
10 const activePost = useBlogDetailStore((s) => s.activePost)
11 const isHydrated = useBlogDetailStore((s) => s.isHydrated)
12
13 useEffect(() => {
14 if (!slug) return
15
16 useBlogDetailStore.setState({ activePost: null, isHydrated: false })
17
18 const idbKey = `blog_post_detail:${slug}`
19 const storagePrefix = 'my_react_app'
20
21 idbGet(idbKey, storagePrefix, true).then((result) => {
22 if (result?.data) {
23 useBlogDetailStore.getState().setState(result.data)
24 } else {
25 useBlogDetailStore.getState().setHydrated()
26 }
27 }).catch(() => {
28 useBlogDetailStore.getState().setHydrated()
29 })
30 }, [slug])
31
32 if (!isHydrated) return <p>Reading from local cache…</p>
33
34 if (!activePost) {
35 return (
36 <div>
37 <p>Post not found. This slug was not in your local cache.</p>
38 <Link to="/blog">← Back to blog</Link>
39 </div>
40 )
41 }
42
43 return (
44 <article>
45 <h1>{activePost.title}</h1>
46 <p>{activePost.excerpt}</p>
47 </article>
48 )
49}
src/main.tsx (excerpt)
1// src/main.tsx (excerpt): wiring the router inside FluxClientWrapper
2import React from 'react'
3import ReactDOM from 'react-dom/client'
4import { createBrowserRouter, RouterProvider } from 'react-router-dom'
5import { FluxClientWrapper } from './components/FluxClientWrapper'
6import BlogPage from './pages/BlogPage'
7import BlogSlugPage from './pages/BlogSlugPage'
8import OfflinePage from './pages/OfflinePage'
9import App from './App'
10import './index.css'
11
12const router = createBrowserRouter([
13 { path: '/', element: <App /> },
14 { path: '/blog', element: <BlogPage /> },
15 { path: '/blog/:slug', element: <BlogSlugPage /> },
16 { path: '/offline', element: <OfflinePage /> },
17])
18
19ReactDOM.createRoot(document.getElementById('root')!).render(
20 <React.StrictMode>
21 <FluxClientWrapper>
22 <RouterProvider router={router} />
23 </FluxClientWrapper>
24 </React.StrictMode>
25)
A detail route with multiple offline navigable subpaths, meaning tabs, nested sections, or anything more than one page under the same dynamic segment, is where isSpa from Step 5 actually forks behavior. Pick whichever matches your setup:
Nothing extra to wire up

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.

14

Your offline fallback page

src/pages/OfflinePage.tsx
1// src/pages/OfflinePage.tsx
2export default function OfflinePage() {
3 return (
4 <div>
5 <h1>You're offline</h1>
6 <p>Previously visited pages are still available. Anything you submit will sync automatically once you reconnect.</p>
7 </div>
8 )
9}
Must be a real route in your router, and must be listed in both precacheRoutes and offlineShell in your fluxVitePlugin() config (Step 5).
15

Offline ready static images (optional)

For static assets not managed through flux.register(), use CachedImg to store them in Flux's image IndexedDB cache.
src/components/Logo.tsx
1// src/components/Logo.tsx
2import { CachedImg } from '@tsworldtech/flux-react'
3
4export function Logo() {
5 return (
6 <CachedImg
7 src="/assets/logo.png"
8 alt="App Logo"
9 className="h-6 w-auto object-contain transition-transform duration-200 group-hover:scale-105"
10 />
11 )
12}
16

Sync your own writes instantly (dispatchLocalUpdate)

Every store so far reacts to data arriving from outside the client: IDB cold boot, bootstrap, or a realtime delta frame. But a locally originated write, such as a form submit, a settings change, or anything the user just did, has to round trip through your backend and then wait for the realtime event to come back before the offline queue, IDB cache, and other open tabs catch up. 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.
Signature

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

src/store/preferencesStore.ts
1// src/store/preferencesStore.ts
2import { create } from 'zustand'
3
4export interface UserPreferences {
5 theme: 'light' | 'dark'
6 locale: string
7 digestFrequency: 'daily' | 'weekly' | 'off'
8}
9
10const defaultPreferences: UserPreferences = {
11 theme: 'light',
12 locale: 'en-US',
13 digestFrequency: 'weekly',
14}
15
16function normalizeRow(row: any, fallback: UserPreferences): UserPreferences {
17 if (!row) return fallback
18 return {
19 theme: row.theme ?? fallback.theme,
20 locale: row.locale ?? fallback.locale,
21 digestFrequency: row.digest_frequency ?? fallback.digestFrequency,
22 }
23}
24
25// The inverse: turns confirmed store state back into a raw row shape
26// before it is handed to dispatchLocalUpdate(). Pure data shape
27// conversion, no Flux dependency, same convention as any other store.
28export function preferencesToRow(prefs: UserPreferences): Record<string, any> {
29 return {
30 theme: prefs.theme,
31 locale: prefs.locale,
32 digest_frequency: prefs.digestFrequency,
33 }
34}
35
36interface PreferencesStore {
37 preferences: UserPreferences
38 original: UserPreferences | null
39 setPreference: <K extends keyof UserPreferences>(key: K, value: UserPreferences[K]) => void
40 isDirty: () => boolean
41 setState: (data: any) => void
42}
43
44export const usePreferencesStore = create<PreferencesStore>((set, get) => ({
45 preferences: { ...defaultPreferences },
46 original: null,
47
48 setPreference: (key, value) => {
49 set((s) => ({ preferences: { ...s.preferences, [key]: value } }))
50 },
51
52 isDirty: () => {
53 const s = get()
54 return s.original ? JSON.stringify(s.preferences) !== JSON.stringify(s.original) : false
55 },
56
57 /* Flux intake gate: SNAPSHOT, scope user
58 Same setState(data) contract every registered store needs. Called
59 on IDB cold boot, on bootstrap, on every realtime delta frame, AND
60 now on a confirmed local write dispatched via dispatchLocalUpdate(). */
61 setState: (data: any) => {
62 if (!data) return
63
64 if (Array.isArray(data)) {
65 if (data.length === 0) return
66 const preferences = normalizeRow(data[0], get().preferences)
67 set({ preferences, original: { ...preferences } })
68 return
69 }
70
71 if (typeof data === 'object') {
72 if (data.op === 'DELETE' || data.eventType === 'DELETE') {
73 set({ preferences: { ...defaultPreferences }, original: null })
74 return
75 }
76
77 const rawRecord = data.data ?? data.new ?? data
78 const preferences = normalizeRow(rawRecord, get().preferences)
79 set({ preferences, original: { ...preferences } })
80 }
81 },
82}))

Register the channel, like any other

src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): register the preferences channel
2import { usePreferencesStore } from '../store/preferencesStore'
3
4export const preferencesAdapter = {
5 setState: (data: any) => usePreferencesStore.getState().setState(data),
6 getState: () => {
7 const preferences = usePreferencesStore.getState().preferences
8 return preferences ? [preferences] : []
9 },
10}
11
12flux.register({
13 channel: 'preferences',
14 idbKey: 'preferences:settings',
15 ttl: 'medium',
16 ingestionType: 'SNAPSHOT',
17 diffBeforeUpdate: true,
18 event: 'UPDATE',
19 scope: 'user',
20 store: preferencesAdapter,
21})
Since this is a 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

Keep this wrapper in 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:
src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): save a local edit, then sync it into Flux
2import { usePreferencesStore, preferencesToRow } from '../store/preferencesStore'
3import { updateUserPreferences } from './actions/preferences' // your own API call
4
5export async function savePreferencesAndSync(): Promise<void> {
6 const before = usePreferencesStore.getState()
7 if (!before.isDirty()) return
8
9 // 1. Do the real write first. Nothing touches Flux until the server
10 // has actually confirmed the mutation. This is not an optimistic
11 // dispatch, it is a confirmed write dispatch.
12 let confirmedRow: any
13 try {
14 confirmedRow = await updateUserPreferences(preferencesToRow(before.preferences))
15 } catch (err) {
16 console.warn('[preferences] Save failed:', err)
17 return
18 }
19
20 // 2. Only now: push the confirmed row through the exact same intake
21 // gate bootstrap and realtime data go through. It updates the
22 // store (via preferencesAdapter and usePreferencesStore's own
23 // setState, same normalizeRow path as everything else), persists
24 // to this user's namespaced IDB key immediately (encrypted when
25 // encryption is on), and mirrors the change to any other open tab
26 // instead of waiting on the realtime UPDATE event to catch up.
27 await flux.dispatchLocalUpdate('preferences', confirmedRow ?? preferencesToRow(before.preferences))
28}

Call it from your form

src/components/PreferencesForm.tsx
1// src/components/PreferencesForm.tsx (excerpt)
2import { usePreferencesStore } from '../store/preferencesStore'
3import { savePreferencesAndSync } from '../lib/flux'
4
5export function PreferencesForm() {
6 const { preferences, setPreference, isDirty } = usePreferencesStore()
7
8 return (
9 <form
10 onSubmit={(e) => {
11 e.preventDefault()
12 savePreferencesAndSync()
13 }}
14 >
15 <select
16 value={preferences.theme}
17 onChange={(e) => setPreference('theme', e.target.value as 'light' | 'dark')}
18 >
19 <option value="light">Light</option>
20 <option value="dark">Dark</option>
21 </select>
22
23 <button type="submit" disabled={!isDirty()}>
24 Save
25 </button>
26 </form>
27 )
28}
The same pattern applies to any channel. Swap 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

A list channel reaches other tabs as a diff patch, so dispatching the new list is enough to remove a row from it. But an LRU detail entry (Step 13) is a separate cached item that is not part of that diff. 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.
src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): confirmed deletion of a record that has an LRU detail entry
2import { useBlogListStore } from '../store/blogStore'
3
4export async function deletePostAndSync(id: string): Promise<{ error: Error | null }> {
5 // 1. Do the real delete first (your own API call).
6 const res = await fetch('/api/posts', {
7 method: 'DELETE',
8 headers: { 'Content-Type': 'application/json' },
9 body: JSON.stringify({ id }),
10 })
11 if (!res.ok) return { error: new Error('Delete failed (' + res.status + ')') }
12
13 // 2. Mirror the new list into the store and IDB. A list channel reaches
14 // other tabs as a diff patch.
15 const remaining = useBlogListStore.getState().posts.filter((p) => p.id !== id)
16 await flux.dispatchLocalUpdate('blog_posts', remaining)
17
18 // 3. The LRU detail entry is a SEPARATE cached item, not part of the
19 // list diff. dispatchLocalDelete removes it from IDB and this tab,
20 // and signals every other open tab to drop it too. Pass the same
21 // id the detail entry is stored under.
22 await flux.dispatchLocalDelete('blog_post_detail', id)
23
24 return { error: null }
25}
17

Encrypt user data at rest

Anything stored for a signed in user, meaning their cached data and their queued offline writes, sits in IndexedDB on a device that may be shared. Add an 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.
src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): turn on encryption at rest
2import { createFlux, createHttpKeyProvider } from '@tsworldtech/flux'
3import { createSupabaseAdapter } from '@tsworldtech/flux-supabase'
4import { supabase } from './supabase-client'
5
6export const flux = createFlux({
7 adapter: createSupabaseAdapter(supabase),
8 storagePrefix: 'my_react_app',
9 ttl: {
10 short: 1000 * 60 * 5,
11 medium: 1000 * 60 * 60,
12 long: 1000 * 60 * 60 * 24,
13 },
14
15 // Encrypts 'user' scoped cache entries and 'user' scoped queued writes.
16 // 'global' scoped data is never encrypted (it carries a checksum only).
17 encryption: {
18 // Asks YOUR backend for the per user secret. See Step 18.
19 keyProvider: createHttpKeyProvider({
20 endpoint: 'http://localhost:3001/api/flux/key',
21
22 // Optional. Runs before every key request. Use it to refresh an
23 // expired session so the key call does not turn into a 401.
24 // prepare: async () => { await refreshMySession() },
25 }),
26
27 // How long an unlocked key stays usable on this device without
28 // being used. Default 7 days. After that the user must sign in
29 // (online) again before the encrypted data opens.
30 sessionKeyIdleMs: 7 * 24 * 60 * 60 * 1000,
31
32 // Sealed queued writes that belong to a user who is NOT signed in
33 // are deleted after this long, so abandoned data does not sit on a
34 // shared machine forever. Default 30 days.
35 queueRetentionMs: 30 * 24 * 60 * 60 * 1000,
36
37 // Accept pre encryption plaintext records once and re seal them.
38 // Set to false one release after every user has upgraded.
39 allowLegacyPlaintext: true,
40
41 // Fires when a user's data cannot be opened right now.
42 // reason: 'offline-needs-login' | 'provider-error' | 'unwrap-failed'
43 onLocked: (userId, reason) => {
44 console.warn('[flux] Secure storage locked for', userId, ':', reason)
45 },
46 },
47
48 // What to do with a stored queued write that fails verification
49 // (edited outside the app). 'delete' removes it, 'quarantine' keeps
50 // a payload less failed row in your failed panel instead.
51 integrity: {
52 queueTamperAction: 'delete',
53 },
54
55 onStorageFallback: (layer, reason) => {
56 console.warn('[flux] Storage degraded to', layer, ':', reason)
57 },
58})
Which data is protected depends on its scope. This is the rule behind every user versus global decision in the next steps:
DataScopeWhat 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 imageseitherNot encrypted. Images from a user channel carry an owner id, are hidden from other users and swept at logout.
What the plaintext header is for

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 unlock on a device needs the network

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.

Know what this protects against

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.

18

The key route and its environment variables

The key route answers one question: "who is this signed in user, and what is their secret?" It authenticates the caller with your normal session, then returns an HMAC derived from a server side master key and the verified user id. Nothing is stored on your server. This is the Node and Express version, using the same verifyAuthHeader helper as your user bootstrap route. For Hono, Workers, cookie sessions or other backends see guides/encryption_key_route.
server/routes/fluxKey.ts
1// server/routes/fluxKey.ts
2//
3// Issues the per user secret Flux uses to unlock encrypted offline data.
4// Auth is your existing bearer token session. The user id comes from the
5// verified token, never from the request body.
6import express, { Router, Request as ExpressRequest, Response as ExpressResponse } from 'express'
7import {
8 createKeyIssuer,
9 createKeyRequestHandler,
10 parseMasters,
11} from '@tsworldtech/flux/server'
12import { verifyAuthHeader } from '../middleware/auth'
13
14const router: Router = express.Router()
15
16let cached: ((req: Request) => Promise<Response>) | null = null
17
18// Built on first request, so the server can boot without the env vars set.
19function getHandler(): ((req: Request) => Promise<Response>) | null {
20 if (cached) return cached
21
22 try {
23 const issuer = createKeyIssuer({
24 masters: parseMasters(process.env.FLUX_KEY_MASTERS),
25 currentKid: process.env.FLUX_KEY_CURRENT ?? '',
26 })
27
28 cached = createKeyRequestHandler({
29 issuer,
30 authenticate: async (request: Request) => {
31 const user = await verifyAuthHeader(request.headers.get('authorization') ?? undefined)
32 if (!user) return null
33 return { userId: user.id }
34 },
35 })
36 return cached
37 } catch (err) {
38 console.error('[flux:key] misconfigured:', (err as Error).message)
39 return null
40 }
41}
42
43// Express to Fetch API bridge. createKeyRequestHandler speaks Request and Response.
44function toWebRequest(req: ExpressRequest): Request {
45 const headers = new Headers()
46 for (const [name, value] of Object.entries(req.headers)) {
47 if (name === 'content-length' || value === undefined) continue
48 if (Array.isArray(value)) value.forEach((v) => headers.append(name, v))
49 else headers.set(name, String(value))
50 }
51
52 const hasBody = req.method !== 'GET' && req.method !== 'HEAD'
53
54 return new Request(`${req.protocol}://${req.get('host')}${req.originalUrl}`, {
55 method: req.method,
56 headers,
57 body: hasBody ? JSON.stringify(req.body ?? {}) : undefined,
58 })
59}
60
61router.all('/', async (req: ExpressRequest, res: ExpressResponse) => {
62 const handler = getHandler()
63 if (!handler) {
64 res.status(500).set('Cache-Control', 'no-store').json({ error: 'server-misconfigured' })
65 return
66 }
67
68 const response = await handler(toWebRequest(req))
69 res.status(response.status)
70 response.headers.forEach((value, name) => res.setHeader(name, value))
71 res.send(await response.text())
72})
73
74export default router
Mount it next to your bootstrap routes (the mount excerpt in Step 12 already includes it). Because your Vite app and your API run on different origins in development, the route also needs the same CORS settings, including the Authorization header, that your other API routes use.
Generate a master key. It is 32 random bytes, base64 encoded:
terminal
1# Generate a master key: 32 random bytes, base64 encoded.
2# Works in PowerShell, bash and zsh. No openssl needed.
3node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
Add both variables to your server's .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:
server/.env
1# server/.env: server only. NEVER expose these to the browser bundle.
2# Do not prefix them with VITE_ and never read them from import.meta.env.
3FLUX_KEY_MASTERS={"k1":"PASTE_THE_BASE64_HERE"}
4FLUX_KEY_CURRENT=k1
Server only. Back it up.

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.

To rotate, add a new version, point FLUX_KEY_CURRENT at it, and keep the old one:
server/.env
1# Rotation: add a new version, point CURRENT at it, KEEP the old one.
2FLUX_KEY_MASTERS={"k1":"OLD_BASE64","k2":"NEW_BASE64"}
3FLUX_KEY_CURRENT=k2
4
5# Each device re wraps its data key at its next unlock.
6# Remove k1 only after the retention and idle windows
7# (30 + 7 days by default) have passed.
Check it works

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.

19

Queued writes: global queues and user queues

Every queued write belongs to exactly one of two kinds, and the kind is decided by two arguments to 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 queueUser queue
Typical usePublic contact form, waitlist, anything with no signed in userSupport messages, settings, project edits, anything tied to an account
Write calladdQueueEntrySafe(entry, prefix, …, 'global', null)addQueueEntrySafe(entry, prefix, …, 'user', userId)
Registrationscope: 'global'scope: 'user'
On diskReadable body plus checksum, userId nullEncrypted body, readable header with the user id
Replay filteruserId: nulluserId: '<uuid>'
Needs sign in to replayNoYes, and an unlocked key
Locked keyNot applicableWrite refused with FluxLockedError
Dedupe scopeGlobal entries onlyThat user's entries only

Resolving the user without the network

src/store/authStore.ts (excerpt)
1// src/store/authStore.ts (excerpt)
2//
3// "Who is acting right now?" for queued writes. It must NEVER make a
4// network round trip, because queued writes happen exactly when the
5// network is missing. Resolution order:
6// 1. the live auth store user (kept while the session is unverified)
7// 2. the locally stored session
8// 3. the last known user namespace Flux renders the cached UI from
9// Returns null only when nobody is signed in.
10export async function getActingUserId(): Promise<string | null> {
11 const s = useAuthStore.getState()
12 if (s.user?.id) return s.user.id
13
14 try {
15 const { data: { session } } = await supabase.auth.getSession()
16 if (session?.user?.id) return session.user.id
17 } catch {
18 // fall through
19 }
20
21 return localStorage.getItem('flux:last_known_user_namespace')
22}

Writing a user queue entry

src/lib/queue/queueUserWrite.ts
1// src/lib/queue/queueUserWrite.ts
2//
3// A USER queue entry. 'user' scope plus a real userId is what makes Flux
4// encrypt it. Without BOTH, Flux stores the entry as a global record
5// (readable body plus checksum, userId: null) and a signed in user's replay
6// will never see it.
7import { addQueueEntrySafe, FluxLockedError } from '@tsworldtech/flux'
8import { getActingUserId } from '../../store/authStore'
9
10const STORAGE_PREFIX = 'my_react_app' // same value as createFlux({ storagePrefix })
11
12export async function queueUserWrite(
13 entry: Parameters<typeof addQueueEntrySafe>[0]
14) {
15 const userId = await getActingUserId()
16
17 // Never fall back to a global (unencrypted) entry for a user's data.
18 if (!userId) throw new Error('You need to be signed in to save changes offline.')
19
20 try {
21 return await addQueueEntrySafe(
22 entry,
23 STORAGE_PREFIX,
24 undefined, // onStorageFallback
25 undefined, // onDuplicate
26 undefined, // mergeHandler
27 'user', // scope
28 userId // tenant
29 )
30 } catch (err) {
31 // The user's key is locked (for example the key endpoint was
32 // unreachable at sign in). Flux refuses the write instead of storing
33 // plaintext or quietly parking it in memory.
34 if (err instanceof FluxLockedError) {
35 throw new Error('Secure storage is locked. Sign in again to save changes while offline.')
36 }
37 throw err
38 }
39}

Writing a global queue entry

src/lib/queue/queueContactMessage.ts
1// src/lib/queue/queueContactMessage.ts
2//
3// A GLOBAL queue entry: a public form with no signed in user. Scope and
4// tenant are passed explicitly so the intent is obvious. Global entries
5// are not encrypted (readable body plus a checksum that detects edits), and
6// they replay with userId: null, signed in or out.
7import { addQueueEntrySafe } from '@tsworldtech/flux'
8
9const STORAGE_PREFIX = 'my_react_app'
10
11export async function queueContactMessage(payload: Record<string, any>) {
12 return addQueueEntrySafe(
13 {
14 channel: 'contact',
15 storeName: 'contact',
16 endpoint: 'http://localhost:3001/api/contact',
17 method: 'POST',
18 payload,
19 timestamp: Date.now(),
20 dedupeKey: String(payload.email).toLowerCase(),
21 dedupeStrategy: 'reject',
22 } as any,
23 STORAGE_PREFIX,
24 undefined,
25 undefined,
26 undefined,
27 'global', // scope
28 null // tenant: nobody
29 )
30}

Register each queue with the matching scope

src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): the registration scope must match the write scope
2
3// USER queue: the registration says scope: 'user'. Register it inside
4// registerUserChannels() from Step 11, not at module top level.
5flux.register({
6 channel: 'support',
7 idbKey: 'support:queue',
8 ttl: 'long',
9 ingestionType: 'COLLECTION_ALL',
10 event: 'INSERT',
11 scope: 'user',
12 store: { setState: () => {}, getState: () => [] },
13 queueConfig: {
14 storeName: 'support',
15 replayEndpoint: 'http://localhost:3001/api/support/send',
16 method: 'POST',
17 dedupeField: 'dedupeKey',
18 dedupeStrategy: 'reject',
19 },
20})
21
22// GLOBAL queue: the registration says scope: 'global'.
23flux.register({
24 channel: 'contact',
25 idbKey: 'contact:queue',
26 ttl: 'long',
27 ingestionType: 'COLLECTION_ALL',
28 event: 'INSERT',
29 scope: 'global',
30 store: { setState: () => {}, getState: () => [] },
31 queueConfig: {
32 storeName: 'contact',
33 replayEndpoint: 'http://localhost:3001/api/contact',
34 method: 'POST',
35 dedupeField: 'email',
36 dedupeStrategy: 'reject',
37 },
38})
39
40// Keep user and global queues in SEPARATE storeNames, so their replay
41// filters can never overlap.

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:
src/lib/queue/replay.ts
1// Replaying by hand with replayQueue() (outside flux.replay()):
2// the userId you pass decides WHICH entries are selected.
3import { replayQueue } from '@tsworldtech/flux'
4import { getActingUserId } from '../../store/authStore'
5
6// USER queue: only this user's entries. Needs a signed in user.
7export async function replaySupport() {
8 const userId = await getActingUserId()
9 if (!userId) return // user entries stay sealed on disk until sign in
10
11 await replayQueue({
12 storeName: 'support',
13 endpoint: 'http://localhost:3001/api/support/send',
14 storagePrefix: 'my_react_app',
15 method: 'POST',
16 userId,
17 })
18}
19
20// GLOBAL queue: only entries with no user. Works signed in or out.
21export async function replayContact() {
22 await replayQueue({
23 storeName: 'contact',
24 endpoint: 'http://localhost:3001/api/contact',
25 storagePrefix: 'my_react_app',
26 method: 'POST',
27 userId: null,
28 })
29}
30
31// A global entry replayed with a string userId is silently skipped,
32// and a user entry replayed with null is silently skipped too.
33// undefined means "no filtering" and replays both kinds for that store,
34// which is why null is the right value for a global queue.

Counters and cross tab sync

src/store/supportStore.ts (excerpt)
1// Keep a queue counter honest across tabs.
2//
3// QUEUE_ENTRY_REMOVED carries no storeName, so a counter that does minus one on
4// every removal drifts when OTHER queues empty. Recount from storage
5// instead, scoped the same way you replay.
6import { getQueueCount } from '@tsworldtech/flux'
7
8async function refreshSupportCount(userId: string) {
9 const count = await getQueueCount('my_react_app', 'support', userId)
10 useSupportStore.setState({ queueCount: count })
11}
12
13const channel = new BroadcastChannel('my_react_app:flux:queue:sync')
14let timer: ReturnType<typeof setTimeout> | null = null
15
16channel.addEventListener('message', (event) => {
17 const type = event.data?.type
18
19 // Added messages name their store. Removals and clears do not.
20 if (type === 'QUEUE_ENTRY_ADDED' && event.data?.storeName !== 'support') return
21
22 if (
23 type === 'QUEUE_ENTRY_ADDED' ||
24 type === 'QUEUE_ENTRY_REMOVED' ||
25 type === 'QUEUE_USER_SCOPE_CLEARED'
26 ) {
27 if (timer) return
28 timer = setTimeout(async () => {
29 timer = null
30 const userId = await getActingUserId()
31 if (userId) await refreshSupportCount(userId)
32 }, 50)
33 }
34})
35
36// Do NOT post { type: 'QUEUE_CLEARED' } after a replay. Other tabs answer
37// it by clearing the WHOLE IndexedDB queue and every localStorage key that
38// starts with your storage prefix: every other queue (user or global) is
39// wiped, because the message has no storeName filter.
Never broadcast QUEUE_CLEARED from your own code

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.

20

Logout, locked data and tamper detection

With encryption on, signing a user out no longer has to throw their unsent writes away. 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.
src/lib/flux.ts (excerpt)
1// src/lib/flux.ts (excerpt): logout helpers
2//
3// With encryption on, flux.clearUserSession() KEEPS the user's unsent
4// writes (sealed on disk) and replays them at the next sign in. Tell the
5// user how many there are before they leave.
6export async function getUnsentChangeCount(): Promise<number> {
7 try {
8 const { pending, failed } = await flux.getQueueSummary()
9 return pending + failed
10 } catch {
11 return 0
12 }
13}
14
15// "Public computer" sign out: wipes the cache AND the queued writes, and
16// destroys the user's key. Call it BEFORE your auth sign out.
17export async function signOutAndDiscardUnsent(): Promise<void> {
18 await flux.clearUserSession({ discardQueue: true })
19}
Offer both choices in your sign out UI: "Sign out" (keeps unsent changes for next time) and "Sign out and clear this device" (calls signOutAndDiscardUnsent() before your auth sign out). Show getUnsentChangeCount() so the user knows what is waiting.
SituationWhat Flux does
Signed out user's sealed writesStay on disk. Replayed at that user's next sign in.
Sealed writes of a user who never returnsDeleted after queueRetentionMs (default 30 days).
Another user signs in on the same deviceCannot read the first user's sealed writes and never replays them.
Sealed under a key that has since been replacedRemoved silently. It can never be opened and is not a tamper alarm.
Stored write or cache entry edited outside the appFails 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

src/components/FluxIntegrityModal.tsx
1// src/components/FluxIntegrityModal.tsx
2import { useEffect, useState } from 'react'
3import type { IntegrityEvent } from '@tsworldtech/flux'
4import { flux } from '../lib/flux'
5
6// Shows when Flux rejects stored data that was edited outside the app.
7// subscribeToIntegrity calls back immediately with anything not yet
8// acknowledged (so the modal still appears after a reload) and again for
9// every new event, from any tab.
10export function FluxIntegrityModal() {
11 const [events, setEvents] = useState<IntegrityEvent[]>([])
12
13 useEffect(() => {
14 const unsubscribe = flux.subscribeToIntegrity((pending: IntegrityEvent[]) => setEvents(pending))
15 return () => unsubscribe()
16 }, [])
17
18 if (events.length === 0) return null
19
20 const queueEvents = events.filter((e) => e.kind === 'queue').length
21 const cacheEvents = events.length - queueEvents
22
23 return (
24 <div role="alertdialog" aria-modal="true" aria-labelledby="flux-integrity-title">
25 <h2 id="flux-integrity-title">Edits detected</h2>
26
27 <p>
28 Some data stored on this device was changed outside the app. The edited
29 copies were rejected and deleted, so nothing altered was used.
30 </p>
31
32 <ul>
33 {cacheEvents > 0 && (
34 <li>{cacheEvents} cached item{cacheEvents > 1 ? 's' : ''} removed. Fresh data will download automatically.</li>
35 )}
36 {queueEvents > 0 && (
37 <li>{queueEvents} unsent change{queueEvents > 1 ? 's' : ''} removed and will not be sent.</li>
38 )}
39 </ul>
40
41 <button type="button" onClick={() => flux.acknowledgeIntegrity()}>
42 I understand
43 </button>
44 </div>
45 )
46}
Mount it once, in the part of your app that renders for a signed in user:
src/components/DashboardShell.tsx (excerpt)
1// Mount it ONCE, inside the part of your app that only renders for a
2// signed in user (for example your authenticated shell or auth gate).
3import { FluxIntegrityModal } from '../components/FluxIntegrityModal'
4
5export function DashboardShell({ children }: { children: React.ReactNode }) {
6 return (
7 <>
8 {children}
9 <FluxIntegrityModal />
10 </>
11 )
12}
Test the whole flow

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.

Just want a static page to work offline, no backend at all?

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:

vite.config.ts
1// vite.config.ts: static offline precaching only
2import { defineConfig } from 'vite'
3import react from '@vitejs/plugin-react'
4import { fluxVitePlugin } from '@tsworldtech/flux-react/plugin'
5
6export default defineConfig({
7 plugins: [
8 react(),
9 fluxVitePlugin({
10 precacheRoutes: ['/', '/pricing', '/about', '/offline'],
11 offlineShell: '/offline',
12 storagePrefix: 'my_static_react_app',
13 bypassRoutePrefixes: ['/auth/callback'],
14 }),
15 ],
16})

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.

Powered by Flux