Skip to main content

Lifecycle Reducers

Special reducers handle system events during the database lifecycle.

Init Reducer

Runs once when the module is first published or when the database is cleared.

spacetimedb.init((ctx) => {
  console.log('Database initializing...');
  
  // Set up default data
  if (ctx.db.settings.count === 0) {
    ctx.db.settings.insert({
      key: 'welcome_message',
      value: 'Hello, SpacetimeDB!'
    });
  }
});

The init reducer:

  • Cannot take arguments beyond ReducerContext
  • Runs when publishing with spacetime publish
  • Runs when clearing with spacetime publish -c
  • Failure prevents publishing or clearing

Client Connected

Runs when a client establishes a connection.

spacetimedb.clientConnected((ctx) => {
  console.log(`Client connected: ${ctx.sender}`);
  
  // ctx.connectionId is guaranteed to be defined
  const connId = ctx.connectionId!;
  
  // Initialize client session
  ctx.db.sessions.insert({
    connection_id: connId,
    identity: ctx.sender,
    connected_at: ctx.timestamp
  });
});

The client_connected reducer:

  • Cannot take arguments beyond ReducerContext
  • ctx.connection_id is guaranteed to be present
  • Failure disconnects the client
  • Runs for each distinct connection (WebSocket, HTTP call)

Client Disconnected

Runs when a client connection terminates.

spacetimedb.clientDisconnected((ctx) => {
  console.log(`Client disconnected: ${ctx.sender}`);
  
  // ctx.connectionId is guaranteed to be defined
  const connId = ctx.connectionId!;
  
  // Clean up client session
  ctx.db.sessions.connection_id.delete(connId);
});

The client_disconnected reducer:

  • Cannot take arguments beyond ReducerContext
  • ctx.connection_id is guaranteed to be present
  • Failure is logged but doesn't prevent disconnection
  • Runs when connection ends (close, timeout, error)

Scheduled Reducers

Reducers can be triggered at specific times using scheduled tables. See Scheduled Tables for details on:

  • Defining scheduled tables
  • Triggering reducers at specific timestamps
  • Running reducers periodically
  • Canceling scheduled executions
Scheduled Reducer Context

Scheduled reducer calls originate from SpacetimeDB itself, not from a client. Therefore:

  • ctx.sender will be the module's own identity
  • ctx.connection_id will be None/null/undefined