One Stream, Many Tabs: Live Updates With Server-Sent Events That Do Not Move the Page

René Kulik on 25.11.2026

Introduction

One of my side projects is a server-rendered web app: Fastify on the server, Eta templates, plain HTML forms, and Tailwind for the styling. No frontend framework. In the background, the server runs jobs that find new entries, and I wanted open pages to learn about those entries without a reload.

That sounds like a job for WebSockets and a client-side framework. It turned out to be about a hundred lines of plain JavaScript, built on three browser APIs that I think are underused: server-sent events, the Web Locks API, and BroadcastChannel.

In this post, I will show how the live updates work, why the page never changes the list on its own, and how all open tabs share a single connection.

Why Server-Sent Events

The updates only flow in one direction, from the server to the page. When I do something on the page, like marking an entry as done, that is a normal HTTP request. I do not need a two-way channel.

Server-sent events are exactly that. The page opens a long-lived HTTP request, and the server writes text events into it whenever something happens. The browser API is a single class:

const events = new EventSource('/events');

events.addEventListener('entries-added', (event) => {
  const data = JSON.parse(event.data);
});

It runs over plain HTTP, so there is no protocol upgrade and no extra library on either side. And EventSource reconnects on its own. When I restart the server during development, every open page picks up the stream again a few seconds later without me doing anything.

The Server Side

An Event Bus

The jobs that find new entries should not know anything about HTTP or open pages. So between them sits a small event bus. Jobs publish events. Every open page is a subscriber.

export class EventBus {
  private readonly subscribers = new Set<EventSubscriber>();

  public subscribe(subscriber: EventSubscriber): () => void {
    this.subscribers.add(subscriber);

    return () => {
      this.subscribers.delete(subscriber);
    };
  }

  public publish(event: ServerSentEvent): void {
    const frame = this.format(event);

    this.subscribers.forEach((subscriber) => {
      subscriber.send(frame);
    });
  }

  public closeAll(): void {
    this.subscribers.forEach((subscriber) => {
      subscriber.close();
    });
    this.subscribers.clear();
  }

  // JSON keeps the data on a single line, which a server-sent event's data field needs.
  private format(event: ServerSentEvent): string {
    return `event: ${event.name}\ndata: ${JSON.stringify(event.data)}\n\n`;
  }
}

The wire format is the whole reason for the comment. An event is a few field: value lines followed by an empty line. A line break inside the data would end the field early, so the data has to fit on one line, and JSON.stringify without indentation guarantees that.

The Stream Endpoint

Fastify normally sends a response and finishes it. A stream has to stay open, so the route takes over the raw Node.js response with reply.hijack():

server.get('/events', (request, reply) => {
  reply.hijack();
  reply.raw.writeHead(200, {
    'Content-Type': 'text/event-stream; charset=utf-8',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
  });
  reply.raw.write(': connected\n\n');

  const unsubscribe = eventBus.subscribe({
    send: (frame) => {
      reply.raw.write(frame);
    },
    close: () => {
      reply.raw.end();
    },
  });

  request.raw.on('close', unsubscribe);
});

The : connected line is a comment in the event stream format. The browser ignores it, but it flushes the headers right away, so EventSource reports the connection as open immediately instead of waiting for the first real event.

When the tab closes, the request’s close event removes the subscriber. Without that, the bus would keep writing into dead connections.

Live Updates Must Never Break the Real Work

The job that finds new entries stores them in the database, sends a desktop notification, and publishes an event. Of these three, the event is the least important. If rendering the event fails for some reason, the entries must still be stored.

So the publishing is wrapped:

// Live updates are only a convenience, so a failure here is logged and must never fail the job itself.
private publish(createEvent: () => LiveUpdateEvent): void {
  try {
    this.eventBus.publish(createEvent());
  } catch (error) {
    this.terminal.log(`could not update the open pages: ${describeError(error)}`);
  }
}

Note that it takes a function that creates the event, not the event itself. Building the event can fail too, and this way that failure is caught by the same try.

Do Not Move What the Reader Is Looking At

My first version did the obvious thing: when new entries arrived, it inserted them at the top of the list. It was annoying to use. I would be reading an entry, and it would jump down by three rows because new ones had arrived above it.

The fix was to stop changing the list at all. The event now only says how many entries were added, and the page shows a bar above the list:

<div data-new-entries-bar hidden class="sticky top-0">
  <span data-new-entries-text></span>
  <a href="/entries">Show</a>
</div>
const offerNewEntries = (data) => {
  pendingCount += data.count;
  newEntriesText.textContent = `${pendingCount} ${pendingCount === 1 ? 'entry was' : 'entries were'} added`;
  newEntriesBar.hidden = false;

  if (document.hidden) {
    unseenCount += data.count;
    document.title = `(${unseenCount}) ${baseTitle}`;
  }
};

“Show” is a plain link that reloads the page. The list only changes when I ask for it. It is the same pattern many social media sites use for their feeds, and now I understand why.

The second part is for when the tab is in the background. The count goes into the tab title, so I can see from another tab that something arrived. When I switch back, the visibilitychange event resets it.

Two other details:

Sending Rendered HTML

Some things on the page do change live. Every background job has a small status dot that turns yellow while it runs and green or red when it is done. Updating a dot means knowing which color, which tooltip, and which text belong to which status. That logic already exists on the server, in the template partial that renders the dot on page load.

So instead of duplicating it in JavaScript, the event carries the rendered partial:

{
  name: 'job-updated',
  data: {
    jobId,
    status,
    html: viewRenderer.render('/views/partials/status-dot', { jobId, status, lastRun }),
  },
}

And the client swaps it in:

const replaceStatusDots = (data) => {
  document.querySelectorAll(`[data-status-dot][data-job-id="${CSS.escape(data.jobId)}"]`).forEach((dot) => {
    dot.outerHTML = data.html;
  });
};

The HTML comes from the server’s own template engine, which escapes its values, so it is as safe as the page itself. And there is exactly one place that decides what a status dot looks like.

One Stream for All Tabs

Browsers limit how many connections a browser may keep open to the same host. Over HTTP/1.1, which is what a small local server speaks, the limit is six. Every EventSource holds one of those connections for as long as the tab is open. With six tabs open, the seventh tab cannot load anything at all. Its requests wait in a queue that never moves.

The solution: only one tab opens the stream, and it passes every event on to the others. Two browser APIs make this short.

The Web Locks API decides which tab holds the stream. navigator.locks.request waits until the lock is free, then runs the callback, and holds the lock until the promise returned by the callback settles. A promise that never settles holds it forever, or rather, until the tab closes. Then the browser releases the lock, and the next waiting tab gets it.

BroadcastChannel passes messages between tabs of the same origin.

Together:

const handlers = { 'entries-added': offerNewEntries, 'job-updated': replaceStatusDots };
const tabs = new BroadcastChannel('live-events');

tabs.addEventListener('message', (message) => {
  handlers[message.data.name]?.(message.data.data);
});

// Browsers allow only a few open connections per host, and every tab with its own stream would use one up.
// One tab holds the stream and passes the events on. When it closes, the next tab takes over.
navigator.locks.request('live-events', () => {
  return new Promise(() => {
    const events = new EventSource('/events');

    Object.entries(handlers).forEach((handler) => {
      const [name, handle] = handler;

      events.addEventListener(name, (event) => {
        const data = JSON.parse(event.data);

        handle(data);
        tabs.postMessage({ name, data });
      });
    });
  });
});

The first tab gets the lock and opens the stream. Every other tab waits for the lock and, in the meantime, listens on the channel. When the stream tab receives an event, it handles it itself and broadcasts it. A BroadcastChannel does not deliver a message back to its sender, which is why the stream tab calls the handler directly.

When I close the stream tab, the lock is released, and one of the waiting tabs gets it and opens a new stream. There is no election, no heartbeat, no leader timeout. The browser does all of it.

Shutting Down Cleanly

One last surprise came on shutdown. server.close() in Node.js waits for all open connections to finish. An event stream never finishes on its own. So with a page open, Ctrl+C did nothing visible for a long time.

The fix is to end the streams first:

const stop = async (): Promise<void> => {
  scheduler.stopAll();
  // Open pages keep their event streams open, which would otherwise hold up closing the server.
  eventBus.closeAll();
  await server.close();
  database.close();
};

The open pages notice the closed stream and start reconnecting, which brings them back as soon as the server is up again.

Conclusion

Live updates do not need a framework or WebSockets when the data only flows one way. Server-sent events cover the transport, rendered partials keep the display logic in one place, and a Web Lock plus a BroadcastChannel turn any number of tabs into a single connection.

The bigger lesson was about the reader, not the code. Live data and a list someone is reading do not mix well. Telling the reader that something arrived, and letting them decide when to look, works better than changing the list under them.