Tutorial: ReactJS Todo
Note Full source code: vski.sh/x/template_frontend
VSKI is not only a backend for services and agents: the same API serves browser frontends directly. This tutorial builds a multi-user todo application in React (Vite + TypeScript) where accounts, per-user data and live synchronization all come from the platform:
- sign up and sign in against the system
_usersauth collection - each user sees and edits only their own todos, enforced by the database, not by the client
- a todo checked in one browser tab appears checked in another tab (and in another browser) instantly, over a WebSocket
No custom backend is written: the whole server side is one collection with rules, declared as code.
What You’ll Build
Section titled “What You’ll Build”flowchart LR R["React app<br/>Vite + TS<br/>@vski/sdk"] <-->|"REST (records, auth)"| V["VSKI server<br/>SQLite + FTS, rules engine"] R <-->|"WebSocket (realtime)"| VOne page, one collection, five rules. The interesting parts are not the React code, but what the app does not have to do: authentication storage, per-user filtering, change notification, reconnection logic.
Prerequisites
Section titled “Prerequisites”- A running VSKI server with the first admin created (see Getting Started)
- Node.js 20 or newer
- The
vskiCLI for the IaC step (see SDKs and CLI)
Step 1: Declare the Data Model
Section titled “Step 1: Declare the Data Model”Accounts need no declaration: every database ships with a system _users
auth collection, and registration and login go through /api/auth/*. What
we declare is the todos collection and who may touch a record:
version: 1database: default
collections: todos: type: base fields: - {name: text, type: text, required: true} - {name: done, type: bool} - {name: authorId, type: text, required: true} rules: list: "authorId = @request.auth.id" view: "authorId = @request.auth.id" create: "authorId = @request.auth.id" update: "authorId = @request.auth.id" delete: "authorId = @request.auth.id"Every rule is the same expression (see
Rules and Access Control): @request.auth.id
resolves to the id of the authenticated user, so:
listandviewfilter queries to records the caller authored; another user’s todos are not hidden, they are simply not returnedcreaterejects a record whoseauthorIdis not the caller, so a logged-in user cannot write todos into someone else’s listupdateanddeleteapply the same check to existing records
Apply it:
pip install --extra-index-url https://vski.sh/api/packages/x/pypi/simple/ "vski-sdk[cli]"export VSKI_URL=http://127.0.0.1:3000vski login # admin email + passwordvski iac apply vskiStep 2: Scaffold the App
Section titled “Step 2: Scaffold the App”npm create vite@latest vski-todos -- --template react-tscd vski-todosnpm install @vski/sdkThe SDK is served by the vski.sh npm registry, so tell npm about the scope
in .npmrc (reads are public, no credentials needed):
@vski:registry=https://vski.sh/api/packages/x/npm/The server URL comes from the environment, with a local default:
VITE_VSKI_URL=http://127.0.0.1:3000If your server runs with ALLOWED_ORIGINS, add the dev origin
(http://127.0.0.1:5173) to it; realtime WebSockets need it too.
Step 3: The Client and the Session
Section titled “Step 3: The Client and the Session”One VskiClient instance for the whole app. The JWT and the user record
survive reloads in localStorage; on boot the app revalidates the token:
import { VskiClient } from "@vski/sdk";
const url = import.meta.env.VITE_VSKI_URL || "http://127.0.0.1:3000";const client = new VskiClient(url);
// restore a previous sessionconst token = localStorage.getItem("todos_token");if (token) client.setToken(token);Registration and login are one call each; login also sets the client
token, and both return the user record:
// create an account, then sign in with itawait client.auth.register({ email, password, passwordConfirm: password, name: email.split("@")[0],});const res = await client.auth.login(email, password);localStorage.setItem("todos_token", res.token);// res.user: {id, email, ...}
// later, on reload: is the token still good?const me = await client.auth.me();Step 4: Load the List
Section titled “Step 4: Load the List”The initial state is a regular query. Records come back newest first:
const page = await client.collection<Todo>("todos").getList({ page: 1, perPage: 200, sort: "-created",});setTodos(page.items);Note there is no where authorId = me anywhere: the list rule already
filtered the result on the server.
Step 5: Realtime Sync
Section titled “Step 5: Realtime Sync”After the initial load the app subscribes to the collection, and every create, update and delete arrives as an event:
useEffect(() => { if (!user) return;
const unsub = client.collection<Todo>("todos").subscribe((event) => { // event.action: "create" | "update" | "delete" // event.record: the changed record if (event.action === "delete") { setTodos((prev) => prev.filter((t) => t.id !== event.record.id)); return; } if (event.record.authorId !== user.id) return; // see below setTodos((prev) => upsert(prev, event.record)); });
return unsub; // unsubscribe on unmount / sign out}, [user]);Two things worth understanding:
- The server filters events per subscriber. The collection’s
listrule applies at subscribe time and again to every delivered event: withlist: "authorId = @request.auth.id"the server evaluates each event’s record against the subscriber before sending it, so user B’s records never reach user A’s socket (and a closed collection rejects the subscription outright). Theevent.record.authorId !== user.idcheck above still has value as defense in depth: it costs one line and guards the UI even if the collection’s rules are later loosened on the server. - Events reconcile, they do not command. Mutations below apply the
server response immediately for a snappy UI; when the matching event
arrives a moment later, upserting by
idis a no-op. That is what makes two tabs converge on the same state.
The SDK manages the WebSocket itself: it connects on the first subscribe, reconnects after a drop, and resends the subscriptions after reconnecting (see Realtime).
Step 6: Mutations
Section titled “Step 6: Mutations”Each action is a single client call; the todo is a record, nothing more:
const todos = client.collection<Todo>("todos");
// addconst created = await todos.create({ text, done: false, authorId: user.id, // must be ours: the create rule checks it});
// check offawait todos.update(created.id, { done: true });
// remove oneawait todos.delete(created.id);
// remove all completed at onceawait todos.bulkDelete(doneIds);A user who tries to create a todo with someone else’s authorId gets a
plain HTTP 403 from the rule engine; surfacing that error in the UI is all
the client has to do about security.
Try It
Section titled “Try It”npm run dev # http://127.0.0.1:5173- Create an account, add a few todos
- Open the same URL in a second tab: the list is already there
- Check a todo in one tab and watch it flip in the other, without a reload
- Sign up as a second user in a private window: the list is empty, and no amount of trying will make the first user’s todos appear
For production, npm run build produces a fully static dist/: host it on
any static server or CDN, keep the origin in ALLOWED_ORIGINS, and point
VITE_VSKI_URL at the deployment’s server.
Where the Work Went
Section titled “Where the Work Went”| Concern | Who handles it | Where it is declared |
|---|---|---|
| Accounts, hashing | the platform | system _users collection |
| Per-user isolation | the rules engine | rules: in collections.yaml |
| Change notifying | the realtime engine | subscribe(...) in the app |
| Reconnecting | the SDK | automatic |
| Persistence | per-tenant SQLite | the server’s data dir |
The application code is left with what it should be left with: rendering, draft input, and the optimistic UI.
Where to Go Next
Section titled “Where to Go Next”- Realtime: consumer groups, metrics and the event stream
- Rules and Access Control: field-level rules and role checks
- SDKs: installing the TypeScript and Python SDKs
- Pipelines: react to collection events server side, for example to index or enrich todos as they are created