Skip to content
⚠️ Beta: API may change before v1.0. Pin to ~0.x.0 to avoid breaking changes.

createPersister()

Creates a persister instance for saving and restoring flow state. Adds features like TTL, versioning, and validation on top of storage stores.

import { createPersister } from "@useflow/react";
function createPersister(options: PersisterOptions): FlowPersister

Configuration object for the persister:

type PersisterOptions = {
store: FlowStore; // Required: Storage backend
ttl?: number; // Optional: Time to live in ms
validate?: (state: PersistedFlowState) => boolean; // Optional: State validation
onSave?: (flowId: string, state: PersistedFlowState) => void; // Optional: Save callback
onRestore?: (flowId: string, state: PersistedFlowState) => void; // Optional: Restore callback
onDiscard?: (event: FlowRestoreDiscardEvent) => void; // Optional: Discard callback
onError?: (error: Error) => void; // Optional: Error handler (see below)
}
import {
createLocalStorageStore,
createSessionStorageStore,
createMemoryStore
} from "@useflow/react";
// Browser localStorage
const localStore = createLocalStorageStore();
// Browser sessionStorage
const sessionStore = createSessionStorageStore();
// In-memory (for testing)
const memoryStore = createMemoryStore();
type FlowStore = {
get: (flowId: string, options?: FlowStoreOptions) =>
Promise<PersistedFlowState | null> | PersistedFlowState | null;
set: (flowId: string, state: PersistedFlowState, options?: FlowStoreOptions) =>
Promise<void> | void;
remove: (flowId: string, options?: FlowStoreOptions) =>
Promise<void> | void;
removeFlow?: (flowId: string) => Promise<void> | void;
removeAll?: () => Promise<void> | void;
}
type FlowStoreOptions = {
instanceId?: string;
variantId?: string;
}
import { createPersister, createLocalStorageStore } from "@useflow/react";
const persister = createPersister({
store: createLocalStorageStore()
});
// Use with Flow component
<Flow
flow={myFlow}
persister={persister}
initialContext={{}}
>
{({ renderStep }) => renderStep({ /* ... */ })}
</Flow>
const persister = createPersister({
store: createLocalStorageStore(),
ttl: 7 * 24 * 60 * 60 * 1000 // 7 days
});
// State older than 7 days will be ignored
const persister = createPersister({
store: createLocalStorageStore(),
validate: (state) => {
// Ensure required fields exist
return state?.stepId && state?.context?.userId;
}
});
// Invalid states will be ignored on restore
const persister = createPersister({
store: createLocalStorageStore(),
onSave: (flowId, state) => {
console.log(`Saved ${flowId} at step ${state.stepId}`);
},
onRestore: (flowId, state) => {
console.log(`Restored ${flowId} from step ${state.stepId}`);
},
onError: (error) => {
console.error('Persistence error:', error);
}
});

Called when a store read, write or removal fails, or when a persister callback throws. The operation still resolves (save and restore return null), so failures never break the flow.

save(), restore() and remove() also accept an onError option for one call. It replaces the persister’s onError rather than adding to it. <Flow> passes one whenever onPersistenceError is set, so failures reach that handler with the flow ID and operation, and the persister’s onError does not also fire. Without a Flow or provider handler, the persister’s onError runs as usual.

Built-in key-value stores throw when stored data can’t be read or deserialized, so corrupted state reaches onError instead of looking like missing state. Custom stores should do the same: return null only when nothing is stored.

Called once when saved state is rejected: expired, version_unmigrated, migration_rejected, or validation_rejected. Missing state and successful restores do not notify. Only expiration removes stored state.

export type FlowRestoreDiscardReason =
| "expired"
| "version_unmigrated"
| "migration_rejected"
| "validation_rejected"
| "incompatible_state";
export interface FlowRestoreDiscardEvent {
flowId: string;
reason: FlowRestoreDiscardReason;
fromVersion?: string;
toVersion?: string;
instanceId?: string;
variantId?: string;
errors?: string[];
}

Both types are exported by @useflow/core and @useflow/react. fromVersion is the saved __meta.version; toVersion is the restore option’s version when known. Only React emits incompatible_state and its errors array.

const persister = createPersister({
store,
onDiscard: (event) => {
Sentry.captureMessage("Flow progress discarded", {
level: "warning",
extra: { ...event },
});
},
});

The restore() option’s onDiscard overrides this default; they never both fire. React passes its resolved Flow/provider callback through this option. React’s incompatible_state check notifies only the Flow/provider onDiscard; when neither is set, it calls onPersistenceError instead.

Throwing callbacks do not interrupt restore. Failures go to onError, or a development-only warning if no handler exists. Flow/provider callback failures use onPersistenceError instead. See reporting discarded progress.

Create a custom store for any backend:

const apiStore: FlowStore = {
get: async (flowId, options) => {
const params = new URLSearchParams({
flowId,
...(options?.instanceId && { instanceId: options.instanceId }),
...(options?.variantId && { variantId: options.variantId })
});
const response = await fetch(`/api/flow-state?${params}`);
if (!response.ok) return null;
return response.json();
},
set: async (flowId, state, options) => {
await fetch('/api/flow-state', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ flowId, state, ...options })
});
},
remove: async (flowId, options) => {
const params = new URLSearchParams({
flowId,
...(options?.instanceId && { instanceId: options.instanceId }),
...(options?.variantId && { variantId: options.variantId })
});
await fetch(`/api/flow-state?${params}`, {
method: 'DELETE'
});
}
};
const persister = createPersister({ store: apiStore });
const indexedDBStore: FlowStore = {
get: async (flowId, options) => {
const db = await openDB();
const key = formatKey(flowId, options);
return db.get('flows', key);
},
set: async (flowId, state, options) => {
const db = await openDB();
const key = formatKey(flowId, options);
await db.put('flows', state, key);
},
remove: async (flowId, options) => {
const db = await openDB();
const key = formatKey(flowId, options);
await db.delete('flows', key);
}
};
// Helper to format keys consistently
function formatKey(flowId: string, options?: FlowStoreOptions) {
const parts = [flowId];
if (options?.variantId) parts.push(options.variantId);
if (options?.instanceId) parts.push(options.instanceId);
return parts.join(':');
}
const persister = createPersister({ store: indexedDBStore });

The returned persister object has these methods:

await persister.save(
flowId: string,
state: FlowState,
options?: {
version?: string;
instanceId?: string;
variantId?: string;
onError?: (error: Error) => void;
}
): Promise<PersistedFlowState | null>
await persister.restore(
flowId: string,
options?: {
version?: string;
migrate?: MigrateFunction;
instanceId?: string;
variantId?: string;
onDiscard?: (event: FlowRestoreDiscardEvent) => void;
onError?: (error: Error) => void;
}
): Promise<PersistedFlowState | null>
await persister.remove(
flowId: string,
options?: {
instanceId?: string;
variantId?: string;
onError?: (error: Error) => void;
}
): Promise<void>
await persister.removeFlow(
flowId: string
): Promise<void>

Removes all instances of a specific flow (base + all instances).

await persister.removeAll(): Promise<void>

Removes all flows managed by this persister.

The store implementation determines the key format. For key-value stores (localStorage, sessionStorage), keys typically follow this pattern:

[flowId]:[variantId]:[instanceId]

Examples:

  • onboarding:: - Default (no variant or instance)
  • onboarding:v2: - With variant
  • onboarding::user123 - With instance
  • checkout:v2:session456 - All options

Different stores may use different formats. Check your store’s documentation for specifics.

<Flow
flow={myFlow}
persister={persister}
onPersistenceError={(error, { flowId, operation }) => {
console.error(`Could not ${operation} ${flowId}:`, error);
// Fallback or notify user
}}
>
{/* ... */}
</Flow>
// Remove specific flow state
await persister.remove('onboarding', { instanceId: 'user123' });
// Remove all instances of a flow
await persister.removeFlow?.('onboarding');
// Clear all persisted data
await persister.removeAll?.();
// Different persistence for each user
<Flow
flow={checkoutFlow}
persister={persister}
instanceId={userId} // Separate storage per user
>
{/* ... */}
</Flow>

Handle breaking changes in your flow:

const migration: MigrateFunction = (oldState, fromVersion) => {
if (fromVersion === "v1") {
// Migrate v1 → v2
return {
...oldState,
context: {
...oldState.context,
newField: 'default'
}
};
}
return oldState;
};
// Flow will use migration function on restore
<Flow
flow={myFlow}
persister={persister}
>
{/* ... */}
</Flow>