Skip to Content
OrbixDocs
Block SDK · Guides

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:

  1. Legacy unversioned values (anything without __orbixEnv: 1) are treated as version 1 (LEGACY_VERSION = 1).
  2. Step-by-step upgrade: If the stored version v is lower than the block's current schemaVersion, the SDK runs migrations[v], migrations[v + 1], and so on until v === schemaVersion. Each step receives a structuredClone copy of the data and { blockType, from, to }.
  3. Write-back: When changed is true, the upgraded envelope is written back to storage.
  4. 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.
  5. Forward safety: Data written by a newer schema version (for example v: 3 opened by schemaVersion: 2 code) 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:

src/index.tsx
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 v1 will jump 1 -> 2 -> 3 when they open it under schemaVersion: 3. Removing step 1 breaks that chain.
  • Guard every field on oldData. Legacy payloads may have undefined or 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:

src/__tests__/migrations.test.ts
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);

On this page