live-updates

Refresh your site within seconds of a publish, without a rebuild, over Server-Sent Events

Published pages are prerendered for speed. Without live updates, a new publish only shows on your site after its next build. With them, your site refreshes itself within seconds of a publish β€” no rebuild, no deploy hook.

Sites created with create-median-app 1.1.0 or later already have everything below. Use this page to add it to an existing site.

How it works

The Median page service streams every change to what your published pages serve as Server-Sent Events:

  • a template is published, rolled back or unpublished
  • a document's published content changes (published pages read references and pattern pages from it)

Draft edits never send an event.

Each event's id is your website's published version, a number that goes up with every change. Every published page you read with median.getPage() or median.resolveComponent() carries the version it was read at, as page.publishedVersion.

That version makes it reliable:

  • A stale page catches up as soon as it opens. The page sends the version it was rendered from; if the website has moved on, an event arrives immediately β€” even if nobody had your site open when you published.
  • Reconnects miss nothing. The browser's EventSource resends the last version it saw when it reconnects, and receives an event if anything was published meanwhile.

Requirements

  • cms-renderer 2.0.3 or later
  • The MEDIAN_API_KEY, DATASET_ENDPOINT and MEDIAN_WEBSITE_ID you already use for published pages

Next.js

1. Relay the stream so your API key stays on the server. Create src/app/api/content-changes/route.ts:

import { median } from '@/lib/median';

// A long-lived stream: never prerendered. Vercel closes it at `maxDuration`;
// the browser reconnects with the last version it saw.
export const dynamic = 'force-dynamic';
export const maxDuration = 300;

export function GET(request: Request) {
  return median.relayContentChanges(request);
}

2. Revalidate on change. Create src/app/actions.ts:

'use server';

import { revalidatePath } from 'next/cache';

let lastRevalidated = 0;

export async function revalidatePublished() {
  // Every open tab reports the same change; one purge every 2 seconds is enough.
  if (Date.now() - lastRevalidated < 2000) return;
  lastRevalidated = Date.now();
  revalidatePath('/', 'layout');
}

3. Listen in the browser. Create src/components/ContentChanges.tsx:

'use client';

import { watchContentChanges } from 'cms-renderer';
import { useEffect } from 'react';
import { revalidatePublished } from '@/app/actions';

export function ContentChanges({ since }: { since: number | null }) {
  useEffect(
    () =>
      watchContentChanges('/api/content-changes', {
        since,
        onChange: () => void revalidatePublished(),
      }),
    [since]
  );
  return null;
}

4. Render it on published pages and let new URLs render on demand:

// src/app/[[...slug]]/page.tsx
export const dynamicParams = true;

export default async function Page({ params }) {
  const page = await median.resolveComponent(pathOf((await params).slug));
  if (!page) notFound();
  return (
    <>
      <ParametricPage page={page} registry={registry} />
      <ContentChanges since={page.publishedVersion} />
    </>
  );
}

5. Let Next's cache hold the pages. Create the client with revalidate: 0, so an in-memory copy never outlives a revalidation:

export const median = new Median({ apiKey, datasetEndpoint, websiteId, registry, revalidate: 0 });

TanStack Start

Published pages are static HTML from the build. After a publish, the page reloads its data from the server.

1. Relay the stream from a request middleware in src/start.ts:

const contentChangesMiddleware = createMiddleware().server(async ({ request, next }) => {
  if (new URL(request.url).pathname !== '/api/content-changes') return next();
  const { median } = await import('./lib/median.server');
  return median.relayContentChanges(request);
});

export const startInstance = createStart(() => ({
  requestMiddleware: [contentChangesMiddleware /* , your other middleware */],
}));

2. Listen and reload the route's data:

import { useRouter } from '@tanstack/react-router';
import { watchContentChanges } from 'cms-renderer';
import { useEffect } from 'react';

export function ContentChanges({ since }: { since: number | null }) {
  const router = useRouter();
  useEffect(
    () =>
      watchContentChanges('/api/content-changes', {
        since,
        onChange: () => void router.invalidate(),
      }),
    [since, router]
  );
  return null;
}

Render <ContentChanges since={page.publishedVersion} /> next to ParametricPage, and create the server client with revalidate: 0. Rebuild when you want the new content baked into the static HTML.

Refresh with no tab open

The listener above runs in your visitors' browsers, so it only works while someone has your site open. The first visitor after a publish still gets the cached page, and their tab refreshes it a moment later. To refresh pages as soon as you publish, whether or not anyone is on your site, also listen from your server.

Long-running servers (Node, Nitro, containers)

Start one subscription when the server starts and keep it open for the life of the process. After each change, drop your cached pages with median.invalidate():

// Runs once per server process, e.g. from a Nitro server plugin.
let since: string | null = null;
for (;;) {
  try {
    const response = await median.contentChanges({ since });
    // Read the SSE stream: keep each event's `id` in `since`, and call
    // median.invalidate() after every event except `ready`.
  } catch {}
  await new Promise((resolve) => setTimeout(resolve, 5000)); // then reconnect
}

Because the loop reconnects with the last id it saw, a change published while the stream was down arrives as soon as it reconnects. The Median docs site works this way: a Nitro server plugin holds the stream and rebuilds its pages in memory after every publish.

Next.js on Vercel

On Vercel, Vercel's CDN caches your pages, and only revalidatePath clears that cache. Next.js only allows revalidatePath inside a request, and Vercel suspends functions between requests. So a Vercel site uses three pieces together, plus the browser listener above for open tabs.

1. A revalidate route. Create src/app/api/revalidate/route.ts:

import { revalidatePath } from 'next/cache';
import { revalidateToken } from '@/lib/publish-listener';

export const dynamic = 'force-dynamic';

export async function POST(request: Request) {
  if (request.headers.get('authorization') !== `Bearer ${revalidateToken()}`) {
    return new Response('Unauthorized', { status: 401 });
  }
  revalidatePath('/', 'layout');
  return new Response(null, { status: 204 });
}

2. A server listener that calls it. Create src/lib/publish-listener.ts:

import { createHash } from 'node:crypto';
import { median } from '@/lib/median';

// Derived from the API key, so there is no extra secret to set.
export const revalidateToken = () =>
  createHash('sha256').update(`revalidate:${process.env.MEDIAN_API_KEY}`).digest('hex');

const origin = process.env.SITE_URL ?? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;

const revalidate = () =>
  fetch(`${origin}/api/revalidate`, {
    method: 'POST',
    headers: { authorization: `Bearer ${revalidateToken()}` },
  });

export async function listenForPublishes() {
  // The loop from "Long-running servers" above, with `revalidate()`
  // (debounced by a second) in place of `median.invalidate()`.
}

Start it once per server process in src/instrumentation.ts:

export async function register() {
  if (process.env.NEXT_RUNTIME !== 'nodejs') return;
  if (process.env.NEXT_PHASE === 'phase-production-build') return;
  const { listenForPublishes } = await import('@/lib/publish-listener');
  void listenForPublishes();
}

3. A time limit on cached pages, in src/app/[[...slug]]/page.tsx:

export const revalidate = 60;

The server listener only hears a publish while a Vercel function instance is running, and a quiet site has none. revalidate = 60 makes sure every page refreshes within about a minute of a publish either way; the listener and open tabs make it immediate when they can.

Other frameworks

Any server can relay the stream. Call the page service with your API key and pass on the last version the browser saw:

GET {DATASET_ENDPOINT}/content-changes?websiteId={MEDIAN_WEBSITE_ID}
x-api-key: {MEDIAN_API_KEY}
Accept: text/event-stream
Last-Event-ID: {the version the browser last saw}
  • Forward the browser's Last-Event-ID header (or a ?since= query parameter on its first connection) as Last-Event-ID. Without it, a reconnecting tab misses what was published while it was away.
  • The first event is ready (its id is the current version) or, if the browser is behind, an immediate change event.
  • Each change is a default message event with id: <version> and data {"website_id", "table": "published", "event": "published", "version"}.
  • Keep-alive comments arrive every 15 seconds.

Good to know

  • API usage. Each stream connection counts as one API request; a browser tab reconnects at most every few minutes, depending on your host's function time limit. A server listener holds one connection per server process.
  • Previews are not affected. The draft preview (/cms-preview_/…) always reads the latest draft and needs no stream.
  • Troubleshooting. If your site does not update, open /api/content-changes in a browser: you should see a ready event. A 502 means the relay could not reach the page service β€” check DATASET_ENDPOINT and MEDIAN_API_KEY.