Encryption key route
How Flux encrypts a signed in user's cached data and queued offline writes, and how to build the one backend endpoint it needs: a key route that tells Flux who the user is and hands back their secret. Includes ready to use versions for Next.js with Supabase or any session library, bearer token and JWT backends, Express, and fetch-style runtimes like Hono, Workers, Deno and Bun.
- Flux installed and a working user scoped setup — see getting_started/nextjs
- A backend you control that can read your signed in user's session or token
- Node 18+ (or any runtime with WebCrypto) on the server that hosts the route
- (Optional)No backend you control? Skip to the passphrase provider in step 9.
How the key route fits in
Whoever holds FLUX_KEY_MASTERS can derive any user's secret. That is the trade-off of server derived keys: your server never sees user data, but it can in principle unlock the wrapped key on a device it also has the disk of. Protect the masters like a signing key. If your threat model requires that your own server can never derive a key, use the passphrase provider (step 9).
This protects data at rest on shared, lost or inspected devices. It does not defend against script running on your own origin: a cross site scripting bug can use the unlocked key while the user is signed in.
The contract your route must meet
| Status | Meaning | What to do |
|---|---|---|
200 | Key issued | Nothing to do. |
400 invalid-user | The user id was empty, not a string, or longer than 256 characters | Check what your authenticate function returns. |
401 unauthorized | No signed in user, or authenticate threw | Check the session cookie or token reaches the route. Refresh an expired session first (the prepare option). |
403 forbidden | The X-Flux-Key-Request header is missing | Use createHttpKeyProvider, or send the header yourself. Do not disable the check unless you replace it with something equivalent. |
404 unknown-kid | Flux asked for a master version your server no longer has | You removed an old master too early. Put it back in FLUX_KEY_MASTERS. |
500 misconfigured | FLUX_KEY_MASTERS or FLUX_KEY_CURRENT is missing or malformed | Fix the env vars. The server log names the reason. |
Flux asks for a key for a specific user id (the one you pass to flux.bootstrap()). If the uid in the response is a different id, the key is refused and that user's data stays locked. Return the same identifier your client uses: the Supabase user.id, the JWT sub, your own user primary key. Pick one and use it everywhere.
Pick the version that fits your backend
authenticate function that returns the verified user id, or null.| Your backend | Use |
|---|---|
| Next.js App Router + Supabase | 3a: the Supabase route |
| Next.js with Auth.js, Clerk, Lucia, iron-session or your own cookies | 3b: the generic Next.js route |
| Any fetch-style server with bearer tokens (JWT), including a separate API | 3c: the bearer token handler |
| Express or another Node framework with its own request object | 3d: the Express route, which uses the issuer directly |
| Hono, Cloudflare Workers, Deno, Bun, Node 18+ servers | 3e: the fetch-style route |
| API on a different origin from the web app | 3f: allowedOrigins, plus the client options in step 5 |
| You cannot or will not run a key endpoint | Passphrase provider, step 9 |
3a. Next.js + Supabase (cookie session)
getUser() verifies the token with Supabase. getSession() only reads the cookie, which a client can forge. This route hands out a secret, so use the verified call.
3b. Next.js with any session library
3c. Bearer token (JWT) on any fetch-style server
3d. Express
3e. Hono, Workers, Deno, Bun
3f. API on a different origin
The server helpers (createKeyIssuer, createKeyRequestHandler, parseMasters) are written to keep server code out of browser bundles, so they are published on the @tsworldtech/flux/server entry. If your installed version exports them from @tsworldtech/flux instead, import from there. Either way, only import them in server code.
Create the master key and set the environment
Never expose these to the browser: no NEXT_PUBLIC_, VITE_ or other public prefix. Set them in your host's environment settings for every environment that serves the route (production, and previews if you test there), then redeploy. Dev servers read env files only at startup, so restart after editing.
Keep a copy in a password manager or secrets vault, never in the repository. If the master is lost, every user's encrypted offline data and queued writes become unrecoverable. Never change a master's value in place: add a new version instead (step 6).
k1, k2, any string) must exist in FLUX_KEY_MASTERS. The route returns 500 server-misconfigured otherwise.Point Flux at the route
createHttpKeyProvider() sends the request, adds the required header, applies a timeout, and validates the response. With a same origin cookie session you only need the endpoint:sessionKeyIdleMs (default 7 days): how long an unlocked key stays usable on a device without being used. After that the user must sign in online again.
queueRetentionMs (default 30 days): sealed queued writes of a user who is not signed in are deleted after this long, so abandoned data does not sit on a shared machine forever. The signed in user's own writes are never purged by it.
allowLegacyPlaintext: accepts records written before encryption was turned on, once, and re-seals them. Set it to false one release after every user has upgraded.
onLocked(userId, reason): fires when a user's data cannot be opened. Reasons: offline-needs-login, provider-error, unwrap-failed.
Rotate the master key
Verify it works
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| POST /api/flux/key answers 500 server-misconfigured | FLUX_KEY_MASTERS is missing, not valid JSON, has a master shorter than 32 bytes, or FLUX_KEY_CURRENT names a version that is not in it. The server log prints the reason. | Fix the variables, restart the dev server (env files are read at startup) or redeploy. |
| 401 on every request | Your session does not reach the route, or the access token is expired. | Check the cookie is sent (same origin, or credentials and CORS set up). Use the prepare option to refresh the session first. |
| 403 on every request | The X-Flux-Key-Request header is missing. | Use createHttpKeyProvider. A proxy that strips custom headers causes this too. |
| Key fetched, data still locked (onLocked: provider-error) | The uid in the response is not the user id Flux asked for, or the response shape is wrong. | Return the same id you pass to flux.bootstrap(). For Supabase that is user.id. For JWTs it is usually sub. |
| onLocked: offline-needs-login | The first sign in on this device happened offline. | Expected. The user must sign in online once on each device. |
| onLocked: unwrap-failed | The stored wrapped key cannot be opened with the secret the server issued. Usually the master for that kid changed. | Never change a master in place. Add a new kid instead. As a last resort the user's local data can be reset by signing out with discardQueue. |
| 404 unknown-kid after a rotation | An old master was removed before every device re-wrapped. | Restore the old master in FLUX_KEY_MASTERS and wait out the idle and retention windows. |
| Works locally, 500 in production | The env vars were set locally but not on the host, or set for the wrong environment (preview vs production). | Set both variables for every environment that serves the app and redeploy. |
| User writes queue as userId: null | Not an encryption problem: the queue write was made with the default global scope. | Pass 'user' and the user id to addQueueEntrySafe. See core_concepts/offline_queue. |
Flux can only ask the key route when it is reachable. A user who signs in for the first time on a device while offline stays locked, and queued user writes are refused with FluxLockedError instead of being stored unencrypted. Once they have signed in online one time, the unlocked key is kept for the idle window and offline cold starts keep working.
No server? Use a passphrase
A forgotten passphrase means the queued data cannot be recovered, and a weak passphrase can be brute forced by someone holding a copy of the disk. The passphrase provider also has no key rotation: it only knows the one version it was created with. Server derived keys (steps 1 to 6) are the better default when you have a backend.
For the engine options that turn encryption on and the user versus global queue rules, see getting_started/nextjs (Steps 17 to 20). For how encrypted entries are selected and replayed, see api/replay. For what a locked key does to queued writes and what logout keeps or removes, see core_concepts/offline_queue.