Fabric.js Document Engine

Search documentation

Find a page or section

中文

Storage adapters

View as Markdown

Where documents are saved, and how to pick the right storage adapter.

A storage adapter tells the engine where documents live. It is how you save a Fabric.js canvas to a database, to the browser, or to anything else. No hosted service is involved.

Built-in adapters

import {
  createLocalStorage,
  createMemoryStorage,
} from "fabricjs-document-engine/storage";
 
const engine = createDocumentEngine({
  canvas,
  storage: createLocalStorage({ prefix: "my-app:" }),
  autosave: true,
});
 
await engine.load("project-42");
await engine.save();
AdapterKeeps documents inGood for
createLocalStorage()The browser's localStoragePrototypes and offline tools
createMemoryStorage()Memory, gone on refreshTests and demos
createKeyValueStorage(store, prefix)Any key-value store you passsessionStorage and similar

All three check revisions, support versions, and add listDocuments() and deleteDocument(id):

const storage = createLocalStorage({ prefix: "my-app:" });
const ids = await storage.listDocuments();
await storage.deleteDocument("old-draft");

localStorage holds about 5 MB per site. For large drawings or many documents, save to your own backend.

Any key-value store

createKeyValueStorage adds revision checks, listing and versions on top of any synchronous store:

import { createKeyValueStorage } from "fabricjs-document-engine/storage";
 
const sessionStore = createKeyValueStorage(
  {
    read: (key) => sessionStorage.getItem(key),
    write: (key, value) => sessionStorage.setItem(key, value),
    remove: (key) => sessionStorage.removeItem(key),
    keys: () => Object.keys(sessionStorage),
  },
  "my-app:"
);

Save a Fabric.js canvas to a database

For a real product, write a storage adapter for your REST API. It is two functions:

import type { DocumentStorage } from "fabricjs-document-engine";
 
const storage: DocumentStorage = {
  async loadDocument(id) {
    const response = await fetch(`/api/documents/${id}`);
    return response.json();
  },
  async saveDocument(document, { expectedRevision, signal }) {
    await fetch(`/api/documents/${document.id}`, {
      method: "PUT",
      headers: { "If-Match": String(expectedRevision ?? "*") },
      body: JSON.stringify(document),
      signal,
    });
  },
};

This short version skips error handling. The custom backend guide shows the full adapter, with conflicts, retries and the SQL to save a Fabric.js canvas to a database safely. Then verify the adapter.