Build a live job-status panel with Astro and Datastar

Render an export's current status with Astro, stream HTML updates with Datastar, and handle disconnects without confusing the latest state with durable event history.

5 min read
A blue server connected to a coral browser window and a yellow progress ring.

An export takes thirty seconds. Your page needs to tell someone whether it's queued, running, or finished. You can render that status with Astro and update it through one Datastar request while the job runs.

We'll build a small export-status page, stream HTML into it, and recover the current state when the browser reconnects. If you're already reporting job outcomes, this fits alongside our guide to deploys and cron jobs : the page shows progress to the person waiting, while Butters keeps the outcome in your team's feed.

Pick the direction of the conversation

The browser doesn't need to send progress updates. The worker knows what's happening. The browser just needs to hear about it.

Server-sent events give you a response that stays open while the server sends updates. Each message has a small text envelope. Datastar reads that envelope and applies the HTML you send, so the status markup stays on the server.

A normal HTML response is enough when a button saves a setting and returns one result. Here, the status changes several times after the request starts, so a stream is useful. We're not building a chat protocol or asking the browser to reconstruct a job object.

We'll use Astro 7.2.8, the Node adapter 11.1.7, and Datastar 1.0.4. Those are the versions used to check this example. Pin the browser bundle so a later release doesn't change your page unexpectedly.

Give Astro a server

Start with an Astro project and add the Node adapter:

npx astro add node

Keep your existing integrations and configure the adapter in astro.config.mjs:

import { defineConfig } from 'astro/config'
import node from '@astrojs/node'

export default defineConfig({
  output: 'server',
  adapter: node({ mode: 'standalone' }),
})

A static file can't keep an HTTP response open. This route needs on-demand rendering and a host that supports streamed responses. Astro's Node adapter documentation covers the deployment configuration.

Download the pinned Datastar bundle into your public directory:

mkdir -p public/vendor
curl -fL https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.4/bundles/datastar.js \
  -o public/vendor/datastar.js

Hosting the bundle yourself also makes the page independent of a CDN request at runtime.

Start with a snapshot

For a runnable demo, we'll simulate one export. Create src/lib/demo-job.ts:

const startedAt = Date.now()

export function readJob() {
  const elapsed = Date.now() - startedAt
  const progress = Math.min(100, Math.floor(elapsed / 200))
  const state = progress === 100 ? 'Complete' : progress < 10 ? 'Queued' : 'Running'
  return { state, progress }
}

export function renderJob(job = readJob()) {
  const { state, progress } = job
  return `<section id="job-status" aria-label="Export status">
    <h2>Customer export</h2>
    <p>${state}: ${progress}%</p>
    <progress max="100" value="${progress}">${progress}%</progress>
  </section>`
}

The simulated job finishes twenty seconds after this module loads. Restart the development server to repeat it. It doesn't launch a real export or create a durable record. That keeps the demo small enough to understand before you connect your own worker.

The same function supplies the initial page and every streamed update. That matters after a disconnect: a new request can render today's state instead of assuming it saw every earlier message.

These interpolated values come from our own fixed labels and numbers. If your real renderer includes a customer name or user-supplied text, escape it before inserting it into HTML. A stream doesn't make untrusted markup safe.

Render a page that works before streaming

Create src/pages/index.astro:

---
import { renderJob } from '../lib/demo-job'
export const prerender = false
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Export status</title>
    <script is:inline type="module" src="/vendor/datastar.js"></script>
  </head>
  <body>
    <h1>Your export</h1>
    <div data-init="@get('/api/job-status', { requestCancellation: 'cleanup' })">
      <div set:html={renderJob()}></div>
    </div>
    <noscript>Reload this page to check the latest export status.</noscript>
  </body>
</html>

The page contains a real snapshot before Datastar loads. The data-init attribute opens the stream. The explicit cleanup option cancels that request when the owning element is removed.

Keep the subscription attribute outside job-status. We're about to patch that section repeatedly. Replacing the element that owns your subscription makes its lifecycle harder to reason about.

Send HTML as SSE

Create src/pages/api/job-status.ts:

import type { APIRoute } from 'astro'
import { readJob, renderJob } from '../../lib/demo-job'

export const prerender = false

export const GET: APIRoute = ({ request }) => {
  const encoder = new TextEncoder()
  let cleanup = () => {}

  const body = new ReadableStream<Uint8Array>({
    start(controller) {
      let stopped = false
      let tick: ReturnType<typeof setInterval> | undefined
      let heartbeat: ReturnType<typeof setInterval> | undefined

      cleanup = () => {
        if (stopped) return
        stopped = true
        clearInterval(tick)
        clearInterval(heartbeat)
        request.signal.removeEventListener('abort', finish)
      }

      function finish() {
        if (stopped) return
        cleanup()
        controller.close()
      }

      function send(text: string) {
        if (stopped) return
        try {
          controller.enqueue(encoder.encode(text))
        } catch {
          cleanup()
        }
      }

      function patch() {
        const job = readJob()
        const lines = renderJob(job).split('\n').map(line => `data: elements ${line}`)
        send(`event: datastar-patch-elements\n${lines.join('\n')}\n\n`)
        if (job.progress === 100) finish()
      }

      request.signal.addEventListener('abort', finish, { once: true })
      if (request.signal.aborted) {
        finish()
        return
      }
      patch()
      if (!stopped) {
        tick = setInterval(patch, 1000)
        heartbeat = setInterval(() => send(': keepalive\n\n'), 10_000)
      }
    },
    cancel() {
      cleanup()
    },
  })

  return new Response(body, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache, no-transform',
      'X-Accel-Buffering': 'no',
    },
  })
}

Each patch ends with a blank line. Each HTML line gets its own data: elements prefix. Datastar matches the section's ID and morphs the new markup into the existing element. You can inspect the exact wire format in the Datastar SSE reference .

The endpoint sends a snapshot immediately, then checks once a second. This is server-side sampling of the demo state over a streamed response, not a production pub/sub system. For a busy application, trigger patches from your job's update notifications instead of giving every viewer a database query every second.

Heartbeat comments help keep an idle connection active, but they don't update the DOM. Finishing the job closes the response. Disconnecting clears both timers, and stream cancellation has its own cleanup path.

Test the awkward parts

Run npm run dev, open the page, and watch the progress reach 100. In another terminal, inspect the response without buffering it:

curl -N http://localhost:4321/api/job-status

Restart the demo, open the page, and briefly disconnect your network. When a new stream starts, its first patch contains the current state. There is no replay log here, and no promise that every intermediate percentage will appear. For a progress panel, the latest state is usually what you need.

Datastar has configurable request retries, and its GET requests normally close while a page is hidden and reopen when it becomes visible. Those behaviours belong to the client. Durable event history belongs to your application. Check the current action options before changing retry or cancellation settings.

Test the deployed route too. A reverse proxy can buffer a response that streamed correctly in development. X-Accel-Buffering is an Nginx hint, not a universal fix. Check your host's response duration limits and buffering settings, and make sure updates arrive individually rather than together at the end.

Replace the demo with your worker

In production, read status from your job store and authorize access before opening the stream. A job ID in a URL doesn't prove that the person requesting it owns the job.

The module-scoped clock works for one demonstration process. It isn't shared across replicas and doesn't survive a restart. Store real job state in shared storage, and use a notification mechanism that reaches every instance serving viewers. Reconnects should still begin with a fresh snapshot.

Keep progress updates out of your team's event feed unless they're useful there. Record a completed export or a failed export once, from the worker that owns the outcome. The browser may reconnect ten times; that shouldn't produce ten completion events.

The practical rule is simple: render the current state first, stream changes while someone is watching, and let the worker own the durable result.