Backend
A realtime database for every tik, powered by SpacetimeDB: tables and functions written in TypeScript, published by the CLI and live on every screen.
Backends are powered by SpacetimeDB, a database built for realtime apps. A tik can own one: tables plus the functions that change them, written in TypeScript as a SpacetimeDB module. The page talks to it over a WebSocket and every connected user sees every change live. That is what shared counters, presence, leaderboards, rooms and turn-based games are built on.
You never install the SpacetimeDB CLI or hold a credential: Codetik publishes the module for you from codetik backend and codetik dev, then hands the generated files back. A backend needs the Pro plan, for development and for every publish.
Turn it on
$ codetik backendIt adds what is missing and leaves the rest alone: options.spacetimedb.enabled in tik.yaml, a starter module in backend/src/index.ts, and spacetimedb in package.json peerDependencies. Then it publishes the module and writes the bindings your page imports.
backend/src/index.ts # your module: tables and reducersbackend/src/tik-backend.ts # Codetik's guard, generated; read it, never edit itbackend/package.json # generated, keep it in the repobackend/tsconfig.json # generated, keep it in the reposrc/module_bindings/ # generated from your module, gitignoredsrc/main.ts # the page, imports ./module_bindingscodetik dev publishes the module when it starts and again on every save under backend/src. A module that does not compile prints its error and keeps the previous bindings; the dev server carries on. codetik backend --status reports what the backend has and lacks, and codetik backend --off removes it.
Who the users are
| Shape | A user is | Set with |
|---|---|---|
| Anonymous | A new identity on every connection; nothing survives a reload | The default with a backend |
| Identified | One stable identity, with a signed name and avatar | codetik permissions --auth on |
With a backend, auth and profile are one switch. Anonymous tiks let one device make any number of identities, so never build one-person-one-vote on them. Either way, every public table is readable by anyone.
Tables
import { schema, table, t, SenderError } from 'spacetimedb/server';import { requireCaller, callerClaims } from './tik-backend'; const scoreTable = table( { name: 'score', public: true }, { identity: t.identity().primaryKey(), name: t.string(), best: t.u32(), updatedAt: t.timestamp(), },); const spacetimedb = schema({ score: scoreTable });export default spacetimedb;- A table is private unless
public: true. A private table is for the server only; a client subscribed to it sees nothing. - Columns:
t.string(),t.bool(),t.identity(),t.timestamp(),t.u32()and other sized numbers (t.u64()and wider are BigInt),t.array(...),t.option(...),t.object(...)andt.enum(...)for structured values. - Modifiers:
.primaryKey(),.unique(),.autoInc(),.index(),.default(value). The modifier decides the accessor:ctx.db.score.identity.find(id)exists becauseidentityis the primary key.
Reducers
Reducers are the only way anything changes. Each one is a transaction: throwing rolls back every write, and a SenderError message reaches the page as the rejection of the call.
export const submit = spacetimedb.reducer( { score: t.u32() }, (ctx, { score }) => { requireCaller(ctx); const who = callerClaims(ctx); if (who === null) throw new SenderError('sign in to post a score'); if (score > 100_000) throw new SenderError('implausible score'); const existing = ctx.db.score.identity.find(ctx.sender); if (existing === null) { ctx.db.score.insert({ identity: ctx.sender, name: who.name ?? 'user', best: score, updatedAt: ctx.timestamp, }); } else if (score > existing.best) { ctx.db.score.identity.update({ ...existing, best: score, updatedAt: ctx.timestamp, }); } },);requireCaller(ctx)in every reducer, lifecycle ones included. Reducers can be called over plain HTTP, so a check at connect time guards nothing.ctx.senderis who called, worked out from the token and impossible to fake. Never take an identity or a name as an argument:post(authorId)lets anyone act as anyone.- Deterministic. No
Date.now(), noMath.random(), no network: usectx.timestampandctx.random(). - Export every reducer as a named
export const; the database only registers what the module exports.
The guard
backend/src/tik-backend.ts is generated from the tik's grants on every publish:
| Helper | What it does |
|---|---|
requireCaller(ctx) | Refuses tokens for other databases, and anonymous callers when auth is on |
callerClaims(ctx) | { subject, name?, avatarUrl? } from the signed token, or null |
isAuthor(ctx) | true only for the tik's author |
Take names from callerClaims, never from tik.profile() on the page, which a fork can fake.
Lifecycle, timers and views
export const init = spacetimedb.init((ctx) => { // once, when the database is created: seed singleton rows here});export const onConnect = spacetimedb.clientConnected((ctx) => { requireCaller(ctx);});export const onDisconnect = spacetimedb.clientDisconnected((ctx) => { // presence cleanup});- There is no
setInterval: a timer is a row in a scheduled table, and the database calls its reducer when the row comes due. Times are in microseconds. - A view is a query evaluated per subscriber.
spacetimedb.viewseesctx.sender, which is how per-user access works;spacetimedb.anonymousViewis the same for everyone, like a top-ten list. - A module may not make network calls or declare HTTP handlers; a publish refuses one that tries.
The page
import { DbConnection, tables } from './module_bindings'; if (!tik.spacetimedb) throw new Error('published without a backend');const { url, database } = await tik.spacetimedb();const token = tik.token ? await tik.token() : undefined; let builder = DbConnection.builder().withUri(url).withDatabaseName(database);if (token) builder = builder.withToken(token); const connection = builder .onConnect((conn) => { conn.subscriptionBuilder().onApplied(render).subscribe([tables.score]); }) .build(); connection.db.score.onInsert(render);connection.db.score.onUpdate(render); async function submit(score: number): Promise<void> { try { await connection.reducers.submit({ score }); } catch (error) { showError(error instanceof Error ? error.message : String(error)); }}- Read the URL and database from
tik.spacetimedb(); never hardcode them. - The first rows arrive in
onApplied;onInsert,onUpdateandonDeletekeep the page live after that. Row callbacks take the context first:onInsert((ctx, row) => ...). - Subscribe to the rows this user needs, not whole tables of everyone's data.
- Pause the connection's traffic while the tik is hidden.
- An identity compares with
toHexString(), never===; at.u64()arrives as a BigInt.
Data and schema changes
One database per tik, shared by development and the published tik.
- Before release a breaking schema change (a new column with no default, a changed type) is refused, and
codetik backend --reset-dbclears the rows on purpose. The firstpublish --livealso clears them, so users start fresh. - After release the data belongs to the users, and a breaking change is refused.
codetik backend --reset-dbis the explicit way through, and it deletes everything. A public tik's backend cannot be changed from the CLI. - Plan for this: add columns with
.default(...), and add new tables rather than reshaping old ones.