travels3.0
Migration

Migration Guide

Upgrade to Travels 3 or migrate from snapshot-based history libraries.

From 2.x to 3.0

Travels 3 separates state ownership, external journals, shared views, and persistence restoration into distinct public capabilities.

Create timelines through factories

Travels is no longer constructible. It remains the namespace for Travels.deserialize().

// 2.x
const travels = new Travels(initialState, options);

// 3.0
const travels = createTravels(initialState, options);

instanceof Travels no longer works: the right-hand side is a plain object, so the expression throws TypeError at runtime and fails to compile in TypeScript. Detect state-owning timelines with isTravels() instead:

// 2.x
if (value instanceof Travels) value.back();

// 3.0
if (isTravels(value)) value.back();

Timelines remain ordinary extensible objects, so the method-wrapping patterns in the Advanced Patterns Guide keep working, and internal calls such as back() still go through a wrapped go(). Their constructor is not a public entry point: calling new travels.constructor(...) throws INVALID_OPERATION instead of bypassing factory validation.

Use createPatchableTravels() when the initial state should be constrained to the durable JSON-shaped state contract at compile time and checked immediately at runtime.

Choose one state owner

A state-owning timeline created with createTravels() exposes state updates but no recordPatches(). An externally owned timeline created with createTravelJournal() exposes recordPatches(), navigation, and reset, but none of the state-owning update methods.

const journal = createTravelJournal(authoritativeState, {
  apply(transition) {
    authoritativeState = commitThroughOwner(transition.patches);
    return authoritativeState;
  },
});

journal.recordPatches(nextState, {
  patches,
  inversePatches,
  metadata: { label: 'External edit' },
});

Remove controlledApply from ordinary TravelsOptions. State-only methods are absent from the returned journal object instead of existing as methods that throw when called. Ownership-specific options now fail closed at runtime: apply belongs only to journal factories, while mutable belongs only to state-owning factories.

Manual archive capabilities now follow the same rule. archive() and canArchive() exist only when the factory receives autoArchive: false; an automatic timeline omits both methods at runtime and in TypeScript instead of retaining a warning-only archive() method.

Journal generics now use the same <S, F, A, P> order as Travels. Most call sites infer these parameters and need no change. If v2 code supplied patch options explicitly as the third parameter, insert the archive mode before them:

// 2.x
type Journal = TravelJournal<State, false, StringPatchOptions>;

// 3.0
type Journal = TravelJournal<State, false, true, StringPatchOptions>;

Controls types no longer carry the auto-freeze parameter, which no member used. Drop the second type argument:

// 2.x
type Controls = RebasableTravelsControls<State, false, StringPatchOptions>;

// 3.0
type Controls = RebasableTravelsControls<State, StringPatchOptions>;

The same applies to TravelsControls, ManualTravelsControls, and RebasableManualTravelsControls. The unused Value and InitialValue helper types have been removed; use S or ReadonlyState<S> directly.

Remove auto-freeze from mutable timelines

createTravels(), createPatchableTravels(), and restoreTravels() reject enableAutoFreeze: true together with mutable: true with INVALID_OPTION. Mutable mode updates the live state in place, and in 2.x freezing each produced state also froze the parts it shared with that live state, so the next update that wrote to them threw a TypeError. Remove enableAutoFreeze from mutable timelines:

// 2.x
const travels = new Travels(store, { mutable: true, enableAutoFreeze: true });

// 3.0
const travels = createTravels(store, { mutable: true });

TypeScript reports the pair when enableAutoFreeze is the literal true, even with a mutable flag typed as boolean. A freeze flag computed at runtime is rejected when the timeline is created.

Treat shared views as read-only

getHistory() now returns readonly ReadonlyState<S>[] through both the instance and controls surfaces, so both the shared array and its entries are read-only in TypeScript. TravelsControls properties and methods are read-only and the controls object is frozen in every build. Observer events expose state as a borrowed ReadonlyState<S> view and patches as ReadonlyTravelPatches; their lazily materialized patch containers, groups, operations, and array paths are also frozen.

const visible = travels.getControls().getHistory(); // readonly ReadonlyState<State>[]
const owned = travels.getHistorySnapshot(); // State[]; detached and mutable

controls.patches is now a cached, frozen ReadonlyTravelPatches view instead of a fresh deep clone on every read. It keeps its reference until history changes. Code that edited the returned object must copy it first with travels.getPatches().

Patch operation values can contain nested objects, so observers should still treat the complete event as read-only. Use getPatches() for a detached, caller-owned retained-history snapshot.

Restore through one validated path

Remove the state-less TravelsHistory input type plus history, initialPatches, initialPosition, and strictInitialPatches. Decode stored input with Travels.deserialize() and restore the complete snapshot atomically:

const history = Travels.deserialize<State>(stored, {
  validation: 'semantic',
  fallback: emptySnapshot,
});

const travels = restoreTravels(history);

Malformed snapshots now throw rather than being discarded. Use Travels.deserialize(..., { fallback }) when recovery is intentional.

The standalone deserializeTravelsHistory() export duplicated Travels.deserialize() and has been removed; call Travels.deserialize() with the same arguments.

restoreTravels() keeps a detached copy of snapshot.state; it never mutates the snapshot or a reused fallback. Mutable integrations that attached history to a live observable store must name that store as the restore target:

// 2.x
const travels = new Travels(store, {
  mutable: true,
  history: Travels.deserialize(stored),
});

// 3.0
const travels = restoreTravels(Travels.deserialize(stored), {
  mutable: true,
  target: store,
});

Travels overwrites target in place with the snapshot state, so the store no longer has to be pre-populated to match the restored history.

Upgrade the official bindings

use-travel@3 creates component-owned timelines through createTravels(). For a restored shared timeline, restore outside React and pass the instance to useTravelStore():

const snapshot = Travels.deserialize<State>(stored);
const timeline = restoreTravels(snapshot);

function Editor() {
  const [state, setState, controls] = useTravelStore(timeline);
  // ...
}

zustand-travel@3 restores one complete serialized history through its exclusive snapshot option while Zustand remains the state owner. A state-owning Travels instance is intentionally rejected. The initializer still defines action functions; the snapshot supplies the data baseline:

const snapshot = Travels.deserialize<State>(stored);

const useStore = create<State & Actions>()(
  travel(
    (set) => ({
      ...defaultState,
      updateTitle: (title) =>
        set((state) => {
          state.title = title;
        }),
    }),
    { snapshot }
  )
);

use-travel@3 requires travels@^3.0.0, while zustand-travel@3 requires travels@^3.0.1; installing travels@^3.0.1 satisfies both. Publish or install the core major first, then upgrade each binding. This keeps the factory overloads, restoreTravels() boundary, read-only shared views, and returned controls on one versioned contract instead of making their behavior depend on peer resolution.

With autoArchive: false, navigating while changes are pending archives them as part of the navigation. 2.x published an archive event followed by a go event; 3.0 stages the pending entry until the navigation succeeds and publishes one go event, advancing getRevision() once, in both immutable and mutable mode. Listeners that persisted only on archive should persist on every committed event:

// 2.x
travels.subscribe(({ type }) => {
  if (type === 'archive') save(travels.serialize());
});

// 3.0
travels.subscribe(() => save(travels.serialize()));

Upgrade Mutative to 2

Travels 3 requires mutative@^2.0.0 as its peer dependency. Upgrade it together with Travels:

npm install travels@3 mutative@2

Mutative 2 keeps the API that Travels uses, and Travels needs no option changes. Mutative 1.x patches could not undo some updates correctly, such as an array shortened and lengthened again in one recipe, which undo restored with holes, or an element changed from 0 to -0, which undo left as -0. Mutative 2 records both.

Check your build for the Mutative 2 runtime changes that reach applications through Travels:

  • Mutative 2 builds target ES2018. Transpile mutative for engines that support Proxy but not ES2018 syntax.
  • Mutative reads process.env.NODE_ENV to select its development or production build. Define it in every bundle, including bundles that target Node.js. To load ES modules without a bundler, map mutative to mutative/dist/mutative.esm.production.min.mjs, or load its UMD build with Travels' UMD build.
  • Mutative 2 patches hold the objects of the next state as their values instead of deep copies. In immutable mode, an object read from getState() is therefore also part of the retained history, and mutating it outside Travels rewrites what redo replays. Treat state as read-only, or enable enableAutoFreeze to make such mutations throw. Mutable mode is unaffected, because it stores detached patch values.
  • Production builds of Mutative throw Minified Mutative error #<code> instead of full messages. Match error codes, not message text, in production.
  • If your own code calls Mutative, review its v1 to v2 migration guide.

Update observer and runtime compatibility

Use TravelsEvent for both subscribers and devtools. The deprecated TravelsDevtoolsEvent alias and the listener-arity-based LEGACY_SUBSCRIBER warning have been removed. Positional listeners must be rewritten to accept the single event object.

Travels 3 requires Node.js 22 or newer and is tested on Node.js 22 and 24.

From Redux-undo

Redux-undo stores whole state snapshots. Travels stores JSON Patch entries.

  1. Keep your existing reducer or state updater as the source of state changes.
  2. Create a Travels instance with the reducer state.
  3. Replace UNDO / REDO dispatches with travels.back() / travels.forward().
  4. Use metadata labels for undo menu text.
  5. Persist with travels.serialize() instead of storing the whole Redux-undo history object.

Snapshot stacks can still be better for small state and short local-only history. Travels is strongest when serialized history size matters.

From Zundo

Zundo integrates directly with Zustand stores. Travels can be used as a separate history engine:

  1. Keep Zustand as the UI store.
  2. Call travels.setState(...) inside store actions.
  3. Sync travels.getState() back into Zustand after state changes.
  4. Use Travels.deserialize(...) and restoreTravels(...) for persisted history.

See examples/zustand.ts.

From use-travel

use-travel is a React hook wrapper. Use Travels directly when you need framework-agnostic control, persistence adapters, metadata, or custom store integration.

  1. Create const travels = createTravels(initialState).
  2. Subscribe with useSyncExternalStore(travels.subscribe, travels.getRevision) and read travels.getState() while rendering.
  3. Expose travels.getControls() to components.
  4. Use serialize() / Travels.deserialize() for reloads.

See examples/react-integration.tsx.

From Positional Subscribe Callbacks

Subscribers now receive the same TravelsEvent object as the devtools hook. Replace positional callback parameters with event destructuring:

// Before
travels.subscribe((state, patches, position, historyLength) => {
  render(state, position);
});

// After
travels.subscribe(
  ({ type, state, patches, position, historyLength, metadata }) => {
    render(state, position);
  }
);

One shallow-frozen event object is shared by all observers for a notification. Its patches property remains an event-local delta and is materialized lazily; the patch containers, groups, operations, and array paths are frozen. Top-level metadata is cloned and frozen on first access. Nested patch values and metadata are event-local but shared by its observers; treat them as read-only. Call travels.getPatches() when full retained history is required. TravelsDevtoolsEvent was a deprecated alias in 2.x and is removed in 3.0. Callbacks that ignore their arguments, such as external store invalidation functions, can remain unchanged.

From Map/Set State

Travels no longer supports Map or Set in either immutable or mutable state. Initial state and updates fail fast, and restored state or patch payloads containing collections are rejected during structural validation. Normalize collections before creating or updating a Travels instance:

type Item = { id: string; title: string };

type LegacyState = {
  itemsById: Map<string, Item>;
  selectedIds: Set<string>;
};

type TravelsState = {
  itemsById: Record<string, Item>;
  selectedIds: string[];
};

declare const legacyState: LegacyState;

const normalizeState = (state: LegacyState): TravelsState => ({
  itemsById: Object.fromEntries(state.itemsById),
  selectedIds: Array.from(state.selectedIds),
});

const travels = createTravels(normalizeState(legacyState));

Use stable string IDs before converting Maps with non-string or object keys. Keep any Map/Set view required by the application outside Travels and derive it from the normalized state.

Do not replay old patch history generated from Map/Set mutations. Such history can contain collection-specific values or non-JSON path locators whose reference identity cannot be migrated reliably. Decode the legacy record outside Travels, materialize its authoritative current state, normalize that state, and create a new history baseline. A persistence codec may convert between application-domain collections and storage, but its output passed to Travels must remain in the supported JSON-shaped contract.

Persistence Migration

Older hand-rolled persistence usually saved { state, patches, position }. Convert it with migrate:

Travels 3 has one restore path. Pass the complete result of Travels.deserialize(...) to restoreTravels(); the former history, initialPatches, initialPosition, and strictInitialPatches options no longer exist. Malformed snapshots throw instead of silently starting with an empty timeline.

const history = Travels.deserialize<State>(stored, {
  validation: 'semantic',
});

const travels = restoreTravels(history);

Migration and function-valued fallback callbacks must return synchronously. Complete asynchronous storage or network work before calling Travels.deserialize(...); Promise-like callback results are rejected as MIGRATION_FAILED or FALLBACK_FAILED without leaking an unhandled rejection.

type CurrentSnapshot = TravelsSerializedHistory<TravelsState>;

const history = Travels.deserialize<TravelsState>(stored, {
  validation: 'semantic',
  migrate(snapshot) {
    if (snapshot && typeof snapshot === 'object' && !('version' in snapshot)) {
      const legacy = snapshot as Omit<CurrentSnapshot, 'version'>;

      return {
        version: 1,
        state: legacy.state,
        patches: legacy.patches,
        position: legacy.position,
      };
    }

    return snapshot as CurrentSnapshot;
  },
});

On this page