Fabric.js has no built-in history. You get canvas.on(...) events and a serializer, and that is all. The first version most people write is one of two things: push a snapshot on every event, or keep a list of commands. Both work for a demo and then break in specific ways.

Snapshot on every event fills the stack with dozens of entries per drag, so one Ctrl+Z moves an object by one pixel. Command objects are harder to get right with Fabric because a single user action often touches several objects, and the restore path fires the same events as the user does, so undo quietly writes new history on top of itself.

This post covers the approach I use in Kanvaskit, a React 19 and Fabric.js 7 editor starter. It is a snapshot approach with a few rules about which events count, how to group actions, and how to keep restores out of the history.

The snapshot stacks

Each history entry is the canvas serialized to JSON. The hook keeps three things: a stack of past states, a stack of future states, and the state the canvas is in right now.

import { useCallback, useEffect, useRef, type RefObject } from 'react'; import type { Canvas } from 'fabric'; const HISTORY_LIMIT = 50; const CUSTOM_PROPS = ['id', 'name']; export function useCanvasHistory(canvasRef: RefObject<Canvas | null>) { const past = useRef<string[]>([]); const future = useRef<string[]>([]); const current = useRef<string | null>(null); const isRestoring = useRef(false); const isBatching = useRef(false); const snapshot = useCallback((): string | null => { const canvas = canvasRef.current; if (!canvas) return null; return JSON.stringify(canvas.toObject(CUSTOM_PROPS)); }, [canvasRef]); // Call once after the initial scene is loaded, so the first edit has a "before" state. const baseline = useCallback(() => { current.current = snapshot(); past.current = []; future.current = []; }, [snapshot]); const record = useCallback(() => { const json = snapshot(); if (json === null || json === current.current) return; if (current.current !== null) { past.current.push(current.current); if (past.current.length > HISTORY_LIMIT) past.current.shift(); } current.current = json; future.current = []; // a new change ends any redo chain }, [snapshot]); const restore = useCallback(async (json: string) => { const canvas = canvasRef.current; if (!canvas) return; isRestoring.current = true; try { await canvas.loadFromJSON(json); canvas.requestRenderAll(); current.current = json; } finally { isRestoring.current = false; } }, [canvasRef]); const undo = useCallback(async () => { const prev = past.current.pop(); if (prev === undefined || current.current === null) return; future.current.push(current.current); await restore(prev); }, [restore]); const redo = useCallback(async () => { const next = future.current.pop(); if (next === undefined || current.current === null) return; past.current.push(current.current); await restore(next); }, [restore]); const onChange = useCallback(() => { if (isRestoring.current || isBatching.current) return; record(); }, [record]); const beginBatch = useCallback(() => { isBatching.current = true; }, []); const commitBatch = useCallback(() => { isBatching.current = false; record(); // one snapshot for the whole batch }, [record]); useEffect(() => { const canvas = canvasRef.current; if (!canvas) return; const events = ['object:added', 'object:removed', 'object:modified', 'text:editing:exited']; events.forEach((name) => canvas.on(name, onChange)); return () => events.forEach((name) => canvas.off(name, onChange)); }, [canvasRef, onChange]); return { baseline, undo, redo, beginBatch, commitBatch }; } 

The stacks hold strings, so memory stays small. Fifty scenes of a few hundred objects each is still a modest amount of JSON.

Save on the right events

The events that matter are object:added, object:removed and object:modified. Each one fires once per completed action.

Do not listen to object:moving or object:scaling. They fire on every mouse move during a drag, so a single drag would create dozens of history entries. object:modified fires once when the user releases the mouse, which is the point where a change is complete.

Text is different. While a user types into an IText, no object event fires for each keystroke, so the history would miss the edit entirely. Fabric fires text:editing:exited on the canvas when editing ends, and the hook saves there.

Batch multi-step actions

Some actions touch several objects. "Align five objects to the left" fires object:modified five times. Without grouping, one undo reverts one object, which is confusing.

beginBatch() turns off recording and commitBatch() turns it back on and takes one snapshot:

import type { Canvas, FabricObject } from 'fabric'; export function alignLeft( canvas: Canvas, history: { beginBatch: () => void; commitBatch: () => void }, ) { const objects: FabricObject[] = canvas.getActiveObjects(); if (objects.length < 2) return; const left = Math.min(...objects.map((o) => o.left ?? 0)); history.beginBatch(); try { for (const obj of objects) { obj.set({ left }); obj.setCoords(); } canvas.requestRenderAll(); } finally { history.commitBatch(); } } 

The try/finally matters. If a batch never closes, every later change is silently dropped from history, and the bug is hard to trace.

Lock history during restore

This is the rule that breaks the most editors. loadFromJSON is async in Fabric 7 and returns a Promise. It clears the canvas and re-adds every object, which fires object:added for each one. If the hook records those events, undo pushes a new entry, the redo stack is cleared, and the next Ctrl+Shift+Z does nothing.

The isRestoring flag in the hook above handles this. It is set before the load, cleared in finally, and onChange ignores events while it is set. The await is required: if you clear the flag before the Promise resolves, the events from the load arrive after the flag is down.

Keyboard shortcuts

Shortcuts should not fire while the user is typing. Ctrl+Z inside a text field should undo the text, and Ctrl+Z while an IText is in edit mode should undo characters, not canvas changes.

import { useEffect, type RefObject } from 'react'; import { IText, type Canvas } from 'fabric'; export function useHistoryShortcuts( canvasRef: RefObject<Canvas | null>, handlers: { undo: () => void; redo: () => void }, ) { useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { const target = e.target as HTMLElement | null; if (target && (target.isContentEditable || target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) { return; } const active = canvasRef.current?.getActiveObject(); if (active instanceof IText && active.isEditing) return; const mod = e.ctrlKey || e.metaKey; const key = e.key.toLowerCase(); if (mod && key === 'z' && !e.shiftKey) { e.preventDefault(); handlers.undo(); } else if ((mod && key === 'z' && e.shiftKey) || (e.ctrlKey && key === 'y')) { e.preventDefault(); handlers.redo(); } }; window.addEventListener('keydown', onKeyDown); return () => window.removeEventListener('keydown', onKeyDown); }, [canvasRef, handlers]); } 

Wire it up in the editor component. handlers should be stable (wrap them in useCallback or useMemo), or the listener is removed and re-added on every render.

const canvasRef = useFabricCanvas(elRef); const history = useCanvasHistory(canvasRef); useHistoryShortcuts(canvasRef, useMemo(() => ({ undo: history.undo, redo: history.redo }), [history.undo, history.redo])); 

Clear the redo stack on a new change

This is already handled in record(): any new change empties future. The rule is simple and easy to forget when you add a new kind of change later. If a user undoes three steps, then moves an object, the three undone steps must be gone. Keeping them would let redo bring back states that no longer follow from the current canvas.

Wrapping up

The whole thing is one hook, one batch helper, and one shortcut listener. The rules that matter are the ones that are easy to get wrong: ignore move and scale events, save on text edit exit, group multi-object actions, and keep restores out of the history with an awaited flag.

I'm building Kanvaskit, a React 19 + Fabric.js 7 editor starter. The free version, Kanvaskit Lite, is at https://github.com/debojitsaha/kanvaskit-lite

If you want the Pro version when it's out, the waitlist is here: https://tally.so/r/kbNOgR?utm_source=devto&utm_medium=article&utm_campaign=undo-redo