Skip to main content
Version: 2.0.0

HTTP Handlers

HTTP handlers allow a SpacetimeDB database to expose an HTTP API. External clients can make HTTP requests to routes nested under /v1/database/:name_or_address/route; these requests are resolved to routes defined by the database and then passed to the corresponding HTTP handler.

warning

HTTP handlers are currently in beta, and their API may change in upcoming SpacetimeDB releases.

Defining HTTP Handlers

Define an HTTP handler with spacetimedb.httpHandler.

The function must accept exactly two arguments:

  1. A HandlerContext.
  2. A Request.

The function must return a SyncResponse.

import { schema, SyncResponse } from "spacetimedb/server";

const spacetimedb = schema({});
export default spacetimedb;

export const say_hello = spacetimedb.httpHandler((_ctx, _req) => {
    return new SyncResponse("Hello!");
});

Registering Handlers to Routes

Once you've defined an HTTP handler, you must register it to a route in order to make it reachable for requests.

All routes exposed by your module are declared in a Router. Register the Router for your database by passing it to spacetimedb.httpRouter.

import { Router } from "spacetimedb/server";

export const router = spacetimedb.httpRouter(
    new Router()
        .get("/say-hello", say_hello)
);

Add routes within a router with the get, head, options, put, delete, post, patch and any methods, which register an HTTP handler for that HTTP method at a given path.

Nest routers with router.nest(prefix, subRouter), which causes subRouter to handle routing for all paths that start with prefix.

Combine routers with router.merge(otherRouter), which combines both routers.

Strict Routing

SpacetimeDB uses strict routing, meaning that a request must match a path exactly in order to be routed to that handler. Trailing slashes are significant.

Sending Requests

Routes defined by a SpacetimeDB database are exposed under the prefix /v1/database/:name/route. To access the say-hello route above, send a request to $SPACETIMEDB_URI/v1/database/$DATABASE/route/say-hello, where $SPACETIMEDB_URI is the SpacetimeDB host (usually https://maincloud.spacetimedb.com), and $DATABASE is the name of the database.