Backend/Whiteboards

Whiteboards

Boards live for the session today, and teammates' cursors are simulated. This page shows how to save boards in your database and let people work on the same board at the same time.

What the demo does today

PartTodayCode
BoardsStart from five sample boards; new and changed boards last until a reloadsrc/components/providers/whiteboards-provider.tsx, src/lib/data/whiteboards.ts
What's on a boardOne JSON-friendly object per board: objects and connectorssrc/lib/whiteboard/types.ts
ImagesA temporary browser link, gone after a reloadaddImage in components/whiteboards/board-page.tsx
Teammates on the boardAvatars and two cursors that move on their owncomponents/whiteboards/board-presence.tsx
ShareCopies the link and marks people as invited; nothing is sentSharePopover in board-page.tsx

Every edit already goes through one place. The board editor, components/whiteboards/use-board-editor.ts, calls the provider's saveContent(id, content) after each change. A drag, a resize or a run of typing counts as one change and saves once, at the end. That's the function you connect.

Save boards

Create a table for boards. The board's details get their own columns so lists and the customer's Boards tab can query them; what's on the board is one JSON column, saved and loaded whole.

Boards table (SQL, Supabase example)
create table boards (
  id text primary key,
  owner_id uuid not null references auth.users default auth.uid(),
  name text not null,
  customer_id bigint references customers(id) on delete set null,
  contract_id text,
  template_id text,
  content jsonb not null default '{"objects": [], "connectors": []}',
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

alter table boards enable row level security;

Load the board list (without content, which can be large) when the provider starts, and a board's content when it opens. See Database for loading records on the server.

Save changes from saveContent. Wait for a short pause before writing, so a burst of edits becomes one save:

whiteboards-provider.tsx (sketch)
const timers = new Map<string, ReturnType<typeof setTimeout>>()

const saveContent = useCallback((id: string, content: BoardContent) => {
  setList((prev) => prev.map((b) => (b.id === id ? { ...b, ...content } : b))) // as today
  clearTimeout(timers.get(id))
  timers.set(id, setTimeout(() => saveBoard(id, content), 800))
}, [])
saveBoard, a Server Action
"use server"
export async function saveBoard(id: string, content: BoardContent) {
  const supabase = await createClient()
  const { error } = await supabase
    .from("boards")
    .update({ content, updated_at: new Date().toISOString() })
    .eq("id", id)
  if (error) throw error
}

Do the same for createBoard, updateBoard (name, customer, contract), duplicateBoard and deleteBoard. Keep the Undo on delete by deleting after the toast closes, or by marking the board deleted and cleaning up later.

Boards made from a template are ordinary boards: the template is copied in when the board is made, and template_id only records which one it was.

Images on boards

An image is an object with a src. Today src is a link to the file in the browser's memory. Upload the file to your storage first, as on File storage, and put the stored file's link in src. Then the board's JSON stays small and the image survives a reload. For private files, save the storage path and sign a link when the board loads.

Record cards

Customer, contact, contract and task cards don't copy the record: they keep its id (refId) and read it live from the providers, so they need nothing extra once those providers read your database. Each card also saves a title, used in exports and when the record has been deleted (the card then says "No longer in the CRM").

Work together in real time

Two things need to reach everyone on a board, as it happens:

  • Changes to what's on the board.
  • Presence: who's there, their cursor and what they have selected. This is never saved.

A hosted service saves you running servers: Liveblocks and Supabase Realtime are two examples. You can also run your own WebSocket server. Here's the shape with Supabase Realtime:

One channel per board (Supabase example)
const channel = supabase.channel(`board:${boardId}`, {
  config: { presence: { key: userId } },
})

channel
  // Someone moved their cursor
  .on("broadcast", { event: "cursor" }, ({ payload }) => showCursor(payload))
  // Someone changed the board: apply it without saving it again
  .on("broadcast", { event: "change" }, ({ payload }) => applyRemote(payload))
  // Who's on the board, for the avatars in the header
  .on("presence", { event: "sync" }, () => setViewers(channel.presenceState()))
  .subscribe(async (status) => {
    if (status === "SUBSCRIBED") await channel.track({ name, color })
  })

// Send your cursor (in board units) at most every 50 ms
channel.send({ type: "broadcast", event: "cursor", payload: { userId, x, y } })

Replace the demo cursors: PresenceCursors in board-presence.tsx draws a list of people at board positions, so give it the cursors from the channel instead of the ones it animates. boardViewers feeds the avatars in the header; swap it for the channel's presence.

Send changes. When saveContent runs, also broadcast what changed. Sending the objects and connectors that changed (by id), rather than the whole board, keeps messages small.

Apply changes from others to the board without adding them to your own undo history: the editor's undo should only take back what you did.

With this approach, when two people change the same sticky at the same moment, the last change wins. That's fine for most teams. If you need edits to merge (two people typing in one text box), use a CRDT library such as Yjs, which Liveblocks and others support.

Who can see a board

  • Same rules as the records. A board linked to a customer is usually visible to everyone who can see that customer. Enforce it on the server, with row-level security or a check in each action.
  • Share. The Share button lists teammates to invite. Store invites in a table (board, person, can edit or view only) and send the email as on Email.
  • View-only. The canvas already has a readOnly mode (pan, zoom and select, no editing) for people who can only view.