typescript-server
SpacetimeDB TypeScript server module SDK reference. Use when writing tables, reducers, or module logic in TypeScript.
How do I install this agent skill?
npx skills add https://github.com/clockworklabs/spacetimedb --skill typescript-serverIs this agent skill safe to install?
- Gen Agent Trust Hubpass
This skill is a technical reference for the SpacetimeDB TypeScript SDK, providing documentation and code examples for building server-side modules. It promotes secure coding practices such as using environment variables for secrets and validating caller identities.
- Socketpass
No alerts
- Snykpass
Risk: LOW · No issues
What does this agent skill do?
SpacetimeDB TypeScript SDK Reference
Module Structure
Tables are built with table(), bound with schema(), and exported as default. Reducers and lifecycle hooks are export const:
import { schema, table, t } from 'spacetimedb/server';
const scoreRecord = table(
{ name: 'score_record', public: true },
{
id: t.u64().primaryKey().autoInc(),
owner: t.identity(),
value: t.u32(),
}
);
const spacetimedb = schema({ scoreRecord }); // ONE object, not spread args
export default spacetimedb;
export const addRecord = spacetimedb.reducer(
{ value: t.u32() },
(ctx, { value }) => {
ctx.db.scoreRecord.insert({ id: 0n, owner: ctx.sender, value });
}
);
schema({...}) accepts table definitions and submodule namespace registrations. Row and object builders used as reducer arguments or view return types are not schema entries. Environment declarations go in the second argument: schema(tables, { env: { ... } }).
Export the default schema and every reducer, lifecycle hook, view, procedure, HTTP export, and visibility filter to register. Root-entry named exports must be registered SpacetimeDB values: keep ordinary root helpers/constants unexported. A submodule library may export ordinary helpers for its consumer to call, because submodule discovery ignores non-module exports; do not re-export those helpers from the root entry.
Imports
Schema builders and module exports come from spacetimedb/server. Runtime value classes such as ScheduleAt, Timestamp, and ConnectionId come from the root spacetimedb package; Range comes from spacetimedb/server:
import {
schema, table, t, SenderError,
type InferSchema, type ReducerCtx,
} from 'spacetimedb/server';
import { ConnectionId, ScheduleAt, Timestamp } from 'spacetimedb';
import { Range } from 'spacetimedb/server';
Tables
table(OPTIONS, COLUMNS) takes two arguments. The name field MUST be snake_case:
const entity = table(
{ name: 'entity', public: true },
{
identity: t.identity().primaryKey(),
name: t.string(),
active: t.bool(),
}
);
Options: name (snake_case, recommended), public: true, event: true, indexes: [...]
ctx.db accessors are the keys passed to schema({...}), verbatim: schema({ scoreRecord }) -> ctx.db.scoreRecord. Keep TypeScript identifiers and accessors camelCase. Use explicit name: 'snake_case' strings when you need a canonical database name that differs from the TypeScript identifier.
Column Types
Every column is a t builder value:
| Builder | JS type | Notes |
|---|---|---|
t.u8() / t.u16() / t.u32() | number | |
t.i8() / t.i16() / t.i32() | number | |
t.u64() | bigint | Use 0n literals |
t.i64() | bigint | Use 0n literals |
t.u128() / t.i128() / t.u256() / t.i256() | bigint | |
t.f64() / t.f32() | number | |
t.bool() | boolean | |
t.string() | string | |
t.identity() | Identity | |
t.connectionId() | ConnectionId | |
t.timestamp() | Timestamp | |
t.timeDuration() | TimeDuration | |
t.scheduleAt() | ScheduleAt |
Modifiers: .primaryKey(), .autoInc(), .unique(), .index('btree'), .default(value).
Use .default(value) only for a newly appended migration-safe field. Do not put defaults on primary-key, unique, or auto-increment columns.
Optional columns: nickname: t.option(t.string())
Schema builders describe the database's wire types; they are not TypeScript type names. For example, a t.u16() value is a TypeScript number, not a value cast to a type named u16.
Indexes
Use inline .index('btree') when a single-column index does not need a named accessor. Use an indexes entry when the accessor is named explicitly or the index spans multiple columns. Every indexes entry requires columns; do not also add .index('btree') to the same column.
// Inline (preferred for single-column):
authorId: t.u64().index('btree'),
// Access: ctx.db.post.authorId.filter(authorId);
// Multi-column (named):
indexes: [{ accessor: 'byGroupUser', algorithm: 'btree', columns: ['groupId', 'userId'] }]
// Access: ctx.db.membership.byGroupUser.filter([groupId, userId]);
Prefer a multi-column index over filtering by one column and looping. Filter takes an array in index column order; a prefix scan passes the leading value bare: filter(groupId).
The published module's entry file must export the schema as default. If you split tables
(schema.ts) from reducers/lifecycle (index.ts), re-export it from the entry:
// index.ts
export { default } from './schema'; // re-export the schema for the module entry
Reducers
Reducers are created with spacetimedb.reducer(...); the export name becomes the reducer name:
export const createEntity = spacetimedb.reducer(
{ name: t.string(), age: t.i32() },
(ctx, { name, age }) => {
ctx.db.entity.insert({ identity: ctx.sender, name, age, active: true });
}
);
// No arguments, just the callback:
export const doReset = spacetimedb.reducer((ctx) => { ... });
Reducer args accept any column type, including arrays of custom types: { splits: t.array(Split) }. Do not pass JSON strings for structured data.
DB Operations
ctx.db.scoreRecord.insert({ id: 0n, owner: ctx.sender, value: 1 }); // Insert (0n for autoInc)
ctx.db.scoreRecord.id.find(recordId); // Find by PK → row | null
ctx.db.entity.identity.find(ctx.sender); // Find by unique column
[...ctx.db.post.authorId.filter(authorId)]; // Filter → spread to Array
[...ctx.db.entity.iter()]; // All rows → Array
ctx.db.scoreRecord.id.update({ ...existing, value: 2 }); // Update (spread + override)
ctx.db.scoreRecord.id.delete(recordId); // Delete by PK
Insert through the table accessor (ctx.db.scoreRecord.insert(...)). Primary-key, unique, and index accessors support lookup or mutation of existing rows, but do not have insert(...).
insert(...) returns the inserted row, including database-assigned auto-increment fields.
The accessor for a primary key or index is the declared column name. For example, a primary key named eventId is accessed as ctx.db.event.eventId, not ctx.db.event.id.
The schema value registers module exports but does not expose database rows. Pass a context into any helper that needs ctx.db.
Note: iter() and filter() return iterators. Spread to Array for .sort(), .filter(), .map().
Lifecycle Hooks
MUST be export const. Bare calls are silently ignored:
export const init = spacetimedb.init((ctx) => { ... });
export const onConnect = spacetimedb.clientConnected((ctx) => { ... });
export const onDisconnect = spacetimedb.clientDisconnected((ctx) => { ... });
ctx.connectionId is ConnectionId | null, including in lifecycle contexts. Guard it before passing it to a helper or using it as a table key.
Reducer Context API
ctx is the only source of sender identity, time, and randomness; stdlib clocks and RNG are unavailable in modules. Let exported callbacks infer their context type. In helpers, use ReducerCtx<InferSchema<typeof spacetimedb>>; do not annotate a context as any, because that erases table row types and can make bigint expressions infer as number.
type Ctx = ReducerCtx<InferSchema<typeof spacetimedb>>;
function findRecord(ctx: Ctx, id: bigint) {
return ctx.db.scoreRecord.id.find(id);
}
// Auth: ctx.sender is the caller's Identity
if (!row.owner.equals(ctx.sender)) throw new SenderError('unauthorized');
// ctx.connectionId: the per-connection id, NULLABLE (ConnectionId | null) — null-check before use.
// One Identity can hold several connections (multiple tabs/devices).
if (ctx.connectionId) { /* ... */ }
// Server timestamp (deterministic per reducer call)
ctx.db.item.insert({ id: 0n, createdAt: ctx.timestamp });
// Deterministic RNG
const f: number = ctx.random(); // [0.0, 1.0)
const roll: number = ctx.random.integerInRange(1, 6); // safe JS number bounds/result, inclusive
const storedRoll: bigint = BigInt(roll); // convert the result for an i64/u64 column
const bytes: Uint8Array = ctx.random.fill(new Uint8Array(16));
// 2.13+: in-place shuffle; copy first to preserve the original array.
const shuffled = ctx.random.shuffle([...cards]);
// Client: Timestamp → Date
new Date(Number(row.createdAt.microsSinceUnixEpoch / 1000n));
Do not construct Identity values from strings (e.g. 'hex' as Identity): serialization fails and kills the module. Identities come from ctx.sender or t.identity() columns.
Construct a ConnectionId from its numeric representation with new ConnectionId(value) after importing ConnectionId from spacetimedb.
Construct exact timestamps with new Timestamp(micros) after importing Timestamp from spacetimedb. Inclusive index ranges use Range from spacetimedb/server:
import { Timestamp } from 'spacetimedb';
import { Range } from 'spacetimedb/server';
ctx.db.shipment.deliverBy.filter(new Range(
{ tag: 'included', value: new Timestamp(1_000n) },
{ tag: 'included', value: new Timestamp(2_000n) },
));
Scheduled Tables
The reducer or procedure referenced by a table's scheduled option must be exported.
import { ScheduleAt } from 'spacetimedb'; // ScheduleAt comes from the root package
const tickTimer = table({
name: 'tick_timer',
}, {
scheduledId: t.u64().primaryKey().autoInc(),
scheduledAt: t.scheduleAt(),
});
export const tick = spacetimedb.reducer(
{ onSchedule: tickTimer },
{ timer: tickTimer.rowType },
(ctx, { timer }) => { /* a one-time row is deleted after this runs; an interval row stays */ }
);
// `onSchedule` also works for scheduled procedures whose return type is `t.unit()`.
// Legacy table-side scheduling, `scheduled: (): any => tick`, still works but is not
// recommended for new code because it forces a forward reference.
// One-time: ScheduleAt.time(ctx.timestamp.microsSinceUnixEpoch + delayMicros)
// Repeating: ScheduleAt.interval(60_000_000n)
// Read time back from a scheduleAt value (tagged union):
// const micros = at.tag === 'time' ? at.value : at.value.microsSinceUnixEpoch; // bigint
To let only the scheduler run a callback, reject calls where !ctx.sender.isEqual(ctx.databaseIdentity).
Submodules
Import the library's full module-namespace object, not just its default schema:
import * as authLib from 'auth_lib';
const spacetimedb = schema({
scoreRecord,
myAuth: { name: 'auth_data', module: authLib },
});
export default spacetimedb;
myAuth is the accessor (ctx.db.myAuth.<table>); auth_data is the canonical namespace used in SQL and wire names. Without an explicit name, the root's case policy derives it (myAuth → my_auth by default). Pin name when renaming an accessor: changing the canonical namespace drops its tables and their data. The library keeps its own flat ctx.db accessors. To call a library function directly, pass ctx.as.myAuth; inside withTx, use tx.as.myAuth. Nested TypeScript submodules are supported. Lifecycle reducers and nonempty environment declarations belong in the root. Submodule routers are ignored; register delegated handlers on the root router. Composition is not cross-language.
Official reusable libraries include @spacetimedb/cron, @spacetimedb/retry, @spacetimedb/rate-limit, and @spacetimedb/crypto. Their registration shapes differ: @spacetimedb/rate-limit/submodule is mountable, cron/retry expose factories, and crypto exports helpers. Consult the chosen package's README/exports rather than assuming every package root is a mountable module.
Environment Variables
const spacetimedb = schema({ scoreRecord }, {
env: {
API_KEY: t.string(),
MODE: t.enum('Mode', ['development', 'production']),
LOG_LEVEL: t.string().optional(),
},
});
// In a root reducer/procedure/view/handler:
// ctx.env.API_KEY: string; ctx.env.LOG_LEVEL: string | undefined
// ctx.env.get('LOG_LEVEL'): string | null
See the concepts skill for shared environment and secret-handling rules.
Inter-Database Calls (Async IDC)
A reducer calls a reducer in another database by inserting a row into an outbox table. The call is sent only if the transaction commits, runs exactly once, and runs in order with other calls through the same outbox to the same database. The sending reducer doesn't wait for it. Both databases must be on the same server.
Generate receiver bindings by listing the receiving module under dependencies in the sending database's spacetime.json, then running spacetime generate <sending-database>. TypeScript bindings are written to src/remote_bindings/.
{
"database": "lobby",
"module-path": "./lobby",
"dependencies": [{ "name": "game_world", "database": "game-world" }],
"children": [{ "database": "game-world", "module-path": "./game_world" }]
}
import gw from './remote_bindings/game_world';
// Each row is one call to game_world's `admitPlayer({ name })` reducer.
const admitPlayerOutbox = table(
{ outbox: { receiver: gw.reducers.admitPlayer } },
{
msgId: t.u64().primaryKey().autoInc(), // exactly one u64 autoInc primary key
world: gw.identity().target(), // exactly one target, typed by the bindings
name: t.string(), // one column per reducer parameter, same name and type
// playerName: t.string().param({ name: 'name' }), // alias a column to a parameter
// Extra columns are allowed. They aren't sent, but onResult can read them.
}
);
// Shorthand: gw.outbox.admitPlayer() declares { msgId, target, ...params } for you.
// It can't be used for a reducer with a parameter named msgId or target.
const spacetimedb = schema({ admitPlayerOutbox });
export default spacetimedb;
export const sendToWorld = spacetimedb.reducer(
{ name: t.string(), world: gw.identity() },
(ctx, { name, world }) => {
// Sent if and only if this transaction commits.
ctx.db.admitPlayerOutbox.insert({ msgId: 0n, world, name });
}
);
// Optional, at most one per outbox. Private. Runs once per row, then the row is deleted.
export const onAdmitPlayerResult = spacetimedb.reducer(
{ onResult: admitPlayerOutbox },
{ row: admitPlayerOutbox.rowType, result: t.result(t.unit(), t.string()) },
(ctx, { row, result }) => {
if ('err' in result) console.warn(`${row.name} was not admitted: ${result.err}`);
}
);
- The receiving reducer is an ordinary reducer and needs no changes. In it,
ctx.senderis the sending database's identity, so authorize calls by checking it against an allow-list table. - The receiving database runs
clientConnectedandclientDisconnectedaround every delivered call, with no JWT. IfclientConnectedrejects the sending database, the call is retried forever. - Outbox rows are insert-only, so a pending call can't be cancelled. A call is never retried once it has a result. To try again, insert a new row, for example from
onResult. - A plain
Identitycan't be a target. Use values typedgw.identity(), such as reducer arguments or columns of that type. Index lookups on those columns accept a plainIdentity. - An outbox table can't also be a scheduled table or an event table.
- After the receiving reducer's parameters change, regenerate the bindings and republish the sending database. Calls built from old bindings fail with a signature mismatch error.
See https://spacetimedb.com/docs/databases/inter-database-communication for details.
Custom Types
// Product type (struct):
const Position = t.object('Position', { x: t.i32(), y: t.i32() });
const entity = table({ name: 'entity' }, {
id: t.u64().primaryKey().autoInc(),
pos: Position,
});
// Sum type (tagged union):
const Shape = t.enum('Shape', {
circle: t.i32(),
rectangle: t.object('Rect', { w: t.i32(), h: t.i32() }),
});
// Values: { tag: 'circle', value: 10 }
Views
A client subscribing to a view receives only the rows it returns. Use a per-user view
(keyed on ctx.sender) for per-viewer access control: deleting a row it depends on
(e.g. a membership row) automatically drops the rows it was exposing from that client.
t.row(...) and t.object(...) return schema builders, not TypeScript runtime row types. Let a view callback infer its result, or annotate a separately declared structural type such as Array<{ sku: bigint; label: string }>. A named output type must not reuse the generated PascalCase name of its view accessor (for example, reserve DiscountedProduct for a discounted_product view).
Without parameters, spacetimedb.view(...) and spacetimedb.anonymousView(...) take view options, a return schema, and a callback. Parameterized views add an argument-schema object before the return schema.
// Anonymous view (same for all clients):
export const activeUsers = spacetimedb.anonymousView(
{ name: 'active_users', public: true },
t.array(entity.rowType),
(ctx) => [...ctx.db.entity.iter()].filter(e => e.active)
);
// Per-user view (varies by ctx.sender):
export const myProfile = spacetimedb.view(
{ name: 'my_profile', public: true },
t.option(entity.rowType),
(ctx) => ctx.db.entity.identity.find(ctx.sender) ?? undefined
);
For a procedural view primary key, define the output with t.row and mark its field .primaryKey():
const CatalogKey = t.row('CatalogKey', {
sku: t.u64().primaryKey(),
label: t.string(),
});
Query-builder views use ctx.from and return the query directly. Because a query returns a row set, declare its return schema as t.array(tableName.rowType). Use where for predicates and rightSemijoin when the result should contain right-side rows that have a matching left-side row:
ctx => ctx.from.article.where(article => article.published.eq(true))
ctx => ctx.from.subscription.rightSemijoin(
ctx.from.account,
(subscription, account) => subscription.accountId.eq(account.id)
)
The method name identifies which side is returned: A.leftSemijoin(B, ...) returns rows from A, while A.rightSemijoin(B, ...) returns rows from B. To return one table's rows when another table has a match, put the returned table on the corresponding side. Semijoins do not project combined columns from both tables.
Procedural views read through ctx.db and return materialized values such as arrays. Query-builder values from ctx.from are returned directly; they are not iterators and cannot be spread, looped over, or mixed with array methods. Use a procedural view when the result is a custom row assembled from multiple tables.
Parameterized views (2.13+) pass arguments to the callback as an object:
export const entityById = spacetimedb.anonymousView(
{ public: true },
{ identity: t.identity() },
t.option(entity.rowType),
(ctx, { identity }) => ctx.db.entity.identity.find(identity) ?? undefined
);
Floating-point arguments are rejected. Views with arguments have no primary key; TypeScript omits primary-key metadata from the returned row type automatically. See client skills for SQL subscription syntax and restrictions.
Client Visibility Filters
export const privateNoteFilter = spacetimedb.clientVisibilityFilter.sql(
'SELECT * FROM owned_row WHERE owner = :sender'
);
Procedures and HTTP
spacetimedb is the local schema value returned by schema({...}); it is not a named export to import from spacetimedb/server.
Procedures declare argument and return types:
const Result = t.object('Result', { value: t.string() });
export const inspect = spacetimedb.procedure(
{ input: t.string() },
Result,
(_ctx, { input }) => ({ value: input })
);
Procedure callbacks are synchronous. Do not mark them async or use await; return the declared value directly. A procedure with return type t.unit() returns {}.
TypeScript outbound HTTP uses ctx.http.fetch(url, options), including for non-GET requests; it does not provide convenience methods such as get() or post(). Responses expose the numeric status, headers.get(name), and text() APIs.
t.array(t.u8()) values are number[]. Convert one to new Uint8Array(value) before using it as a binary request body.
Procedures and handlers open short database transactions with ctx.withTx(tx => ...). Perform network I/O before opening the transaction; only database work belongs inside its callback.
Scheduled procedures use the same onSchedule binding as scheduled reducers. The procedure must be exported, return t.unit(), and accept the scheduled row as its argument.
Inbound HTTP uses httpHandler, httpRouter, Router, and SyncResponse:
httpHandler and httpRouter are methods on the local spacetimedb schema value, not named imports.
import { Router, SyncResponse } from 'spacetimedb/server';
export const health = spacetimedb.httpHandler((_ctx, _request) =>
new SyncResponse('ok', {
status: 200,
headers: { 'content-type': 'text/plain' },
})
);
export const routes = spacetimedb.httpRouter(new Router().get('/health', health));
Handlers are synchronous: return SyncResponse directly rather than marking the callback async. Pass the exported httpHandler(...) value to the router, not its raw callback. The router selects the path, while a handler reads request data with APIs such as request.text(); Request has no path property. A handler context does not expose ctx.db; use ctx.withTx(tx => ...) when a handler needs transactional database access.
Module Unit Tests
Use spacetimedb 2.12+ and Node.js 22+ in the module project, not the client. Set "type": "module" in package.json and install the test runner with npm install --save-dev vitest@^3.2.4. Configure the host-import replacement:
// vitest.config.ts
import { defineConfig, type Plugin } from 'vitest/config';
import { spacetimedbModuleTestPlugin } from 'spacetimedb/server/test-utils/vitest';
export default defineConfig({
plugins: [spacetimedbModuleTestPlugin() as unknown as Plugin],
test: { environment: 'node' },
});
// src/index.test.ts, for the addRecord reducer above
import { expect, it } from 'vitest';
import { createModuleTestHarness, TestAuth } from 'spacetimedb/server/test-utils';
import spacetimedb, * as moduleExports from './index';
it('inserts a record', () => {
const test = createModuleTestHarness(spacetimedb, moduleExports);
test.withReducerTx(TestAuth.internal(), ctx => {
moduleExports.addRecord(ctx, { value: 1 });
});
expect(test.db.scoreRecord.count()).toBe(1n);
});
Run npx vitest run. Create a fresh harness per test. withReducerTx commits on normal return and rolls back/rethrows on exceptions; do not catch a failure inside the transaction if rollback is expected. Callbacks must be synchronous. Use TestAuth.fromJwtPayload(JSON.stringify({ iss: 'test', sub: 'alice' }), connectionId) for client authorization tests; internal auth represents the database, not a client or the publisher. The harness exposes clock, rng, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or scheduling; invoke lifecycle/scheduled reducers explicitly and retain live integration tests for those host behaviors.
How can the creator link this skill?
Add the canonical catalog link to the repository README so users can inspect current installs and available audits. The publishing guide covers the complete discovery path.
<a href="https://skillzs.dev/skills/clockworklabs/spacetimedb/typescript-server">View typescript-server on skillZs</a>