# Save conflicts

> Detect a canvas editor save conflict when two tabs or devices edit one document. Revision checks stop silent overwrites and let the user choose.

Source: https://fabricjs-document-engine.jscrate.dev/docs/guides/save-conflicts
Last updated: 2026-09-28

A canvas editor save conflict happens when someone else saved the same document after you opened it. Without a check, the last save silently wins and the other person's work is gone. The engine uses a revision number to catch this.

## Try it

Draw in tab A and save. Then draw in tab B and save. Tab B gets a conflict, and you choose what to keep.

```tsx
"use client";

import {
  useDocumentEngine,
  useDocumentState,
} from "fabricjs-document-engine/react";
import { createMemoryStorage } from "fabricjs-document-engine/storage";
import {
  PencilIcon,
  RotateCcwIcon,
  SaveIcon,
  ShieldCheckIcon,
} from "lucide-react";
import { useTranslations } from "next-intl";

import { DemoCanvas, newShape, Status, ToolButton } from "./demo-ui";
import { useFabricCanvas } from "./use-fabric-canvas";

// Both editors save to the same storage, like two tabs of one app.
const storage = createMemoryStorage();
const DOCUMENT_ID = "conflict-demo";
const TONE = {
  saved: "ok",
  saving: "busy",
  unsaved: "idle",
  conflict: "error",
  error: "error",
} as const;

function Tab({ name, color }: { name: string; color: string }) {
  const t = useTranslations("demos");
  const { elementRef, canvas } = useFabricCanvas();
  const engine = useDocumentEngine(canvas, {
    storage,
    document: { id: DOCUMENT_ID },
  });
  const state = useDocumentState(engine);
  const status = state?.saveStatus ?? "saved";
  const conflict = status === "conflict";

  return (
    <div className="flex min-w-0 flex-col gap-2">
      <p className="text-[13px] font-medium">{t("conflict.tab", { name })}</p>
      <DemoCanvas elementRef={elementRef} label={t("conflict.tab", { name })} />

      {/* The conflict actions are always there, so the layout never jumps. */}
      <div className="grid grid-cols-2 gap-1.5">
        <ToolButton
          icon={PencilIcon}
          label={t("conflict.draw")}
          onClick={() => canvas?.add(newShape("square", color))}
        />
        <ToolButton
          icon={SaveIcon}
          label={t("conflict.save")}
          primary
          disabled={!state?.isDirty || conflict}
          onClick={() => void engine?.save().catch(() => undefined)}
        />
        <ToolButton
          icon={RotateCcwIcon}
          label={t("conflict.reload")}
          disabled={!conflict}
          onClick={() =>
            void engine?.load(DOCUMENT_ID, { discardUnsavedChanges: true })
          }
        />
        <ToolButton
          icon={ShieldCheckIcon}
          label={t("conflict.keepMine")}
          disabled={!conflict}
          onClick={() => void engine?.save({ overwrite: true })}
        />
      </div>

      <Status tone={TONE[status]}>
        {t(`conflict.status.${status}`, { revision: state?.revision ?? 0 })}
      </Status>
    </div>
  );
}

export default function SaveConflictDemo() {
  return (
    <div className="grid w-full max-w-md grid-cols-2 gap-3 text-left">
      <Tab name="A" color="#f2836f" />
      <Tab name="B" color="#6f00ff" />
    </div>
  );
}
```

```tsx
import { Canvas } from "fabric";
import { useLayoutEffect, useRef, useState } from "react";

/**
 * The page every demo draws on. The document keeps this size; CSS scales the
 * canvas down to fit its card, so saved documents and exports never depend on
 * the screen.
 */
export const PAGE = { width: 480, height: 300 };

// Selection handles in the site's style. Fabric does not save these.
const SELECTION = {
  borderColor: "#6f00ff",
  borderScaleFactor: 1.5,
  borderOpacityWhenMoving: 0.5,
  cornerStyle: "circle",
  cornerSize: 11,
  cornerColor: "#ffffff",
  cornerStrokeColor: "#6f00ff",
  transparentCorners: false,
} as const;

export function styleSelection(canvas: Canvas) {
  canvas.set({
    selectionColor: "rgba(111, 0, 255, 0.06)",
    selectionBorderColor: "#6f00ff",
    selectionLineWidth: 1,
  });
  const style = () => canvas.getActiveObject()?.set(SELECTION);
  canvas.on("selection:created", style);
  canvas.on("selection:updated", style);
}

/**
 * Creates a Fabric.js canvas once the `<canvas>` element exists, and disposes
 * it on unmount. The engine is created from the returned `canvas`.
 */
export function useFabricCanvas({ width, height } = PAGE) {
  const elementRef = useRef<HTMLCanvasElement>(null);
  const [canvas, setCanvas] = useState<Canvas | null>(null);

  // A layout effect creates the canvas before the first paint.
  useLayoutEffect(() => {
    const created = new Canvas(elementRef.current!, {
      width,
      height,
      backgroundColor: "#ffffff",
    });
    styleSelection(created);
    setCanvas(created);

    return () => {
      // Dispose after the engine's own cleanup, so its last recovery copy
      // still sees the objects.
      setTimeout(() => created.dispose().catch(() => undefined));
    };
  }, [width, height]);

  return { elementRef, canvas };
}
```

```tsx
import { Circle, type FabricObject, Rect, Triangle } from "fabric";
import type { LucideIcon } from "lucide-react";

import { cn } from "@/lib/utils";

import { PAGE } from "./use-fabric-canvas";

export const COLORS = ["#f2836f", "#5fe6c4", "#7ad9ec", "#6f00ff", "#ffd666"];

// Demo shapes are placed by their top-left corner, like a design tool.
const CORNER = { originX: "left", originY: "top" } as const;

/** A new shape at a random spot on the page. */
export function newShape(kind: "square" | "circle", fill?: string) {
  const left = 40 + Math.random() * (PAGE.width - 160);
  const top = 30 + Math.random() * (PAGE.height - 120);
  const color = fill ?? COLORS[Math.floor(Math.random() * COLORS.length)];
  return kind === "square"
    ? new Rect({
        ...CORNER,
        left,
        top,
        width: 88,
        height: 64,
        rx: 10,
        ry: 10,
        fill: color,
      })
    : new Circle({ ...CORNER, left, top, radius: 34, fill: color });
}

/** A small composed drawing, so no demo starts on an empty page. */
export function seedShapes(): FabricObject[] {
  return [
    new Rect({
      ...CORNER,
      left: 48,
      top: 56,
      width: 176,
      height: 124,
      rx: 16,
      ry: 16,
      fill: COLORS[4],
    }),
    new Circle({ ...CORNER, left: 268, top: 44, radius: 58, fill: COLORS[0] }),
    new Rect({
      ...CORNER,
      left: 256,
      top: 196,
      width: 176,
      height: 52,
      rx: 26,
      ry: 26,
      fill: COLORS[1],
    }),
    new Triangle({
      ...CORNER,
      left: 96,
      top: 196,
      width: 72,
      height: 60,
      fill: COLORS[3],
    }),
  ];
}

export function DemoFrame({
  className,
  ...props
}: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "flex w-full max-w-md flex-col gap-3 text-left outline-none",
        className
      )}
      {...props}
    />
  );
}

/**
 * Scales the fixed-size Fabric canvas to the frame's width. The rules are
 * `!important` because Fabric writes its sizes as inline styles.
 */
export function DemoCanvas({
  elementRef,
  label,
  page = PAGE,
  children,
}: {
  elementRef: React.Ref<HTMLCanvasElement>;
  label: string;
  page?: { width: number; height: number };
  children?: React.ReactNode;
}) {
  return (
    <div
      className="relative overflow-hidden rounded-lg border bg-white shadow-xs [&_.canvas-container]:aspect-(--page)! [&_.canvas-container]:h-auto! [&_.canvas-container]:w-full! [&_canvas]:h-full! [&_canvas]:w-full!"
      style={
        { "--page": `${page.width} / ${page.height}` } as React.CSSProperties
      }
    >
      <div>
        <canvas ref={elementRef} aria-label={label} />
      </div>
      {children}
    </div>
  );
}

export function Toolbar({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("flex flex-wrap items-center gap-1.5", className)}
      {...props}
    />
  );
}

export function ToolButton({
  icon: Icon,
  label,
  iconOnly = false,
  primary = false,
  className,
  ...props
}: React.ComponentProps<"button"> & {
  icon: LucideIcon;
  label: string;
  iconOnly?: boolean;
  primary?: boolean;
}) {
  return (
    <button
      type="button"
      title={label}
      aria-label={iconOnly ? label : undefined}
      className={cn(
        "inline-flex h-8 min-w-0 items-center justify-center gap-1.5 rounded-md border px-2.5 text-[13px] font-medium whitespace-nowrap transition-colors disabled:pointer-events-none disabled:opacity-40 [&_svg]:size-3.5 [&_svg]:shrink-0",
        primary
          ? "border-transparent bg-foreground text-background hover:bg-foreground/85"
          : "bg-background hover:bg-muted",
        iconOnly && "w-8 px-0",
        className
      )}
      {...props}
    >
      <Icon aria-hidden />
      {!iconOnly && <span className="truncate">{label}</span>}
    </button>
  );
}

const TONES = {
  idle: "bg-zinc-400",
  busy: "bg-amber-400",
  ok: "bg-emerald-500",
  error: "bg-red-500",
};

/** One line of status text. Its height never changes, so the card never jumps. */
export function Status({
  tone = "idle",
  children,
}: {
  tone?: keyof typeof TONES;
  children: React.ReactNode;
}) {
  return (
    <p
      role="status"
      className="flex h-5 min-w-0 items-center gap-2 text-[13px] text-muted-foreground"
    >
      <span
        aria-hidden
        className={cn("size-1.5 shrink-0 rounded-full", TONES[tone])}
      />
      <span className="truncate">{children}</span>
    </p>
  );
}
```

## How revisions work

Every saved document has a `revision` number. When the engine saves, it tells your storage adapter the revision it last saw, in `expectedRevision`. If the stored revision is different, someone saved in between, and the adapter refuses with `SAVE_CONFLICT`.

The built-in adapters already do this. For your own backend, see [custom backend](https://fabricjs-document-engine.jscrate.dev/docs/storage/custom-backend).

## Handle a conflict

The save fails with `SAVE_CONFLICT`, and `status` becomes `conflict`. Conflicts are never retried. Ask the user what to do:

```ts
engine.on("save:error", async ({ error }) => {
  if (error.code !== "SAVE_CONFLICT") return;

  const keepMine = await askUser("Someone else saved this document.", [
    "Keep my version",
    "Load their version",
  ]);

  if (keepMine) {
    await engine.save({ overwrite: true });
  } else {
    const { id } = engine.getDocumentInfo();
    await engine.load(id, { discardUnsavedChanges: true });
  }
});
```

- `save({ overwrite: true })` skips the check. Your storage receives `expectedRevision: null`.
- `load(id, { discardUnsavedChanges: true })` throws your changes away and opens the saved version.

## Multiple tabs of one user

Most conflicts come from multiple tabs of the same person, not from two people. The same check covers both. If you see a canvas editor save conflict inside a single tab, your adapter is not returning the new revision. Return `{ revision }` from `saveDocument`, or store `document.revision`.

## After a crash

A document restored from [recovery](https://fabricjs-document-engine.jscrate.dev/docs/guides/recovery) keeps the revision it was based on. If the server moved on in the meantime, the next save reports a conflict instead of overwriting newer work.
