TypeScript Reference
The SpacetimeDB client SDK for TypeScript contains all the tools you need to build clients for SpacetimeDB modules using Typescript, either in the browser or with NodeJS.
Before diving into the reference, you may want to review:
- Generating Client Bindings - How to generate TypeScript bindings from your module
- Connecting to SpacetimeDB - Establishing and managing connections
- SDK API Reference - Core concepts that apply across all SDKs
| Name | Description |
|---|---|
| Project setup | Configure your TypeScript project to use the SpacetimeDB TypeScript client SDK. |
| Generate module bindings | Use the SpacetimeDB CLI to generate module-specific types and interfaces. |
DbConnection type | A connection to a remote database. |
DbContext interface | Methods for interacting with the remote database. Implemented by DbConnection and various event context types. |
EventContext type | DbContext available in row callbacks. |
ReducerEventContext type | DbContext available in reducer callbacks. |
SubscriptionEventContext type | DbContext available in subscription-related callbacks. |
ErrorContext type | DbContext available in error-related callbacks. |
| Access the client cache | Make local queries against subscribed rows, and register row callbacks to run when subscribed rows change. |
| Observe and invoke reducers | Send requests to the database to run reducers, and register callbacks to run when notified of reducers. |
| Identify a client | Types for identifying users and client connections. |
Project setup
First, create a new client project, and add the following to your tsconfig.json file:
{
"compilerOptions": {
//You can use any target higher than this one
//https://www.typescriptlang.org/tsconfig#target
"target": "es2015"
}
}
Then add the SpacetimeDB SDK to your dependencies:
cd client
npm install spacetimedb
WARNING! The
@clockworklabs/spacetimedb-sdkpackage has been deprecated in favor of thespacetimedbpackage as of SpacetimeDB version 1.4.0. If you are using the old SDK package, you will need to switch tospacetimedb. You will also need a SpacetimeDB CLI version of 1.4.0+ to generate bindings for the newspacetimedbpackage.
You should have this folder layout starting from the root of your project:
quickstart-chat
├── client
│ ├── node_modules
│ ├── public
│ └── src
└── server
└── src
Tip for utilities/scripts
If want to create a quick script to test your module bindings from the command line, you can use https://www.npmjs.com/package/tsx to execute TypeScript files.
Then you create a script.ts file and add the imports, code and execute with:
npx tsx src/script.ts
Generate module bindings
Each SpacetimeDB client depends on some bindings specific to your module. Create a module_bindings directory in your project's src directory and generate the Typescript interface files using the Spacetime CLI. From your project directory, run:
mkdir -p client/src/module_bindings
spacetime generate --lang typescript \
--out-dir client/src/module_bindings \
--project-path PATH-TO-MODULE-DIRECTORY
Import the module_bindings in your client's main file:
import * as moduleBindings from './module_bindings/index';
You may also need to import some definitions from the SDK library:
import { Identity, ConnectionId, Event, ReducerEvent } from 'spacetimedb';
Type DbConnection
DbConnection;
A connection to a remote database is represented by the DbConnection type. This type is generated per-module, and contains information about the types, tables and reducers defined by your module.
| Name | Description |
|---|---|
| Connect to a database | Construct a DbConnection. |
| Access tables and reducers | Access subscribed rows in the client cache, request reducer invocations, and register callbacks. |
Connect to a database
class DbConnection {
public static builder(): DbConnectionBuilder;
}
Construct a DbConnection by calling DbConnection.builder() and chaining configuration methods, then calling .build(). You must at least specify withUri, to supply the URI of the SpacetimeDB to which you published your module, and withModuleName, to supply the human-readable SpacetimeDB domain name or the raw Identity which identifies the database.
| Name | Description |
|---|---|
withUri method | Set the URI of the SpacetimeDB instance which hosts the remote database. |
withModuleName method | Set the name or Identity of the remote database. |
withConfirmedReads method | Enable or disable confirmed reads. |
onConnect callback | Register a callback to run when the connection is successfully established. |
onConnectError callback | Register a callback to run if the connection is rejected or the host is unreachable. |
onDisconnect callback | Register a callback to run when the connection ends. |
withToken method | Supply a token to authenticate with the remote database. |
build method | Finalize configuration and connect. |
Method withUri
class DbConnectionBuilder {
public withUri(uri: string): DbConnectionBuilder;
}
Configure the URI of the SpacetimeDB instance or cluster which hosts the remote database.
Method withModuleName
class DbConnectionBuilder {
public withModuleName(name_or_identity: string): DbConnectionBuilder;
}
Configure the SpacetimeDB domain name or hex string encoded Identity of the remote database which identifies it within the SpacetimeDB instance or cluster.
Method withConfirmedReads
class DbConnectionBuilder {
public withConfirmedReads(confirmedReads: bool): DbConnectionBuilder;
}
Configure the connection to request confirmed reads.
When enabled, the server will send query results only after they are confirmed to be durable, i.e. persisted to disk on one or more replicas depending on the replication settings of the database. When set to false, the server will send results as soon as transactions are committed in memory.
If this method is not called, the server chooses the default.
Callback onConnect
class DbConnectionBuilder {
public onConnect(
callback: (ctx: DbConnection, identity: Identity, token: string) => void
): DbConnectionBuilder;
}
Chain a call to .onConnect(callback) to your builder to register a callback to run when your new DbConnection successfully initiates its connection to the remote database. The callback accepts three arguments: a reference to the DbConnection, the Identity by which SpacetimeDB identifies this connection, and a private access token which can be saved and later passed to withToken to authenticate the same user in future connections.
Callback onConnectError
class DbConnectionBuilder {
public onConnectError(
callback: (ctx: ErrorContext, error: Error) => void
): DbConnectionBuilder;
}
Chain a call to .onConnectError(callback) to your builder to register a callback to run when your connection fails.
Callback onDisconnect
class DbConnectionBuilder {
public onDisconnect(
callback: (ctx: ErrorContext, error: Error | null) => void
): DbConnectionBuilder;
}
Chain a call to .onDisconnect(callback) to your builder to register a callback to run when your DbConnection disconnects from the remote database, either as a result of a call to disconnect or due to an error.
Method withToken
class DbConnectionBuilder {
public withToken(token?: string): DbConnectionBuilder;
}
Chain a call to .withToken(token) to your builder to provide an OpenID Connect compliant JSON Web Token to authenticate with, or to explicitly select an anonymous connection. If this method is not called or null is passed, SpacetimeDB will generate a new Identity and sign a new private access token for the connection.
Method build
class DbConnectionBuilder {
public build(): DbConnection;
}
After configuring the connection and registering callbacks, attempt to open the connection.
Access tables and reducers
Field db
class DbConnection {
public db: RemoteTables;
}
The db field of the DbConnection provides access to the subscribed view of the remote database's tables. See Access the client cache.
Field reducers
class DbConnection {
public reducers: RemoteReducers;
}
The reducers field of the DbConnection provides access to reducers exposed by the remote module. See Observe and invoke reducers.
Interface DbContext
interface DbContext<
DbView,
Reducers,
>
DbConnection, EventContext, ReducerEventContext, SubscriptionEventContext and ErrorContext all implement DbContext. DbContext has fields and methods for inspecting and configuring your connection to the remote database.
The DbContext interface is implemented by connections and contexts to every module. This means that its DbView and Reducers are generic types.
| Name | Description |
|---|---|
db field | Access subscribed rows of tables and register row callbacks. |
reducers field | Request reducer invocations and register reducer callbacks. |
disconnect method | End the connection. |
| Subscribe to queries | Register SQL queries to receive updates about matching rows. |
| Read connection metadata | Access the connection's Identity and ConnectionId |
Field db
interface DbContext {
db: DbView;
}
The db field of a DbContext provides access to the subscribed view of the remote database's tables. See Access the client cache.
Field reducers
interface DbContext {
reducers: Reducers;
}
The reducers field of a DbContext provides access to reducers exposed by the remote module. See Observe and invoke reducers.
Method disconnect
interface DbContext {
disconnect(): void;
}
Gracefully close the DbConnection. Throws an error if the connection is already disconnected.
Subscribe to queries
| Name | Description |
|---|---|
SubscriptionBuilder type | Builder-pattern constructor to register subscribed queries. |
SubscriptionHandle type | Manage an active subscripion. |
Type SubscriptionBuilder
SubscriptionBuilder;
| Name | Description |
|---|---|
ctx.subscriptionBuilder() constructor | Begin configuring a new subscription. |
onApplied callback | Register a callback to run when matching rows become available. |
onError callback | Register a callback to run if the subscription fails. |
subscribe method | Finish configuration and subscribe to one or more SQL queries. |
subscribeToAllTables method | Convenience method to subscribe to the entire database. |
Constructor ctx.subscriptionBuilder()
interface DbContext {
subscriptionBuilder(): SubscriptionBuilder;
}
Subscribe to queries by calling ctx.subscription_builder() and chaining configuration methods, then calling .subscribe(queries).
Callback onApplied
class SubscriptionBuilder {
public onApplied(
callback: (ctx: SubscriptionEventContext) => void
): SubscriptionBuilder;
}
Register a callback to run when the subscription is applied and the matching rows are inserted into the client cache.
Callback onError
class SubscriptionBuilder {
public onError(
callback: (ctx: ErrorContext, error: Error) => void
): SubscriptionBuilder;
}
Register a callback to run if the subscription is rejected or unexpectedly terminated by the server. This is most frequently caused by passing an invalid query to subscribe.
Method subscribe
class SubscriptionBuilder {
subscribe(queries: string | string[]): SubscriptionHandle;
}
Subscribe to a set of queries.
See the SpacetimeDB SQL Reference for information on the queries SpacetimeDB supports as subscriptions.
Method subscribeToAllTables
class SubscriptionBuilder {
subscribeToAllTables(): void;
}
Subscribe to all rows from all public tables. This method is provided as a convenience for simple clients. The subscription initiated by subscribeToAllTables cannot be canceled after it is initiated. You should subscribe to specific queries if you need fine-grained control over the lifecycle of your subscriptions.
Type SubscriptionHandle
SubscriptionHandle;
A SubscriptionHandle represents a subscribed query or a group of subscribed queries.
The SubscriptionHandle does not contain or provide access to the subscribed rows. Subscribed rows of all subscriptions by a connection are contained within that connection's ctx.db. See Access the client cache.
| Name | Description |
|---|---|
isEnded method | Determine whether the subscription has ended. |
isActive method | Determine whether the subscription is active and its matching rows are present in the client cache. |
unsubscribe method | Discard a subscription. |
unsubscribeThen method | Discard a subscription, and register a callback to run when its matching rows are removed from the client cache. |
Method isEnded
class SubscriptionHandle {
public isEnded(): bool;
}
Returns true if this subscription has been terminated due to an unsubscribe call or an error.
Method isActive
class SubscriptionHandle {
public isActive(): bool;
}
Returns true if this subscription has been applied and has not yet been unsubscribed.
Method unsubscribe
class SubscriptionHandle {
public unsubscribe(): void;
}
Terminate this subscription, causing matching rows to be removed from the client cache. Any rows removed from the client cache this way will have onDelete callbacks run for them.
Unsubscribing is an asynchronous operation. Matching rows are not removed from the client cache immediately. Use unsubscribeThen to run a callback once the unsubscribe operation is completed.
Throws an error if the subscription has already ended, either due to a previous call to unsubscribe or unsubscribeThen, or due to an error.
Method unsubscribeThen
class SubscriptionHandle {
public unsubscribeThen(on_end: (ctx: SubscriptionEventContext) => void): void;
}
Terminate this subscription, and run the onEnd callback when the subscription is ended and its matching rows are removed from the client cache. Any rows removed from the client cache this way will have onDelete callbacks run for them.
Returns an error if the subscription has already ended, either due to a previous call to unsubscribe or unsubscribeThen, or due to an error.
Read connection metadata
Field isActive
interface DbContext {
isActive: bool;
}
true if the connection has not yet disconnected. Note that a connection isActive when it is constructed, before its onConnect callback is invoked.
Type EventContext
EventContext;
An EventContext is a DbContext augmented with a field event: Event. EventContexts are passed as the first argument to row callbacks onInsert, onDelete and onUpdate.
| Name | Description |
|---|---|
event field | Enum describing the cause of the current row callback. |
db field | Provides access to the client cache. |
reducers field | Allows requesting reducers run on the remote database. |
Event type | Possible events which can cause a row callback to be invoked. |
Field event
class EventContext {
public event: Event<Reducer>;
}
/* other fields */
The Event contained in the EventContext describes what happened to cause the current row callback to be invoked.
Field db
class EventContext {
public db: RemoteTables;
}
The db field of the context provides access to the subscribed view of the remote database's tables. See Access the client cache.
Field reducers
class EventContext {
public reducers: RemoteReducers;
}
The reducers field of the context provides access to reducers exposed by the remote module. See Observe and invoke reducers.