Open in a new tab

Stream a server's events into the page with Server-Sent Events, reconnect with a growing delay when the connection drops, and resume right after the last event seen, so none is missed or shown twice.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

The server talks and the page listens: a deploy or an export in progress, notifications, prices, a dashboard. Server-Sent Events go over plain HTTP, reconnect on their own and need no library on the server. When the page must also talk back over the same channel (chat, collaboration), use fw's ws module over a WebSocket server instead.

Copy-paste steps

  1. npm install @awacloud/fw

  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).

  3. Copy index.html, main.js and stand-in-events.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.

  4. In your app, delete stand-in-events.js and its import, and serve the stream yourself. With Node and no dependency, the endpoint is:

    import { createServer } from 'node:http';
    createServer((req, res) => {
        const from = Number(new URL(req.url, 'http://localhost').searchParams.get('lastEventId') ?? 0);
        res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
        // for each new step, after `from`: give it an id, a name and its data
        res.write(`id: ${from + 1}\nevent: step\ndata: ${JSON.stringify({ text: 'Install' })}\n\n`);
    }).listen(8080);
    

What it shows

  • sse.connect(url, { retry: { initial, max, factor } }) opens the stream; on('step', (data, event) => …) receives each named event with its event.lastEventId; on('open'), on('done') and close().
  • on('reconnect', ({ attempt, delay }) => …): after a drop, fw waits a delay that grows by factor up to max, says so, and reconnects with ?lastEventId=<last id> (a browser cannot set headers on an EventSource), so the server resumes after it.
  • A browser without EventSource gets a sentence, not an error.
  • stand-in-events.js plays the server inside the page so the example runs anywhere: six deploy steps, one dropped connection after the third, and a resume from the lastEventId it is given. Every other URL gets the browser's own EventSource.

Code

main.js

javascriptApache-2.055 lines

// SPDX-License-Identifier: Apache-2.0
// The stand-in plays the event stream in the page; in your app, delete this import and the file.
import { standIn } from './stand-in-events.js';
import fw from '@awacloud/fw';
import { sse } from '@awacloud/fw/dom/net/sse.js';

fw.runtime.registerAllDeep([sse]);
const SSE = fw.runtime.resolve('sse');
export { standIn };

const list = /** @type {HTMLElement} */ (document.getElementById('steps'));
/** @param {string} text */
const show = (text) => { /** @type {HTMLElement} */ (document.getElementById('status')).textContent = text; };
/** @type {any} */
let connection = null;

/**
 * Follow the deploy's event stream: each `step` event is listed once, with
 * the id the server gave it. When the connection drops, fw reconnects with
 * a growing delay and sends the last id seen, so the server resumes after it.
 * @param {{ retryMs?: number }} [opts]
 * @returns {any} the connection, or null without EventSource
 */
export function follow({ retryMs = 1000 } = {}) {
    stop();
    list.replaceChildren();
    if (typeof globalThis.EventSource !== 'function') {
        show('this browser has no EventSource: no live updates');
        return null;
    }
    show('connecting…');
    const url = new URL('./api/deploy-events', location.href).href;
    connection = SSE.connect(url, { retry: { initial: retryMs, max: 30000, factor: 2 } });
    connection.on('open', () => show('connected'));
    connection.on('step', (/** @type {string} */ data, /** @type {MessageEvent} */ event) => {
        list.appendChild(document.createElement('li')).textContent = `#${event.lastEventId} ${JSON.parse(data).text}`;
    });
    connection.on('reconnect', (/** @type {{ attempt: number, delay: number }} */ r) => {
        show(`connection lost: reconnecting in ${r.delay} ms (attempt ${r.attempt})`);
    });
    connection.on('done', () => {
        stop();
        show('deploy finished');
    });
    return connection;
}

/** Close the stream: no more events, no reconnect. */
export function stop() {
    connection?.close();
    connection = null;
}

document.getElementById('restart')?.addEventListener('click', () => follow());
follow();

index.html

htmlApache-2.025 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Follow live updates from the server</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Follow live updates from the server</h1>
    <p>A deploy streamed as Server-Sent Events by a stand-in server that runs in the page. The connection drops once,
      after the third step: watch it reconnect and resume.</p>
    <p>Status: <output id="status" aria-live="polite"></output></p>
    <ol id="steps"></ol>
    <p><button id="restart" type="button">Restart the deploy</button></p>
  </main>
</body>
</html>

stand-in-events.js

javascriptApache-2.048 lines

// SPDX-License-Identifier: Apache-2.0
// A stand-in for YOUR server's event stream, so this page runs anywhere, also
// with no backend: it plays a deploy as Server-Sent Events on ./api/deploy-events,
// drops the connection once after the third step, and resumes from the
// `lastEventId` query parameter like a real server would. Delete this file and
// its import in your app; every other URL gets the browser's EventSource.

export const standIn = { intervalMs: 700, dropAfter: 3, urls: /** @type {string[]} */ ([]) };
const STEPS = ['Fetch the sources', 'Install', 'Run the tests', 'Build', 'Upload', 'Switch traffic'];
const NativeEventSource = globalThis.EventSource;

class StandInEventSource extends EventTarget {
    /** @type {ReturnType<typeof setInterval> | undefined} */
    #timer;
    /** @param {string | URL} url @param {EventSourceInit} [init] */
    constructor(url, init) {
        super();
        const parsed = new URL(String(url), location.href);
        // Any other URL is a real stream: hand back the browser's own EventSource.
        if (!parsed.pathname.endsWith('/api/deploy-events')) return new NativeEventSource(url, init);
        this.url = parsed.href;
        this.readyState = 0;
        standIn.urls.push(this.url);
        const from = Number(parsed.searchParams.get('lastEventId') ?? 0);
        let id = from;
        setTimeout(() => { this.readyState = 1; this.dispatchEvent(new Event('open')); });
        this.#timer = setInterval(() => {
            id++;
            const data = JSON.stringify({ text: STEPS[id - 1] });
            this.dispatchEvent(new MessageEvent('step', { data, lastEventId: String(id) }));
            if (id === STEPS.length) {
                this.dispatchEvent(new MessageEvent('done', { data: '{}', lastEventId: String(id) }));
                this.close();
            } else if (from === 0 && id === standIn.dropAfter) {
                this.close();
                this.dispatchEvent(new Event('error')); // the network dropped
            }
        }, standIn.intervalMs);
    }

    close() {
        clearInterval(this.#timer);
        this.readyState = 2;
    }
}

// @ts-ignore: the stand-in replaces the constructor for this page only
globalThis.EventSource = StandInEventSource;