Skip to content

@ogygia/postrender

Invalidation

Clear one page with invalidate(path), a whole section with invalidateWhere({ prefix }), or every page that read a document with invalidate(source, args). A post on a page, a deploy and the TTL clear pages on their own.

On this page

A stored page stays as it was rendered until something clears it. Clearing takes the page out of the store and purges it at every CDN edge you configured, and the next request renders it again and stores the new version.

You clear pages from server code, most often a webhook your CMS calls when an editor publishes. Postrender gives you three ways to name the pages: one path, a path prefix, or a data source and its arguments. A post on a page, a deploy and the TTL clear pages without any call.

import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { postrender } from '@ogygia/postrender';
import type { RequestHandler } from './$types';

export const POST: RequestHandler = async ({ request }) => {
  if (
    request.headers.get('x-webhook-secret') !==
    env.WEBHOOK_SECRET
  )
    error(401, 'Bad secret');
  const { slug } = (await request.json()) as { slug: string };
  await postrender.invalidate(`/blog/${slug}`);
  return new Response(null, { status: 204 });
};

By URL

postrender.invalidate(path) clears the page stored under path. Pass the path exactly as the page is keyed (One copy per path):

  • the pathname only, with no origin and no query string;
  • decoded: '/café', not '/caf%C3%A9' (an encoded slash is decoded too; see One copy per path);
  • with the trailing slash the page has. invalidate('/docs/intro') doesn’t clear /docs/intro/.

It resolves once the store and every edge have answered. A store or an edge that fails doesn’t make it reject: each failure is logged (postrender_fanout_failed), and the page may stay at that store or edge until its TTL ends.

The example above clears one post. To clear a page under both its slash forms, call it twice.

import { postrender } from '@ogygia/postrender';

export async function clearBoth(path: string): Promise<void> {
  const bare = path.replace(/\/+$/, '');
  if (bare === '') return postrender.invalidate('/');
  await Promise.all([
    postrender.invalidate(bare),
    postrender.invalidate(`${bare}/`)
  ]);
}

By prefix

postrender.invalidateWhere({ prefix }) clears every page under a path: a locale, a section, or everything in the store with '/'.

The prefix gets a leading slash and loses any trailing one, so 'blog/', '/blog/' and '/blog' are the same. It clears the page at the prefix and every page below it, and never a sibling that only starts with the same letters: { prefix: '/fr' } clears /fr, /fr/ and /fr/about, not /fresh.

At the CDN, each edge purges the prefix its own way, and some prefixes, '/' among them, don’t reach every CDN today. Purge a CDN has the details.

import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { postrender } from '@ogygia/postrender';
import type { RequestHandler } from './$types';

export const POST: RequestHandler = async ({ request }) => {
  if (
    request.headers.get('x-webhook-secret') !==
    env.WEBHOOK_SECRET
  )
    error(401, 'Bad secret');
  const { locale } = (await request.json()) as {
    locale: string;
  };
  await postrender.invalidateWhere({ prefix: `/${locale}/` });
  return new Response(null, { status: 204 });
};

By data source

Some content shows up on many pages: a promo banner, a pricing table, the site’s footer links. Listing every path that shows it is brittle. Instead, declare the function that loads it as a data source with import.meta.og.source(), and clear by the function and its arguments.

The macro wraps the function and gives it back unchanged to its callers. Each time a render that may be stored calls it, the page notes a receipt for that function and those arguments. postrender.invalidate(getDoc, ['promo']) then clears exactly the pages whose render called getDoc('promo'), at the store and at every edge, however many there are.

Publishing promo clears every page, while publishing pricing clears only /pricing.

Match the arguments

Arguments match by their shape, not by identity: getDoc('promo') matches invalidate(getDoc, ['promo']), and an object argument matches another with the same keys and values in any order. A URL counts as its pathname, and a Kit RequestEvent as its route and pathname.

When the arguments carry more than identifies the content (a request object, a fetch function, an options bag), pass a key that picks out what matters. invalidate() runs the same key over the arguments you pass it.

invalidate(getProduct, [{ id: 'p1', currency: 'EUR' }]) now clears every page that read product p1, in any currency.

Rules for a data source

  • Declare it as export const at the top level of a module: export const name = import.meta.og.source(fn) or (fn, { key }). Anything else fails the build (macro_source_misuse). It follows the macro rules.
  • Clear with the declared function. Passing a function that isn’t a source throws postrender_invalidate_not_source.
  • The store needs evictByTag. Every built-in store has it. A custom store without it logs postrender_store_no_evict_by_tag and clears nothing, while paths and prefixes still work (Write a store adapter).
  • Only renders that may be stored note receipts. A call from a server island’s render or a remote function isn’t counted, and doesn’t need to be: those aren’t stored.
export type Doc = { title: string; html: string };

export const getDoc =  import.meta.og
  .source 
  (async (slug: string): Promise<Doc> => {
    const res = await fetch(
      `https://cms.example.com/docs/${slug}`
    );
    return (await res.json()) as Doc;
  });
import { getDoc } from '$lib/server/cms';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ params }) => ({
  doc: await getDoc(params.slug),
  promo: await getDoc('promo')
});
import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { postrender } from '@ogygia/postrender';
import { getDoc } from '$lib/server/cms';
import type { RequestHandler } from './$types';

export const POST: RequestHandler = async ({ request }) => {
  if (
    request.headers.get('x-webhook-secret') !==
    env.WEBHOOK_SECRET
  )
    error(401, 'Bad secret');
  const { slug } = (await request.json()) as { slug: string };
  await postrender.invalidate(getDoc, [slug]);
  return new Response(null, { status: 204 });
};
type ProductQuery = { id: string; currency: string };

export const getProduct = import.meta.og.source(
  async (q: ProductQuery) => {
    const res = await fetch(
      `https://api.example.com/products/${q.id}?currency=${q.currency}`
    );
    return (await res.json()) as {
      name: string;
      price: number;
    };
  },
  { key: (q) => q.id }
);

Form posts

A request to a page’s URL that isn’t a GET and succeeds (a status under 400) clears that page from the store, as Kit’s form actions rerun a page’s loads. The response waits for it, so the GET that follows a form’s redirect gets the new page. A store that’s down is tried three times within two seconds, and then the response goes out anyway.

Kit gives a remote function call the URL of the page it was made from, so a command or a remote form called from a stored page clears that page too. A command on a busy page (a like button, say) therefore makes the page render again after every call. A command that fails clears it as well, since Kit answers it with a 200 (#2297, item 3).

The rule counts every method but GET, so today a HEAD or an OPTIONS request to a stored page clears it as well. Uptime checkers and link checkers send HEAD, so a page they watch renders more often than it should (#2297, item 2). Check a stored page with a GET, never curl -I.

This clears the store only. A copy at your CDN isn’t purged and stays until its s-maxage ends, so call postrender.invalidate() yourself when a post changes what everyone sees.

import { guestbook } from '$lib/server/guestbook';
import type { Actions, PageServerLoad } from './$types';

export const load: PageServerLoad = async () => ({
  entries: await guestbook.list()
});

export const actions: Actions = {
  default: async ({ request }) => {
    const form = await request.formData();
    await guestbook.add(String(form.get('message') ?? ''));
    return { ok: true }; // the stored /guestbook is cleared before this answer goes out
  }
};

Deploys

Every stored page records the build that stored it, Kit’s version.name, and is served only to that build. For any other build it’s a miss, and the new build renders and stores its own copy. So a new release never serves the old release’s HTML, whose hashed asset files may be gone, even while old instances of a rolling deploy are still storing pages.

On the first request after a server starts with a new build that may use the store (Which requests use the store), postrender also clears the pages the previous build stored, at the store and at every edge, so they stop taking up room and no CDN keeps serving them. It finds the previous build in a record it keeps in the store. The memory store starts empty on every start, so this only matters for a shared store. With a CDN in front, each old page is purged by its own URL, one purge call per page per edge, which adds up on a large site (#2297, item 5).

You don’t write anything for this. To clear everything by hand, call postrender.invalidateWhere({ prefix: '/' }).

TTL

A stored page is cleared after ttl seconds, whatever happens. Set it with postrender({ ttl }). The default is 86400, one day. A value is rounded down to whole seconds and held between 1 and 86400, so no page is stored for more than a day.

The TTL applies twice. A store with expiry drops the page after ttl seconds, and postrender also checks the page’s age when it reads it, so a store that never expires anything still never serves an old page. The CDN gets the same number as s-maxage, unless an edge sets its own maxAge. Workers KV can’t expire anything sooner than 60 seconds, so the KV store raises a shorter TTL to 60.

import { sveltekit } from '@sveltejs/kit/vite';
import { ogygia } from 'ogygia/vite';
import { postrender } from '@ogygia/postrender/vite';
import { dataShake } from '@ogygia/data-shake/vite';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    ogygia(),
    postrender({ ttl: 3600 }),
    dataShake(),
    sveltekit()
  ]
});

Clears during a render

A page can be rendering when you clear it: the render may have read the content from before the publish. Postrender doesn’t store that render. It’s sent to the visitor who asked for it, with private, no-store, and the requests that were waiting for it are let go to render the page again, together, once. That render is stored.

A clear by path or prefix stops the renders of the pages it names. A clear by source stops every render in progress, since a render’s receipts aren’t all known until it ends.

Call sites

Call the functions from server code in the app’s own server: a +server.ts endpoint, a form action, a remote command, a scheduled job inside the server. They reach the store and edges the app’s postrender.handle() was given.

  • On several instances, give them a shared store. With the memory store, a clear reaches only the instance that ran it.
  • From outside the server (a script, another service), call an endpoint of the app. A separate process has no postrender.handle(), so it would clear an empty memory store of its own.
  • With federation, every clear is also sent to the apps that baked this app’s fragments, which clear their own pages (cross-app thaw). A path clears the pages that baked that path, a source the pages that baked fragments which read it, and a prefix everything they baked from this app.
  • In dev, nothing is stored, so a clear has nothing to clear.