Change your data shape safely
Evolve persisted block state across releases with schemaVersion and pure migration functions.
Once users place your block into documents, their saved data persists across block updates. Whenever you rename a field, split a string into an object, or change an array structure, increment schemaVersion and register a migration function so existing blocks upgrade cleanly instead of crashing on missing fields.
How the migration envelope works
Persisted values written by useOrbixState, useStorage, usePersistentStorage, and useLiveQuery are wrapped in a versioned envelope:
{
"__orbixEnv": 1,
"v": 2,
"data": { "items": [] }
}When a block reads stored data:
- Legacy unversioned values (anything without
__orbixEnv: 1) are treated as version1(LEGACY_VERSION = 1). - Step-by-step upgrade: If the stored version
vis lower than the block's currentschemaVersion, the SDK runsmigrations[v],migrations[v + 1], and so on untilv === schemaVersion. Each step receives astructuredClonecopy of the data and{ blockType, from, to }. - Write-back: When
changedistrue, the upgraded envelope is written back to storage. - Rollback on throw: If any migration function throws an exception, the SDK aborts the upgrade, returns the untouched pre-migration payload, and does not overwrite stored data.
- Forward safety: Data written by a newer schema version (for example
v: 3opened byschemaVersion: 2code) is returned as-is and never down-migrated.
Declaring migrations in defineBlock
Set schemaVersion (or manifest.schemaVersion) to the target integer (>= 1), and provide a migrations map keyed by fromVersion, where migrations[n] upgrades data from n to n + 1:
import { defineBlock, useOrbixState, type BlockRenderProps } from '@orbixdocs/sdk';
// v1 stored: { notes: string }
// v2 stores: { entries: Array<{ id: string; body: string }>, showArchived: boolean }
interface NotesStateV2 {
entries: Array<{ id: string; body: string }>;
showArchived: boolean;
}
export default defineBlock({
manifest: {
id: 'acme.release-notes',
name: 'Release Notes',
version: '2.0.0',
sdk: '^3.0.0',
schemaVersion: 2,
},
schemaVersion: 2,
migrations: {
// Upgrades stored v1 data -> v2
1: (v1Data: { notes?: string }) => {
const legacyText = typeof v1Data?.notes === 'string' ? v1Data.notes.trim() : '';
return {
entries: legacyText ? [{ id: 'migrated-1', body: legacyText }] : [],
showArchived: false,
};
},
},
component(props: BlockRenderProps) {
const [state, setState] = useOrbixState<NotesStateV2>(props, {
entries: [],
showArchived: false,
});
return (
<div>
<div>{state.entries.length} note(s)</div>
<button
type="button"
disabled={props.isReadOnly}
onClick={() =>
setState((prev) => ({
...prev,
entries: [
...prev.entries,
{ id: String(Date.now()), body: 'New entry' },
],
}))
}
>
Add entry
</button>
</div>
);
},
});Rules for safe migrations
- Keep migrations pure and synchronous. Do not call network APIs, read
localStorage, or mutate the input object in place — always return the new state object. - Keep old step functions forever. Users who have not opened an old page since
v1will jump1 -> 2 -> 3when they open it underschemaVersion: 3. Removing step1breaks that chain. - Guard every field on
oldData. Legacy payloads may haveundefinedor unexpected types; default missing arrays or strings defensively.
Unit testing migrations with migrateStoredValue
Test every migration path — legacy unversioned payloads, versioned envelopes, and corrupt inputs — directly in Vitest using migrateStoredValue:
import {
registerBlockMigrations,
migrateStoredValue,
wrapEnvelope,
} from '@orbixdocs/sdk';
registerBlockMigrations('acme.release-notes', {
schemaVersion: 2,
migrations: {
1: (d: { notes?: string }) => ({
entries: d?.notes ? [{ id: 'migrated-1', body: d.notes }] : [],
showArchived: false,
}),
},
});
// 1. Legacy unversioned v1 object upgrades to v2
const fromLegacy = migrateStoredValue('acme.release-notes', { notes: 'Ship v2' });
console.assert(fromLegacy.changed === true);
console.assert(fromLegacy.fromVersion === 1 && fromLegacy.toVersion === 2);
console.assert(fromLegacy.value.entries[0]?.body === 'Ship v2');
// 2. Current v2 envelope is untouched
const currentEnv = wrapEnvelope('acme.release-notes', {
entries: [],
showArchived: true,
});
const unchanged = migrateStoredValue('acme.release-notes', currentEnv);
console.assert(unchanged.changed === false);