Realtime Events

PocketBase pushes realtime messages to browsers over server-sent events. In Pages, page code sends, and browsers receive.

Sending from a page

Turn on the realtime plugin and call ctx.realtime.send():

// pb_pages/+config.ts
module.exports = { plugins: ['realtime'] }
// pb_pages/rooms/[id].ts
module.exports = {
  post(ctx) {
    ctx.realtime.send(`rooms/${ctx.params.id}/delta`, ctx.req.body())
    return ctx.res.json({ ok: true })
  },
}

Limit recipients with a filter:

ctx.realtime.send('alerts', 'Hi', { filter: (client) => !!client.get('auth') })

Listening from a page

ctx.realtime.subscribe() listens to a topic as the visitor, with the collection's rules applied, and gives each change to a for await loop. Stream them with ctx.res.sse(), or as Datastar patches:

// pb_pages/rooms/[id]/live.ts
module.exports = {
  async get(ctx) {
    const stream = ctx.res.sse()
    for await (const msg of ctx.realtime.subscribe(`rooms/${ctx.params.id}/delta`)) {
      stream.send('delta', msg)
    }
  },
}

See ctx.realtime.subscribe().

Receiving in the browser

Use the PocketBase JS SDK:

const pb = new PocketBase(location.origin)

const unsubscribe = await pb.realtime.subscribe(`rooms/${ROOM_ID}/delta`, (e) => {
  console.log('Received delta:', e)
})

// Later
unsubscribe()

The SDK reconnects on its own and resubscribes to its topics after a reconnect.

Hypermedia

To push HTML instead of data, see HTMX Integration and the Datastar add-on.