Guides

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.

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

How the key route fits in

Flux encrypts in the browser, so it needs a secret the browser cannot invent for itself and an attacker with a copy of the disk cannot guess. That secret comes from your server. The key route is a single endpoint that verifies who is asking and answers with a value derived from a master key that only your server holds.
typescript
1// What happens, end to end:
2//
3// 1. A user signs in to your app (your normal auth). Flux starts their session.
4//
5// 2. Flux calls YOUR key route: POST /api/flux/key (cookie or token)
6// - your route verifies the session and learns the user id
7// - it answers { secret, kid, uid, current }
8// secret = HMAC-SHA256( master[kid], "flux-user-key-v1|" + userId )
9// - nothing is stored on your server. The secret is recomputed on demand.
10//
11// 3. Flux, in the browser:
12// - derives a key-encryption key from that secret (HKDF, bound to the user and kid)
13// - first time on this device: creates a random 32 byte data key, wraps it
14// with that key and stores the wrapped copy
15// - later: unwraps the stored data key
16// - keeps the unlocked, non-extractable data key for the idle window
17//
18// 4. Flux seals user-scoped cache entries and queued writes with the data key
19// (AES-GCM). Your server never sees the data key or any user data.
20//
21// What your server learns: that user X asked for a key. What your server
22// can do: derive any user's secret, because it holds the master keys.
Know the trust model

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.

2

The contract your route must meet

Any backend works as long as it follows this contract. Flux sends the request for you and checks the response.
typescript
1// REQUEST (Flux sends this for you with createHttpKeyProvider)
2//
3// POST /api/flux/key
4// X-Flux-Key-Request: 1 required. Blocks cross-site form posts.
5// Content-Type: application/json
6// body: { "kid": "k1" } optional. Only sent to unwrap an OLDER key
7// version after a master key rotation.
8//
9// GET is also supported: GET /api/flux/key?kid=k1
10//
11// RESPONSE 200
12//
13// {
14// "secret": "<base64, at least 16 bytes>",
15// "kid": "k1", which master version produced it
16// "uid": "<the user id>", Flux refuses the key if this is not the
17// user id it asked for
18// "current": "k2" the version used for new unlocks
19// }
20//
21// Headers: Cache-Control: no-store
22//
23// The user id comes from your VERIFIED SESSION. Never from the request body.
Status codes the provided handler returns, and what each one means for you:
StatusMeaningWhat to do
200Key issuedNothing to do.
400 invalid-userThe user id was empty, not a string, or longer than 256 charactersCheck what your authenticate function returns.
401 unauthorizedNo signed in user, or authenticate threwCheck the session cookie or token reaches the route. Refresh an expired session first (the prepare option).
403 forbiddenThe X-Flux-Key-Request header is missingUse createHttpKeyProvider, or send the header yourself. Do not disable the check unless you replace it with something equivalent.
404 unknown-kidFlux asked for a master version your server no longer hasYou removed an old master too early. Put it back in FLUX_KEY_MASTERS.
500 misconfiguredFLUX_KEY_MASTERS or FLUX_KEY_CURRENT is missing or malformedFix the env vars. The server log names the reason.
The user id must match on both sides

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.

3

Pick the version that fits your backend

Three things vary between backends: how you read the session, which runtime you are on, and where your secrets live. The handler itself never changes. You supply an authenticate function that returns the verified user id, or null.
Your backendUse
Next.js App Router + Supabase3a: the Supabase route
Next.js with Auth.js, Clerk, Lucia, iron-session or your own cookies3b: the generic Next.js route
Any fetch-style server with bearer tokens (JWT), including a separate API3c: the bearer token handler
Express or another Node framework with its own request object3d: the Express route, which uses the issuer directly
Hono, Cloudflare Workers, Deno, Bun, Node 18+ servers3e: the fetch-style route
API on a different origin from the web app3f: allowedOrigins, plus the client options in step 5
You cannot or will not run a key endpointPassphrase provider, step 9

3a. Next.js + Supabase (cookie session)

app/api/flux/key/route.ts
1// app/api/flux/key/route.ts (Next.js App Router + Supabase cookie session)
2import { createClient } from '@/lib/supabase/server' // your server side Supabase client
3import {
4 createKeyIssuer,
5 createKeyRequestHandler,
6 parseMasters,
7} from '@tsworldtech/flux/server' // or '@tsworldtech/flux', whichever your package exports
8
9export const runtime = 'nodejs'
10export const dynamic = 'force-dynamic'
11
12let cached: ((req: Request) => Promise<Response>) | null = null
13
14// Built on first request, so `next build` does not need the env vars.
15function getHandler(): ((req: Request) => Promise<Response>) | null {
16 if (cached) return cached
17
18 try {
19 const issuer = createKeyIssuer({
20 masters: parseMasters(process.env.FLUX_KEY_MASTERS),
21 currentKid: process.env.FLUX_KEY_CURRENT ?? '',
22 })
23
24 cached = createKeyRequestHandler({
25 issuer,
26 authenticate: async () => {
27 const supabase = await createClient()
28 // getUser() verifies the token with Supabase. getSession() only reads the cookie.
29 const { data, error } = await supabase.auth.getUser()
30 if (error || !data.user) return null
31 return { userId: data.user.id }
32 },
33 })
34 return cached
35 } catch (err) {
36 console.error('[flux:key] misconfigured:', (err as Error).message)
37 return null
38 }
39}
40
41async function handle(req: Request): Promise<Response> {
42 const handler = getHandler()
43 if (!handler) {
44 return new Response(JSON.stringify({ error: 'server-misconfigured' }), {
45 status: 500,
46 headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
47 })
48 }
49 return handler(req)
50}
51
52export const POST = handle
53export const GET = handle
54export const OPTIONS = handle
getUser(), not getSession()

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

typescript
1// app/api/flux/key/route.ts (Next.js with ANY session library)
2//
3// The only part that changes between backends is `authenticate`. Replace
4// getSessionUser() with whatever your stack uses: NextAuth/Auth.js
5// (auth()), Clerk (auth()), Lucia (validateRequest()), iron-session,
6// your own cookie lookup, etc. It must return the user's id from a
7// VERIFIED session, or null.
8import {
9 createKeyIssuer,
10 createKeyRequestHandler,
11 parseMasters,
12} from '@tsworldtech/flux/server'
13import { getSessionUser } from '@/lib/auth' // YOUR function: () => Promise<{ id: string } | null>
14
15export const runtime = 'nodejs'
16export const dynamic = 'force-dynamic'
17
18const handler = createKeyRequestHandler({
19 issuer: createKeyIssuer({
20 masters: parseMasters(process.env.FLUX_KEY_MASTERS),
21 currentKid: process.env.FLUX_KEY_CURRENT ?? '',
22 }),
23 authenticate: async () => {
24 const user = await getSessionUser()
25 return user ? { userId: user.id } : null
26 },
27})
28
29export const POST = handler
30export const GET = handler
31export const OPTIONS = handler
32
33// Note: this builds the issuer at import time, so `next build` needs the
34// env vars. The Supabase version above builds it lazily instead.

3c. Bearer token (JWT) on any fetch-style server

typescript
1// Any fetch-style server, authenticating with a bearer token (a JWT).
2// Uses the `jose` library to verify the token. Swap in your own verifier.
3import { jwtVerify } from 'jose'
4import {
5 createKeyIssuer,
6 createKeyRequestHandler,
7 parseMasters,
8} from '@tsworldtech/flux/server'
9
10const jwtSecret = new TextEncoder().encode(process.env.JWT_SECRET)
11
12export const fluxKeyHandler = createKeyRequestHandler({
13 issuer: createKeyIssuer({
14 masters: parseMasters(process.env.FLUX_KEY_MASTERS),
15 currentKid: process.env.FLUX_KEY_CURRENT ?? '',
16 }),
17
18 authenticate: async (req) => {
19 const header = req.headers.get('authorization') ?? ''
20 const token = header.startsWith('Bearer ') ? header.slice(7) : null
21 if (!token) return null
22
23 try {
24 const { payload } = await jwtVerify(token, jwtSecret, { issuer: 'my-app' })
25 // The user id MUST be the same id your client passes to Flux
26 // (the userId you give flux.bootstrap()). Flux refuses the key otherwise.
27 return payload.sub ? { userId: payload.sub } : null
28 } catch {
29 return null
30 }
31 },
32})

3d. Express

typescript
1// server.ts (Express + express-session)
2//
3// Express handlers are not fetch-style, so use the issuer directly and
4// do the two checks yourself: the required header, and your session.
5import express from 'express'
6import session from 'express-session'
7import { createKeyIssuer, parseMasters } from '@tsworldtech/flux/server'
8
9const app = express()
10app.use(express.json())
11app.use(session({ secret: process.env.SESSION_SECRET!, resave: false, saveUninitialized: false }))
12
13const issuer = createKeyIssuer({
14 masters: parseMasters(process.env.FLUX_KEY_MASTERS),
15 currentKid: process.env.FLUX_KEY_CURRENT ?? '',
16})
17
18app.post('/api/flux/key', async (req, res) => {
19 res.set('Cache-Control', 'no-store')
20
21 // 1. Blocks cross-site form posts. A page on another site cannot add a
22 // custom header without a CORS preflight.
23 if (!req.get('x-flux-key-request')) return res.status(403).json({ error: 'forbidden' })
24
25 // 2. The user id comes from YOUR verified session, never from the body.
26 const userId = (req.session as any)?.userId as string | undefined
27 if (!userId) return res.status(401).json({ error: 'unauthorized' })
28
29 // 3. Optional: an older key version, requested after a rotation.
30 const kid = typeof req.body?.kid === 'string' ? req.body.kid : undefined
31
32 try {
33 res.json(await issuer.issue(userId, kid)) // { secret, kid, uid, current }
34 } catch (err: any) {
35 res.status(err?.status ?? 500).json({ error: err?.code ?? 'server-error' })
36 }
37})
38
39app.listen(3001)

3e. Hono, Workers, Deno, Bun

typescript
1// src/index.ts (Hono on Cloudflare Workers; also fine on Deno, Bun, Node 18+)
2//
3// createKeyRequestHandler is a plain (Request) => Response function, so it
4// plugs straight in. On Workers, secrets live on `env`, not process.env,
5// so the handler is built from env and cached per isolate.
6import { Hono } from 'hono'
7import {
8 createKeyIssuer,
9 createKeyRequestHandler,
10 parseMasters,
11} from '@tsworldtech/flux/server'
12
13type Env = { FLUX_KEY_MASTERS: string; FLUX_KEY_CURRENT: string }
14
15const app = new Hono<{ Bindings: Env }>()
16
17let cached: ((req: Request) => Promise<Response>) | null = null
18
19function getHandler(env: Env) {
20 if (!cached) {
21 cached = createKeyRequestHandler({
22 issuer: createKeyIssuer({
23 masters: parseMasters(env.FLUX_KEY_MASTERS),
24 currentKid: env.FLUX_KEY_CURRENT,
25 }),
26 // Replace with your own session or token check. It must return the
27 // verified user id, or null.
28 authenticate: async (req) => {
29 const userId = await myVerifySession(req)
30 return userId ? { userId } : null
31 },
32 })
33 }
34 return cached
35}
36
37app.all('/api/flux/key', (c) => getHandler(c.env)(c.req.raw))
38
39export default app

3f. API on a different origin

typescript
1// API on a different origin from the web app (for example
2// app.example.com talks to api.example.com).
3//
4// Server: list the web app's origin. Anything else gets no CORS headers.
5const handler = createKeyRequestHandler({
6 issuer,
7 authenticate,
8 allowedOrigins: ['https://app.example.com'],
9})
10//
11// The handler already allows the headers Flux sends
12// (authorization, content-type, x-flux-key-request) and credentials.
13// Make sure your session cookie is SameSite=None; Secure if you
14// authenticate with cookies across origins.
Which import path?

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.

4

Create the master key and set the environment

A master key is 32 random bytes, base64 encoded. Generate one for each environment. Use a different one for development and production, so a key issued on localhost never matches production.
terminal
1# 32 random bytes, base64. Works in PowerShell, bash and zsh (needs Node).
2node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
Put it in the server environment as a JSON object of version to key, plus the version to use for new unlocks:
.env.local
1# Server only. NEVER prefix with NEXT_PUBLIC_ (or your framework's public prefix).
2FLUX_KEY_MASTERS={"k1":"PASTE_THE_BASE64_HERE"}
3FLUX_KEY_CURRENT=k1
Server only. Back it up.

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).

Each master must decode to at least 32 bytes, and the key id (k1, k2, any string) must exist in FLUX_KEY_MASTERS. The route returns 500 server-misconfigured otherwise.
5

Point Flux at the route

On the client, 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:
lib/flux.ts (excerpt)
1// lib/flux.ts (excerpt) — cookie session, same origin (the default)
2import { createFlux, createHttpKeyProvider } from '@tsworldtech/flux'
3
4const flux = createFlux({
5 // ...adapter, storagePrefix, ttl...
6 encryption: {
7 keyProvider: createHttpKeyProvider({
8 endpoint: '/api/flux/key',
9
10 // Optional. Runs before every key request. Use it to refresh an
11 // expired session so the call does not fail with a 401.
12 prepare: async () => { await refreshMySession() },
13 }),
14 sessionKeyIdleMs: 7 * 24 * 60 * 60 * 1000,
15 queueRetentionMs: 30 * 24 * 60 * 60 * 1000,
16 allowLegacyPlaintext: true,
17 onLocked: (userId, reason) => console.warn('[flux] locked', userId, reason),
18 },
19 integrity: { queueTamperAction: 'delete' },
20})
With bearer tokens, or an API on another origin:
lib/flux.ts (excerpt)
1// lib/flux.ts (excerpt) — bearer token, possibly a different origin
2import { createHttpKeyProvider } from '@tsworldtech/flux'
3
4const keyProvider = createHttpKeyProvider({
5 endpoint: 'https://api.example.com/flux/key',
6
7 // If this returns nothing, the call fails before any request is sent.
8 getAccessToken: async () => getMyAccessToken(),
9
10 // Cookies are not needed with a bearer token. Use 'include' only if your
11 // API authenticates cross-origin with cookies instead.
12 credentials: 'omit',
13})
14
15// Other options on createHttpKeyProvider:
16// method 'POST' (default, body { kid }) or 'GET' (?kid=)
17// headers extra static or computed headers
18// buildBody custom POST body: ({ userId, kid }) => ...
19// parseResponse map a differently shaped response to { secret, kid, uid? }
20// timeoutMs default 10000
21// fetch override fetch (tests, custom agents)
If your backend already exposes a key like endpoint with a different JSON shape, map it on the client instead of changing the server:
typescript
1// Your backend already has a key endpoint with a different JSON shape?
2// Map it instead of rewriting the server.
3import { createHttpKeyProvider } from '@tsworldtech/flux'
4
5const keyProvider = createHttpKeyProvider({
6 endpoint: '/api/crypto/user-secret',
7
8 // Flux needs { secret: base64 (16+ bytes), kid: string, uid?: string }.
9 parseResponse: (body) => ({
10 secret: body.data.key,
11 kid: body.data.version,
12 uid: body.data.userId, // include it if you can: Flux checks it matches
13 }),
14})
What the encryption options mean

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.

6

Rotate the master key

Rotation never re-encrypts user data. Each device re-wraps only its small data key under the new master the next time it unlocks. The steps are always the same: add, switch, wait, remove.
.env.local
1# 1. Generate a new master (command above).
2# 2. Add it as a new version and point CURRENT at it. KEEP the old one.
3FLUX_KEY_MASTERS={"k1":"OLD_BASE64","k2":"NEW_BASE64"}
4FLUX_KEY_CURRENT=k2
5
6# What happens: each device, at its next unlock, sees that its stored key was
7# wrapped under k1 while the server now issues k2. Flux asks for k1 (the
8# "kid" in the request), unwraps the data key, and re-wraps it under k2.
9# No user data is re-encrypted, so nothing is lost and nothing is slow.
10#
11# 3. Remove k1 only after BOTH windows have passed:
12# the idle window (sessionKeyIdleMs, default 7 days)
13# the retention window (queueRetentionMs, default 30 days)
14# Remove it earlier and devices still wrapped under k1 get 404 unknown-kid
15# and cannot unlock.
7

Verify it works

First check the route on its own with three requests: no header, header but not signed in, and signed in.
terminal
1# 1. Without the header: must be 403
2curl -i -X POST http://localhost:3000/api/flux/key
3
4# 2. With the header but not signed in: must be 401
5curl -i -X POST http://localhost:3000/api/flux/key -H "X-Flux-Key-Request: 1"
6
7# 3. Signed in: copy your session cookie from DevTools (Application -> Cookies)
8curl -i -X POST http://localhost:3000/api/flux/key \
9 -H "X-Flux-Key-Request: 1" \
10 -H "Cookie: <your session cookie>"
11# Expect 200 and { "secret": "...", "kid": "k1", "uid": "...", "current": "k1" }
Then check the whole flow in the browser:
typescript
1// In the browser, after signing in:
2//
3// Network tab: one POST /api/flux/key answering 200 per unlock
4// (not one per request: the unlocked key is kept)
5//
6// Application -> IndexedDB -> <storagePrefix> -> keys:
7// wrapped:<userId> the user's data key, wrapped (safe at rest)
8// session:<userId> the unlocked key for the idle window
9//
10// Queue a user write while offline, then open the 'queue' store:
11// userId: '<uuid>' and an "enc" field -> encrypted
12// userId: null and "body" + "sum" -> written as GLOBAL (check the
13// scope and userId arguments)
14//
15// Sign out, sign in again: the queued write replays.
16// Edit a cached value in DevTools and refocus: the integrity modal appears.
8

Troubleshooting

SymptomLikely causeFix
POST /api/flux/key answers 500 server-misconfiguredFLUX_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 requestYour 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 requestThe 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-loginThe first sign in on this device happened offline.Expected. The user must sign in online once on each device.
onLocked: unwrap-failedThe 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 rotationAn 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 productionThe 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: nullNot 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.
First sign in on a device needs the network

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.

9

No server? Use a passphrase

If you cannot run a key endpoint, or you need a design where your server can never derive a key, derive the secret from a passphrase the user types. Nothing is sent anywhere, and it works fully offline.
typescript
1// No server at all: derive the secret from something the user types.
2import { createFlux, createPassphraseKeyProvider } from '@tsworldtech/flux'
3
4const flux = createFlux({
5 // ...
6 encryption: {
7 keyProvider: createPassphraseKeyProvider({
8 // Called on every unlock that has no usable stored key.
9 // Return nothing to cancel.
10 getPassphrase: async (userId) => askUserForPassphrase(userId),
11
12 // iterations: 600000, // PBKDF2-SHA256 (default)
13 // kid: 'pw-v1', // change only if you change iterations or salt
14 // salt: 'my-app', // optional app-wide salt, keep it stable
15 }),
16 },
17})
18
19// Trade-offs:
20// + Your server never sees anything, and it works fully offline.
21// - A forgotten passphrase means the queued data cannot be recovered.
22// - A weak passphrase can be brute-forced from a copy of the disk.
23// - It cannot rotate: only the one key version it was created with exists.
Choose with open eyes

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.

Powered by Flux