Schema Migration
When your data shape changes between app versions, Mnemonic's schema registry
and migration rules handle the upgrade automatically. For field-level policy
changes that should apply after reading persisted data, use reconcile.
Schema registry
A schema registry stores versioned schemas for each key and resolves migration
paths to upgrade stored data. For the common immutable case, use
createSchemaRegistry(...) instead of hand-rolling the indexing boilerplate.
import {
createSchemaRegistry,
MnemonicProvider,
useMnemonicKey,
insertChildIfMissing,
renameNode,
dedupeChildrenBy,
type KeySchema,
type MigrationRule,
type StructuralTreeHelpers,
} from "react-mnemonic/schema";
Registering schemas
const schemas: KeySchema[] = [
{
key: "profile",
version: 1,
schema: {
type: "object",
properties: { name: { type: "string" }, email: { type: "string" } },
required: ["name", "email"],
},
},
{
key: "profile",
version: 2,
schema: {
type: "object",
properties: {
name: { type: "string" },
email: { type: "string" },
migratedAt: { type: "string" },
},
required: ["name", "email", "migratedAt"],
},
},
];
Adding migrations
Migrations define how to transform data from one version to the next:
const migrations: MigrationRule[] = [
{
key: "profile",
fromVersion: 1,
toVersion: 2,
migrate: (value) => {
const v1 = value as { name: string; email: string };
return { ...v1, migratedAt: new Date().toISOString() };
},
},
];
const registry = createSchemaRegistry({
schemas,
migrations,
});
When a component reads a v1 profile from storage, Mnemonic automatically runs the migration to produce a v2 value.
createSchemaRegistry validates duplicate schemas and ambiguous migration
graphs up front. If you need runtime schema registration for
schemaMode="autoschema", keep a custom mutable SchemaRegistry
implementation instead of the immutable helper.