Skip to content
GitHub

Strutvane 0.2 is still being built. These pages describe how it will work; anything marked "Coming in 0.2" doesn't exist yet. Release notes and support policy.

Broadcasting

View as Markdownllms.txt

Normally a page shows what the server said when it loaded, and nothing changes until you reload. Broadcasting lets the server push a message to every open tab that’s listening: “post 42 was published”, “Grace is now editing this invoice”, “you have a new notification”. Tables refresh themselves, the bell lights up, and two people editing the same record see each other.

Messages travel over a WebSocket: a connection the browser keeps open to the server, so the server can send at any time. A channel is a named stream of messages (“posts”, “team.7.projects”); a page subscribes to the channels it cares about.

  1. Install the package:

    Terminal window
    node strut install:realtime

    What you’ll see (something like this):

    ✔ Installed @strutvane/realtime
    ✔ Wrote config/broadcasting.ts and routes/channels.ts
    ✔ Registered the "realtime" dev process (npm run dev starts it)
    ✔ The generated admin tables now refresh live
  2. Open the Posts screen in two browser windows, signed in as two different users of the same team.

  3. Publish a post in one window.

What you’ll see: the other window’s table updates within a moment, without a reload, showing only the posts that user may see.

That’s model broadcasting, switched on for every generated resource. The rest of this page is for your own screens and events.

Kind Who may listen Example Use it for
Public anyone, signed in or not status a public status banner
Private signed-in users your rule allows posts.42 updates about one record
Presence like private, and everyone sees who else is listening posts.42.editing “Grace is also editing this post”

Private and presence channels are authorised: when a tab subscribes, the server asks your rule whether this user may listen. A refused subscription is just refused; the tab learns nothing about the channel.

routes/channels.ts
import { allows } from '@strutvane/framework'
import { defineChannels } from '@strutvane/realtime'
import { Post } from '../app/models/post.ts'
import { PostPolicy } from '../app/policies/post.policy.ts'
const policy = new PostPolicy()
export default defineChannels((channel) => {
// Only users who may view the post hear about it. The same policy as GET /api/posts/{post}.
channel.private('posts.{post}', { post: Post }, (user, post) => allows(policy, 'view', user, post))
// Presence: return what others may see about this user (never more than their name).
channel.presence('posts.{post}.editing', { post: Post }, async (user, post) =>
user !== null && (await allows(policy, 'update', user, post)) ? { id: user.id, name: user.name } : false,
)
})

{post} is bound like a route parameter, so the rule receives the post, or the subscription fails as “not found” when the user may not see it.

Team-scoped by construction: channel names are prefixed with the current team behind the scenes. A user of team A subscribing to posts.42 subscribes to team A’s posts.42; there is no way to name another team’s channel.

Make an event broadcastable by saying which channels it goes to:

app/events/post-published.event.ts
import { defineBroadcast } from '@strutvane/realtime'
import type { Post } from '../models/post.ts'
export const PostPublished = defineBroadcast('post.published', (post: Post) => ({
on: [`posts.${post.id}`, 'posts'],
payload: { id: post.id, title: post.title, slug: post.slug },
}))

Send it from your code:

app/http/controllers/post.controller.ts
import { broadcast } from '@strutvane/realtime'
import { PostPublished } from '../../events/post-published.event.ts'
await broadcast(PostPublished(post), { afterCommit: true })

What you’ll see: every tab subscribed to posts.42 or posts receives { id: 42, title: 'Hello world', slug: 'hello-world' }.

  • afterCommit: true waits until the database transaction has committed, so listeners never fetch a post that doesn’t exist yet.
  • Payloads are filtered through the model’s serializer and read rules: hidden and secret columns are never sent, even if you pass the whole model.
  • Broadcasting goes through the queue when one is configured, so a slow WebSocket server never slows down the request.

Every generated resource broadcasts created, updated, deleted and restored for its records, on a channel per record and one per list. The admin tables listen to the list channel and refetch the rows the user may see (they don’t trust the pushed data to decide visibility). Turn it off for a model:

app/models/post.ts
export class Post extends Model('posts', { fillable: ['title', 'body', 'status'], broadcasts: false }) {}

The package’s client subpath is the Echo-like part:

resources/ui/lib/live.ts
import { realtime } from '@strutvane/realtime/client'
const live = realtime() // connects to the app's WebSocket server, signed in with the session cookie
// A private channel
const unsubscribe = live.private('posts.42').listen('post.published', (post) => {
console.log(`"${post.title}" is live`)
})
// A presence channel
live.presence('posts.42.editing')
.here((people) => showEditors(people))
.joining((person) => addEditor(person))
.leaving((person) => removeEditor(person))
// Later, when the page goes away
unsubscribe()

In React, the UI kit’s hooks do the subscribing and cleaning up for you:

resources/ui/pages/posts/show.tsx
import { usePresence } from '@strutvane/ui/realtime'
export function EditingBadge({ postId }: { postId: number }) {
const editors = usePresence(`posts.${postId}.editing`)
return editors.length > 1 ? <span>{editors.length - 1} other person editing</span> : null
}

Notifications can use a broadcast channel. With @strutvane/realtime installed, the bell updates the moment a notification is stored; without it, the bell checks again when the window regains focus.

  • Development: npm run dev starts the WebSocket server as one more process, next to the app and Vite. In Docker mode it runs in the app container like everything else.
  • Production: run it as its own long-running process (or container) next to the web server. With more than one WebSocket server, they share messages through Redis (see Redis).
  • Behind a proxy, allow WebSocket upgrades on the realtime path, and keep the connection timeout above the client’s ping interval.
Situation What users see
Wi-Fi drops, laptop sleeps the client reconnects by itself and re-subscribes; tables refetch once to catch up on what they missed
The WebSocket server is down the app works normally; pages just stop updating live, and a quiet “Live updates paused” notice appears
A subscription is refused nothing is shown; the channel stays silent
The session expires subscriptions to private channels end; the usual session-expired notice appears

Live updates are a convenience on top of the normal API, never the only way to see data.

  • With Docker, the realtime server runs inside the app container; its port is forwarded to 127.0.0.1 like the app’s.
  • Without Docker, npm run dev runs it on your machine. Windows, macOS and Linux behave the same.

Why: the realtime server isn’t running (only the web server is), the event wasn’t broadcast on the channel the page listens to, or the subscription was refused. Fix: check that npm run dev shows the realtime process, compare the channel names, and check the channel rule for that user.

Why: this can’t happen through channel names (they’re team-scoped), so look for a custom server-side broadcast that sends another team’s data on purpose, for example from a command running without a team. Fix: broadcast inside the team’s context; jobs and requests carry it automatically.

The browser shows a secret column in the payload

Section titled “The browser shows a secret column in the payload”

Why: it can’t, if the payload goes through the model’s serializer. A hand-built payload object bypasses it. Fix: pass model data through the serializer, or list only the fields you mean to send.

Why: the broadcast was sent inside a transaction that hadn’t committed yet. Fix: broadcast(event, { afterCommit: true }).