Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Add live updates with SSE, HTMX, and Idiomorph

Extend your Slabs app so changes made in one browser tab appear immediately in every other open tab. You will add an SSE stream with ctx.realtime.sse_stream, broadcast Maud HTML fragments with ctx.realtime.publish_html, morph regions in place with Idiomorph, track online participants with ctx.realtime.track_presence, and guard WebSocket upgrades with validate_ws_origin.

How Slabs realtime works

AppCtx.realtime is an in-process broadcast hub backed by tokio::sync::broadcast. Each named topic (such as "board:brd_123" or "room:rm_456") holds a 256-message ring buffer.

  • ctx.realtime.sse_stream(topic) returns an Axum Sse response with a 15-second "ping" keep-alive comment. Slow receivers skip lagged events instead of disconnecting.
  • ctx.realtime.publish_html(topic, event, html) pushes an HTML fragment to every subscriber on topic.
  • ctx.realtime.track_presence(topic, user_id, meta) registers an online participant and returns a PresenceGuard that removes the entry automatically when the connection drops.
  • html::document(...) loads /_slabs/vendor/htmx.min.js, /_slabs/vendor/htmx-ext-sse.js, and /_slabs/vendor/idiomorph-ext.min.js, and attaches hx-ext="morph" on <body>.

Step 1. Add an SSE stream slab

Create slabs/realtime/notes_sse.rs. Check authentication or room permissions first on private streams, then return ctx.realtime.sse_stream(...).

#![allow(unused)]
fn main() {
use axum::{extract::State, response::IntoResponse};
use slabs::prelude::*;

pub fn slab() -> SlabDef {
    SlabDef::get("/notes/stream", handle)
        .name("realtime.notes_sse")
        .summary("Stream live note HTML fragments over SSE")
}

async fn handle(State(ctx): State<AppCtx>) -> impl IntoResponse {
    ctx.realtime.sse_stream("notes:global")
}

#[cfg(test)]
mod tests {
    use axum::http::StatusCode;

    #[tokio::test]
    async fn sse_route_is_registered_in_manifest() {
        let app = crate::test_app().await;
        let res = app.get("/_slabs/manifest").await;
        assert_eq!(res.status, StatusCode::OK);
        assert!(res.text().contains("/notes/stream"));
    }
}
}

Step 2. Publish HTML after the database commit

Publish to ctx.realtime only after tx.commit().await? succeeds. Browsers will never receive an event for a transaction that rolled back.

Update slabs/notes/create_note.rs:

#![allow(unused)]
fn main() {
use axum::{extract::State, http::StatusCode, Form};
use chrono::Utc;
use serde::Deserialize;
use slabs::prelude::*;

pub fn slab() -> SlabDef {
    SlabDef::post("/notes", handle)
        .name("notes.create_note")
        .summary("Insert a note and broadcast it to SSE subscribers")
}

#[derive(Debug, Deserialize)]
pub struct Input {
    pub body: String,
}

async fn handle(
    State(ctx): State<AppCtx>,
    Form(input): Form<Input>,
) -> SlabResult<StatusCode> {
    let body = input.body.trim().to_string();
    if body.is_empty() {
        return Err(SlabError::validation("body", "note body cannot be blank"));
    }

    let note_id = id::new("nte");
    let now = Utc::now().to_rfc3339();

    let mut tx = ctx.db.begin().await?;
    sqlx::query("INSERT INTO notes (id, body, created_at) VALUES (?, ?, ?)")
        .bind(&note_id)
        .bind(&body)
        .bind(&now)
        .execute(&mut *tx)
        .await?;
    tx.commit().await?;

    let fragment = maud! {
        article id=(format!("note-{note_id}")) class="card p-3" {
            p class="text-sm" { (body) }
            p class="text-xs text-muted-foreground mt-1" { (now) }
        }
    };

    ctx.realtime
        .publish_html("notes:global", "note_created", fragment.into_string());

    Ok(StatusCode::NO_CONTENT)
}
}

Returning StatusCode::NO_CONTENT from the form post lets the SSE stream insert the new element once for both the sender and every other connected viewer, so the page never renders duplicate rows.

Step 3. Connect HTMX SSE in your page slab

In slabs/notes/list_notes.rs, add hx-ext="sse", sse-connect="/notes/stream", and sse-swap="note_created" to the list container:

#![allow(unused)]
fn main() {
section id="notes-list"
        hx-ext="sse"
        sse-connect="/notes/stream"
        sse-swap="note_created"
        hx-swap="afterbegin"
        class="space-y-2" {
    @for note in &notes {
        article id=(format!("note-{}", note.id)) class="card p-3" {
            p class="text-sm" { (note.body) }
            p class="text-xs text-muted-foreground mt-1" { (note.created_at) }
        }
    }
}
}

Step 4. Morph updated regions with Idiomorph

When an event replaces a card, form, or modal body instead of appending a new row, use hx-swap="morph:innerHTML" or hx-swap="morph:outerHTML". Idiomorph diffs the incoming HTML against the live DOM and patches only changed attributes and text nodes. Open inputs keep focus and scroll positions stay put.

#![allow(unused)]
fn main() {
// Replace an existing board region in place when its columns change
ctx.realtime.publish_html(
    &format!("board:{board_id}"),
    "board_updated",
    rendered_columns.into_string(),
);
}

In the HTML container:

#![allow(unused)]
fn main() {
div id="board-columns"
    hx-ext="sse"
    sse-connect=(format!("/boards/{board_id}/stream"))
    sse-swap="board_updated"
    hx-swap="morph:innerHTML" {
    // Server-rendered columns
}
}

Step 5. Track online presence and guard WebSockets

ctx.realtime includes in-memory presence tracking for rooms, boards, and collaborative documents. Hold the returned PresenceGuard for the lifetime of the connection so the participant is removed automatically on disconnect.

#![allow(unused)]
fn main() {
use serde_json::json;

let _presence = ctx.realtime.track_presence(
    &format!("room:{room_id}"),
    &session.user_id,
    json!({ "name": user_name }),
);

// List currently connected participants on the topic
let online: Vec<PresenceEntry> = ctx
    .realtime
    .list_presence(&format!("room:{room_id}"));
}

If a slab upgrades a connection to a WebSocket, validate the browser Origin header before accepting the upgrade to block Cross-Site WebSocket Hijacking (CSWSH):

#![allow(unused)]
fn main() {
use axum::http::HeaderMap;
use slabs::prelude::*;

if !validate_ws_origin(&headers, &ctx.config.cors_origins) {
    return Err(SlabError::forbidden("cross-origin websocket blocked"));
}
}

validate_ws_origin requires a valid Origin header matching either the request Host or an explicit origin configured in SLABS_CORS_ORIGINS.

Step 6. Test realtime broadcasts and presence in isolation

You do not need a browser to verify SSE broadcasts or presence tracking. Subscribe to the topic on app.ctx.realtime before calling the mutation slab:

#![allow(unused)]
fn main() {
#[tokio::test]
async fn create_note_broadcasts_html_fragment() {
    let app = crate::test_app().await;
    let mut rx = app.ctx.realtime.subscribe("notes:global");

    let res = app
        .post_form("/notes", &[("body", "Broadcast test")])
        .await;
    assert_eq!(res.status, axum::http::StatusCode::NO_CONTENT);

    let msg = rx.try_recv().expect("expected realtime message");
    assert_eq!(msg.event, "note_created");
    assert!(msg.data.contains("Broadcast test"));
}
}

Run mise exec -- cargo nextest run to verify the test passes, then open two browser windows side by side with slabs dev to watch notes appear live.