SSE API

Complete reference for the Server-Sent Events interface.

Client-Side (HTMX)

Connecting

<!-- Connect to SSE endpoint -->
<div hx-sse="connect:/sse">
  <!-- Child elements can subscribe to events -->
</div>

Subscribing to Events

<!-- Swap content when 'messages' event is received -->
<ul id="messages" hx-sse="swap:messages">
  <!-- Content will be replaced -->
</ul>

<!-- Multiple subscriptions -->
<div hx-sse="swap:users swap:notifications">
  <!-- Responds to both events -->
</div>

Server-Side (ctx.sse)

sse.subscribe
subscribe(tables: string | string[]): void

Subscribe the current request to updates from specific database tables.

Parameters
NameTypeDescription
tables string | string[] Table name(s) to subscribe to
Example
export async function loader(ctx) {
  // Subscribe to changes in messages and users tables
  ctx.sse.subscribe(['messages', 'users']);
  
  const messages = ctx.db.query('SELECT * FROM messages');
  return { messages };
}
sse.broadcast
broadcast(event: string, data: string): void

Broadcast a custom event to all connected clients.

Parameters
NameTypeDescription
event string Event name
data string HTML or data to send
Example
// Broadcast a notification to all clients
ctx.sse.broadcast('notification', `
  <div id="notification" hx-swap-oob="true">
    New message received!
  </div>
`);

Automatic Subscriptions

When you query a table using ctx.db, MiniWork automatically tracks which tables were accessed. When those tables are modified, updates are broadcast to subscribed clients.

// This loader auto-subscribes to 'posts' table
export async function loader(ctx) {
  const posts = ctx.db.query('SELECT * FROM posts');
  return { posts };
}

// When any client adds a post, all subscribers get updated
export async function action(ctx) {
  const { title } = await ctx.json();
  ctx.db.run('INSERT INTO posts (title) VALUES (?)', [title]);
  // ^^ This triggers SSE broadcast to 'posts' subscribers
}
OOB Swaps

SSE updates use HTMX out-of-band swaps. Elements with matching IDs are replaced automatically without a full page refresh.