Zero2Scale

SSE and Datastar: let the server be the only owner of state

12 min read


In the previous article I wrote about Functional Core, Imperative Shell, which keeps business rules in one place. This article takes the same idea to the web page. If the rules live on the server in one place, why does the page's state still live in several?

My answer is that it doesn't have to. The tools that make this practical are Server-Sent Events (SSE) and Datastar.

The problem: many copies of the truth

Picture an online shop built with React, Vue, or Svelte the way most are today. One customer's cart can exist in several places at once:

  1. in the database
  2. in the JSON the API returned
  3. in a client cache such as React Query or SWR
  4. in a global store such as Redux, Zustand, or Pinia
  5. in the state of the component that draws the number on the cart icon
  6. in an optimistic update that changed the number early "because it will probably work"

Every copy is a chance for the data to disagree, and the bugs that follow are familiar:

  • The cart icon says 3 items, but the cart page shows 2.
  • An admin has cancelled the order, but the customer's open tab still shows a "Pay now" button.
  • The "Delete" button is hidden based on the user's permissions, but the permissions in the client were loaded at login an hour ago.
  • Form validation exists twice: once in Zod on the client, once in Go on the server. Someone updates one of them, and now a form passes on one side and fails on the other.

These bugs don't happen because the team writes bad code. They happen because the architecture copies the truth to several places and then tries to keep every copy in sync at all times. That is one of the hardest problems in computing. There is a reason cache invalidation is one of the proverbial two hard things.

And the work that takes the most time is often not the features. It's the work of keeping these copies in sync: writing the API, writing TypeScript types that match the Go structs, deciding when to refetch, and chasing bugs that only appear when a user has two tabs open.

The idea: the server knows the state, and sends HTML

React taught us UI = f(state). That's a great idea, but React chose to run f in the browser, so the state has to be shipped across the network into the browser too.

Datastar asks a slightly different question: why not run f where the state actually lives?

  • The state lives on the server (the database, the session, the business rules).
  • The server turns that state into HTML.
  • The browser takes that piece of HTML and swaps it into the page.

The browser no longer keeps a copy of the truth. It only has whatever the server sent last. If you want to know how many items are in the cart, you ask the server, and it answers with HTML that is already correct. The cart icon and the cart page can't show different numbers, because both are built from the same data, by the same code, in the same place.

So the bugs listed above aren't "fixed". They have nowhere to happen in the first place.

SSE: how the server talks to the browser

If the server owns the state, it needs a way to send changes to the browser. Server-Sent Events is a web standard that has done this for years, and it is surprisingly simple.

An SSE response is an ordinary HTTP response with Content-Type: text/event-stream. The server keeps writing messages to it, one event at a time, in plain text a person can read:

event: datastar-patch-elements
data: elements <span id="cart-count">2</span>

That's all. No new protocol, no connection upgrade, no binary framing. What follows from that:

  • Your existing infrastructure just works. Load balancers, proxies, CDNs, gzip or Brotli compression, cookies, and the authentication you already have, because it's HTTP.
  • Reconnection is built in. When the network drops, you don't write reconnect logic.
  • It's easy to debug. Open DevTools, or use curl, and you can read the messages.
  • One mechanism for one-off answers and live streams. Send one event and close, or hold the connection open and push updates in real time. It's the same thing.

Many people reach for WebSocket first when they hear "real-time". For most web pages, two-way messaging is more than you need. The browser can already send data to the server with a normal HTTP request. What was missing is a way for the server to answer more than once, and SSE does exactly that.

Datastar: the bridge between HTML and SSE

Datastar is a small, single-file JavaScript library. No build step, no node_modules. You describe the page's behaviour with data-* attributes directly in your HTML, and every action that talks to the server (@get, @post, ...) receives its answer as SSE.

The server answers with two main kinds of event:

  • datastar-patch-elements sends HTML that replaces the element in the page with the same id. Datastar morphs the DOM, changing only what is different, so an input the user is typing in keeps its focus.
  • datastar-patch-signals updates signals in the browser. You'll use it far less than the first one.

Signals are Datastar's browser-side state. That sounds like we're back to several copies, but the difference is in how they're used. Signals are for screen state: the text being typed, whether a menu is open, whether a request is in flight. They are not for business state like a cart or an order's status. That always stays on the server and arrives as rendered HTML.

Example 1: searching this website

Open the search page and start typing. The results change as you type. With JavaScript turned off, the same page still works as a plain form that reloads on Enter.

The search box looks like this:

<form action="/search" method="get" role="search">
  <input type="search" name="q" value="{{Query}}"
         data-bind:q
         data-on:input__debounce.250ms="@get('/search')">
</form>
  • data-bind:q binds the input's value to a signal named q.
  • data-on:input__debounce.250ms says: once the user stops typing for 250 milliseconds, send @get('/search') along with the signals.

On the server, one route handles both cases. A request from Datastar gets just the results back as a patch. Any other request gets the whole page.

func (s *server) search(c fiber.Ctx) error {
    env := s.env(c)
    posts := s.Site.Posts(env.Lang)
    if sse.IsDatastar(c) {
        var sig struct {
            Q string `json:"q"`
        }
        if err := sse.ReadSignals(c, &sig); err != nil {
            return fiber.NewError(fiber.StatusBadRequest, err.Error())
        }
        q := search.Normalize(sig.Q)
        frag, err := s.Render.Fragment("search-results",
            view.Results(env.Lang, q, search.Run(posts, q, maxSearchResults)))
        if err != nil {
            return err
        }
        return sse.Send(c, func(w io.Writer) error {
            return sse.WritePatchElements(w, frag, sse.PatchOptions{})
        })
    }

    q := search.Normalize(c.Query("q"))
    b, err := s.Render.Page("search",
        view.Search(env, q, search.Run(posts, q, maxSearchResults)))
    if err != nil {
        return err
    }
    return sendHTML(c, b)
}

What I want you to notice is what isn't there:

  • no JSON API for search
  • no TypeScript types to keep in step with Go
  • no client-side component to display results, because the same search-results partial is used for both the full page and the patch
  • no search state in the browser that can go stale or disagree with the real data

The search logic (search.Normalize, search.Run) lives in the core and is tested with plain tables. The HTML it produces is tested with golden files on the server. You don't need a real browser to check that search returns the right results.

Example 2: the contact form, with one set of validation rules

This website's contact form submits with @post:

<form action="/contact" method="post"
      data-on:submit="@post('/contact', {contentType: 'form', retry: 'never'})"
      data-indicator:_contactsending>
  ...
  <button type="submit" data-attr:disabled="$_contactsending">Send message</button>
</form>

When the user submits, the server validates the data with contact.Validate, a function in the core. If a field is wrong, the server renders the form again with an error message under that field and sends the whole form back as a patch.

So there is one set of validation rules, in one language, tested in one place. The error messages are the same ones the page shows without JavaScript. data-indicator:_contactsending is pure screen state: it disables the button while the request is in flight. A signal name that starts with _ tells Datastar not to send it to the server, because it's not something the server needs to know.

Example 3: real-time, without client-side state

Back to the bug where an admin cancels an order but the customer still sees "Pay now". If the order status page holds an SSE connection open, the server renders a new order card every time the status changes and sends it to every tab that has the page open.

<div data-init="@get('/orders/1042/live')">
  <div id="order-1042"> ... </div>
</div>
// Sketch: hold the connection open and send a new card whenever the status changes.
func (s *server) orderLive(c fiber.Ctx) error {
    id := strings.Clone(c.Params("id"))
    updates := s.Orders.Subscribe(id)
    return sse.Stream(c, func(emit func(func(io.Writer) error) error) {
        defer s.Orders.Unsubscribe(id, updates)
        for o := range updates {
            frag, err := s.Render.Fragment("order-card", view.OrderCard(o))
            if err != nil {
                return
            }
            if emit(func(w io.Writer) error {
                return sse.WritePatchElements(w, frag, sse.PatchOptions{})
            }) != nil {
                return // the user closed the tab
            }
        }
    })
}

The buttons on the card are decided by a view model on the server, from the real status at that moment. Once the order is cancelled, the new card has no "Pay now" button. No client-side code listens for events and decides which buttons to hide, and no tab is left behind showing old data.

If the customer manages to click the old button before the card updates, that request still goes through the status transition function in the core, which answers ErrInvalidTransition, as in the FCIS article. The rule is enforced in one place, and the screen is just a reflection of it.

What you get

SPA + JSON API Server owns state + Datastar
Source of truth many copies, kept in sync by hand one: the server
Business rules and validation often duplicated on both sides one set, in the core
Code to maintain API, DTOs, client types, store, components handler, view model, template
JavaScript sent to users the whole app bundle one library file
Works without JavaScript usually not yes, Datastar is only an enhancement
Real-time WebSocket plus client-side code SSE and the same templates
Testing both sides, plus the seam between them mostly on the server

One more thing you can't ignore is team speed. When work isn't split into "the API" and "the screen", one developer can ship a feature from the database to the button in a single pull request, without waiting on another team or agreeing on a JSON shape first.

Limits worth knowing

I believe in this approach, but it isn't right for everything.

  • Every interaction goes to the server. Users far from the server will feel the latency. For most websites this isn't a problem, and morphing only what changed makes the page feel faster than you'd expect. But drawing on a canvas, games, or image editors need real client-side JavaScript. You can still use that as a web component in one spot, alongside Datastar.
  • Offline apps have to keep state in the browser by their nature.
  • Real-time pages hold connections open, so your server has to handle that. Go does this easily, but make sure your proxy doesn't buffer the response. This website sets X-Accel-Buffering: no for nginx.
  • It takes a change of habit. People used to SPAs will want to keep data in signals because it's convenient. My rule: if the server needs a piece of data to make a decision, that data shouldn't be a signal.

If you build ordinary web applications (back offices, dashboards, shops, forms, content sites), which is most of the industry, these limits barely matter, while the benefits apply to every feature you write.

You can start tomorrow

You don't need to rewrite your app. Datastar can be added to server-rendered pages one page at a time.

  1. Pick the page with the most out-of-sync state bugs, or the one whose validation rules are duplicated on both sides.
  2. Pull the part of the page that changes often into a partial with a stable id, and use that partial for both the full page and the patch.
  3. Make the page work without JavaScript first, with plain forms and links.
  4. Add data-on with @get or @post, and have the handler answer with datastar-patch-elements when the request comes from Datastar.
  5. Delete the client-side code that used to hold that page's state. This is the most satisfying step.

When the server is the only owner of state, "the data doesn't match" bugs have nowhere left to happen. The time you used to spend keeping copies of the truth in sync goes back into building features your users actually want.

Sources

  • Datastar: the official site, with the guide, examples, and the full attribute reference.
  • Server-sent events in the HTML Standard: the SSE specification, including the event: and data: format used in this article.
  • Hypermedia Systems: a book you can read free online. It explains using HTML to represent application state, which is the foundation this family of tools is built on.