Quickstart
Define a schema, create a document from a backend, and edit it live from two browser tabs.
This page takes you from nothing to one document that two browser tabs edit together. You write four small files: a schema both sides share, a setup script that makes the database, a backend that creates the document and mints document tokens, and a browser client.
Before you start
You need:
-
A running server. Follow the cloud quickstart or the self-hosting quickstart. The samples below assume a local
mimicdathttp://127.0.0.1:7700with a superuser namedadmin, such as the self-hosting quickstart's, or one started on a local PostgreSQL:export MIMIC_POSTGRES_URL='postgres://localhost:5432/mimic_dev' MIMIC_BOOTSTRAP_PASSWORD=… mimicd serve \ --deployment-name dev \ --listen.public 127.0.0.1:7700 \ --bootstrap-admin adminOn the hosted service, the dashboard creates the database and its keys for you: skip the setup step, and use your database's addresses and keys from its Connect page (see connecting an application).
-
The packages in your project: see Installation.
Define the schema
A schema describes the shape of every document in a collection. Put it in a module that both the backend and the browser import, together with the ids the server knows the database and the collection by.
// shared.ts
import { Primitive } from "@voidhash/mimic-core";
export const TodoList = Primitive.Struct({
title: Primitive.String().required(),
items: Primitive.Array(
Primitive.Struct({
text: Primitive.String().required(),
done: Primitive.Boolean().default(false),
}),
).default([]),
}).required();
// Ids you draw once: 32 lowercase hexadecimal characters each,
// for example from `openssl rand -hex 16`.
export const DATABASE = "…";
export const COLLECTION = "…";Primitive.Struct is an object with named fields, and Primitive.Array is an
ordered list whose items have stable ids. Schemas
lists every primitive.
Create the database, the collection and a key
A superuser creates the database, its lists collection with the schema as
its version 1, and a database key for the backend, through the
server's administration API. Each call can be sent again: making something
again the same way is done.
// setup.ts
import { serializeSchema } from "@voidhash/mimic-core";
import { COLLECTION, DATABASE, TodoList } from "./shared";
const server = "http://127.0.0.1:7700";
const superuser = `Basic ${btoa(`admin:${process.env.MIMIC_BOOTSTRAP_PASSWORD}`)}`;
const admin = async (method: string, path: string, body: unknown) => {
// A database's partitions are placed just after it is created:
// the calls that follow may be answered 503 for a moment.
for (let attempt = 0; ; attempt++) {
const response = await fetch(`${server}/v1/admin${path}`, {
method,
headers: { authorization: superuser, "content-type": "application/json" },
body: JSON.stringify(body),
});
if (response.ok) return response.json();
if (response.status !== 503 || attempt === 30) {
throw new Error(`${method} ${path}: ${response.status} ${await response.text()}`);
}
await new Promise((resolve) => setTimeout(resolve, 500));
}
};
await admin("PUT", `/databases/${DATABASE}`, { budget_group: "default", partitions: 1 });
await admin("PUT", `/databases/${DATABASE}/collections/${COLLECTION}`, {
name: "lists",
schema: serializeSchema(TodoList.schema),
});
const { key } = await admin("POST", `/databases/${DATABASE}/keys`, {
name: "quickstart-backend",
permission: "write",
});
console.log(`MIMIC_KEY=${key}`);The key's secret (mk_…) is answered this once. Keep it in your backend's
environment as MIMIC_KEY.
Create the document and mint tokens
The backend holds the key. It makes sure the document exists, then serves one route that returns a document token: a short-lived credential for one document, which the browser opens its session with.
// server.ts
import { createServer } from "node:http";
import { EngineSDK } from "@voidhash/mimic-server/engine";
import { COLLECTION, DATABASE, TodoList } from "./shared";
const sdk = new EngineSDK({ url: "http://127.0.0.1:7700", credential: process.env.MIMIC_KEY });
const database = sdk.database(DATABASE);
const lists = database.collection(COLLECTION, { primitive: TodoList });
// Create the document unless it exists.
const documentId = "groceries";
const existing = await lists.get(documentId).catch((error) => {
if (error.code === "not_found") return undefined;
throw error;
});
if (!existing?.live) {
await lists.createFrom(documentId, { title: "Groceries" });
}
// Mint a token for the browser.
const appOrigin = "http://localhost:5173";
createServer(async (request, response) => {
response.setHeader("Access-Control-Allow-Origin", appOrigin);
if (request.url !== "/api/token") {
response.writeHead(404).end();
return;
}
const { capability, expires } = await database.mintCapability({
collection: COLLECTION,
document: documentId,
permission: "write",
ttlSeconds: 600,
origins: [appOrigin],
});
response.setHeader("Content-Type", "application/json");
response.end(JSON.stringify({ token: capability, expires }));
}).listen(3001);A real backend checks who is asking before it mints a token, and decides
between "read" and "write". origins limits the token to pages of your
application; replace appOrigin with the origin your page is served from.
Right after the server starts, minting may answer unavailable for a few
seconds, until the server's signing key is in use.
Open the document in the browser
The client opens a session at the server's /v1/sessions endpoint, receives
the document, and keeps it in sync. credential is a function: the client
calls it whenever it opens a session or renews one, and a token may be used
again until it expires.
// client.ts
import { createSyncClientDocument } from "@voidhash/mimic/sync";
import { COLLECTION, DATABASE, TodoList } from "./shared";
const fetchToken = async (): Promise<string> => {
const response = await fetch("http://localhost:3001/api/token");
return (await response.json()).token;
};
const todoList = createSyncClientDocument({
primitive: TodoList,
url: "ws://127.0.0.1:7700/v1/sessions",
database: DATABASE,
collection: COLLECTION,
document: "groceries",
credential: fetchToken,
});
todoList.subscribe({
onStateChange: (snapshot) => {
console.log(
snapshot?.title,
snapshot?.items.map((item) => item.value),
);
},
});
await todoList.connect();snapshot is the document decoded into plain data. Each array item is
{ id, pos, value }: a stable id, its position, and the item itself.
Edit it
Writes go through transaction. The function receives a typed proxy of the
document; everything it writes is applied locally at once and sent to the
server as one atomic transaction.
// Add an item.
todoList.transaction((root) => {
root.items.push({ text: "Milk" });
});
// Tick the first item off.
todoList.transaction((root) => {
root.items.first()?.value.done.set(true);
});Open the page in two tabs. Each tab logs the other's edits as they arrive, and both end with the same list, whatever order the edits were made in.
What happened
- The setup created a collection whose schema the server now enforces: a transaction that would leave the document invalid is rejected.
- Each tab opened a session on the document with a document token and received the document's current state.
- Each edit was applied locally first (an optimistic update), then committed by the server and sent to the other tab. If the connection drops, the client reconnects, catches up from the revision it holds, and sends again what the server has not answered; the server evaluates each transaction at most once.