Live Demo

This is a working SSE counter running on this very site. Click the button to see server-sent events in action.

Server-side counter via SSE

5

How It Works

When you click the button, Datastar sends a GET request to /api/increment. The server atomically increments a counter, renders the Counter component using the type-safe Render API, and sends an SSE event that patches the DOM.

The SSE Handler

This Go handler runs on the server. It uses gastro.Render.Counter() to render the component with the new count, then sends it as a Datastar patch event:

var count atomic.Int64

func handleIncrement(w http.ResponseWriter, r *http.Request) {
    n := count.Add(1)

    html, err := gastro.Render.Counter(
        gastro.CounterProps{Count: int(n)},
    )
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    sse := datastar.NewSSE(w, r)
    sse.PatchElements(html)
}

The Page

The page uses Datastar's data-on:click attribute to trigger the SSE request. No custom JavaScript needed:

---
import Layout "components/layout.gastro"
Title := "Counter"
---
{{ wrap Layout (dict "Title" .Title) }}
    <div id="count">0</div>
    <button data-on:click="@get('/api/increment')">+1</button>
{{ end }}

This pattern works for any real-time UI: dashboards, notifications, live feeds, collaborative editing, and more. See the SSE & Datastar docs for the full API.