WebSocket · In depth

SocketService

Route-scoped background worker. Used by `SocketRoute` to run ticks or lifecycle hooks tied to a specific route.

Explain it like I’m five

The simple mental model

A SocketService is a helper that clocks in when its route starts and clocks out when the route stops, such as presence tracking or a periodic snapshot publisher.

When it fits

When should I use it?

Use it for route-scoped background behavior that needs explicit startup, shutdown, and access to the owning route.

A practical API pattern

Follow the example

This pattern explains the named API. Application classes, credentials, and assets may need to be supplied; use a complete recipe for a runnable starting point.

Read this article as Markdown

JavaScript
const { SocketService } = require('redweb')

class ClockService extends SocketService {
  constructor() { super('clock', 1000) }
  onTick() {
    this.route.clients.forEach((socket) => socket.sendJson({ type: 'time', now: Date.now() }))
  }
}
  1. 1

    The service is constructed with a stable name.

  2. 2

    SocketRoute starts it once the route is ready.

  3. 3

    Shutdown awaits the service so timers, subscriptions, and external connections cannot leak.

Surface area

Methods and members

constructor(name, tickRateMs = null)

Stores a service id and optional tick interval; the interval is activated in onInit if onTick exists.

onInit(route)

Called once by SocketRoute, sets `this.route` and, if a tick interval was supplied, schedules recurring onTick execution.

onTick()

Optional; implement to run on the configured interval.

onShutdown()

Clears the tick interval; extend for cleanup hooks.