@ogygia/postrender
Stores and CDNs
Pages live in a store you pass to postrender.handle(), the memory store by default, or Valkey, Upstash or Workers KV when the app runs on more than one instance. Edge adapters stamp cache headers for Akamai, CloudFront or Cloudflare and purge them on every clear.
postrender.handle() takes the live parts of postrender: a store, where stored pages are kept, and edge, a list of CDNs in front of the app. They go here, not in vite.config.ts, because they hold clients and credentials that only exist when the server runs.
The store answers every hit and miss. The edges matter when you clear a page: postrender clears it from the store and purges it at every edge at the same time. Each edge also adds the headers its CDN needs to a stored page.
import { sequence } from '@sveltejs/kit/hooks';
import * as ogygia from 'ogygia/server';
import {
UPSTASH_REDIS_REST_URL,
UPSTASH_REDIS_REST_TOKEN,
CF_ZONE_ID,
CF_PURGE_TOKEN
} from '$env/static/private';
import {
postrender,
UpstashStore,
CloudflareEdge
} from '@ogygia/postrender';
export const handle = sequence(
postrender.handle({
store: new UpstashStore({
url: UPSTASH_REDIS_REST_URL,
token: UPSTASH_REDIS_REST_TOKEN
}),
edge: [
new CloudflareEdge({
zoneId: CF_ZONE_ID,
apiToken: CF_PURGE_TOKEN,
site: 'https://www.example.com'
})
]
}),
ogygia.handle()
);Memory store
With no store, pages go to a MemoryStore inside the server process. It keeps up to 1000 pages and 64 MiB of HTML (counted as the string’s length), and drops the least recently used page first when either fills. Pass your own limits to the constructor.
The memory store suits one long-running server, such as adapter-node on a single machine. It starts empty on every start, and each instance has its own:
- On several instances, each one renders and stores every page for itself, and a clear reaches only the instance that ran it. The others keep serving their copy until the TTL ends.
- On serverless, each instance lives briefly, so few requests are hits.
Configuring edges without a store warns once (postrender_edges_without_shared_store), because a clear would purge the CDN while the other instances still hold the page and hand it back to the CDN on its next miss.
import { sequence } from '@sveltejs/kit/hooks';
import * as ogygia from 'ogygia/server';
import { postrender, MemoryStore } from '@ogygia/postrender';
export const handle = sequence(
postrender.handle({
store: new MemoryStore(
5000,
256 * 1024 * 1024
)
}),
ogygia.handle()
);Shared stores
A shared store keeps one copy of each page for every instance, survives restarts, and lets a clear reach everyone. Three are built in:
| Store | Takes | Notes |
|---|---|---|
new ValkeyStore(client) | A connected ioredis client, for Valkey or Redis. Not node-redis: see the warning below. | Pages are kept under og:a:<path> with the TTL as their expiry. Each data source’s pages are a set under og:t:<tag>. A prefix clear scans keys with SCAN. The client needs the set commands (sadd, smembers), because every page is filed under its build and its sources. |
new UpstashStore({ url, token }) | The REST URL and token of an Upstash Redis database. | The same keys as ValkeyStore, with one HTTPS call per command and no client library, which suits serverless. A failed call throws postrender_adapter_request_failed. |
new CloudflareKvStore(binding) | A Workers KV namespace binding. | KV is eventually consistent, so a far location can serve the old page for up to about a minute after a clear. KV’s shortest expiry is 60 seconds, so a shorter TTL is raised to 60. Each stored page costs several KV writes (the page, plus one per tag, and every page has at least its build’s tag), and the build record is written again whenever a new isolate starts. KV allows one write per second per key, and the free plan a limited number of writes a day, so a busy site can run out; failed writes log postrender_store_failed (#2299). |
Use ioredis with ValkeyStore, never node-redis
ValkeyStore calls its client the way ioredis takes arguments. node-redis v4 accepts those calls without an error but reads them differently: pages are stored with no expiry, a prefix clear scans your whole database instead of ogygia’s keys, and each batch it deletes can be any key in the database, sessions and other app data included. A source clear also leaves most of its pages stored. Until this is fixed (#2298), pass an ioredis client, or use UpstashStore or a store of your own.
A client without the set commands still stores pages, but can’t file them under their build or sources: clearing by source and the deploy cleanup miss them, and every write logs postrender_store_failed, with postrender_store_client_missing as its cause. A store failure never fails a request; see When a store or edge fails.
On Cloudflare Workers, read the binding from cloudflare:workers:
PAGES is a KV namespace bound in your Wrangler config, and CF_ZONE_ID and CF_PURGE_TOKEN are a variable and a secret there.
import Redis from 'ioredis';
import { REDIS_URL } from '$env/static/private';
export const redis = new Redis(REDIS_URL);import { sequence } from '@sveltejs/kit/hooks';
import * as ogygia from 'ogygia/server';
import { postrender, ValkeyStore } from '@ogygia/postrender';
import { redis } from '$lib/server/redis';
export const handle = sequence(
postrender.handle({
store: new ValkeyStore(redis)
}),
ogygia.handle()
);import { sequence } from '@sveltejs/kit/hooks';
import * as ogygia from 'ogygia/server';
import { env } from 'cloudflare:workers';
import {
postrender,
CloudflareKvStore,
CloudflareEdge
} from '@ogygia/postrender';
export const handle = sequence(
postrender.handle({
store: new CloudflareKvStore(env.PAGES),
edge: [
new CloudflareEdge({
zoneId: env.CF_ZONE_ID,
apiToken: env.CF_PURGE_TOKEN,
site: 'https://www.example.com'
})
]
}),
ogygia.handle()
);CDN purging
An edge adapter does two things. As a page is stored, it adds the headers its CDN caches by. When you clear pages, it calls the CDN’s purge API. Three are built in:
| Edge | What it stamps and purges |
|---|---|
new AkamaiEdge({ host, clientToken, clientSecret, accessToken, site, network?, maxAge? }) | EdgeGrid credentials for Fast Purge, and site, the public origin a purged path is made absolute against. network is 'production' (default) or 'staging'. Each page gets an edge-cache-tag header with its first three path prefixes (p:/fr, p:/fr/shop, p:/fr/shop/shoes). A path is purged by URL; a prefix is purged by its tag, so a prefix deeper than three segments isn’t purged at Akamai and stays until its s-maxage ends. The root has no tag: invalidateWhere({ prefix: '/' }) purges nothing at Akamai, and no prefix clear purges the page / there. |
new CloudFrontEdge({ distributionId, accessKeyId, secretAccessKey }) | A distribution and AWS credentials allowed to create invalidations. It adds no headers, because CloudFront follows the page’s cache-control. A path is invalidated as itself; a prefix as <prefix> and <prefix>/*. For the root prefix that’s / and //*, so only the page / is invalidated. |
new CloudflareEdge({ zoneId, apiToken, site, maxAge? }) | A zone, an API token with the Zone Cache Purge permission, and the public origin. Each page gets the same prefix tags as Akamai’s, under cache-tag. A path is purged by URL. A prefix is purged with Cloudflare’s purge by prefix, so check that your plan includes it. |
A failed purge call throws postrender_adapter_request_failed inside the clear, which logs it and carries on with the other edges.
Two gaps in the built-in edges are open (#2297, items 7 and 8):
- Clearing everything doesn’t reach Akamai or CloudFront. As the table says, a
'/'prefix purges nothing at Akamai and only/at CloudFront. AfterinvalidateWhere({ prefix: '/' }), purge the whole property in the CDN’s own console or API. - Paths are sent decoded. A purge for
/caféor/a bis sent as written, not percent-encoded, so it may not match the URL the CDN cached. At CloudFront, a path with&or<makes the request fail. Purge such pages in the CDN’s console too.
Two options are shared:
maxAge(Akamai and Cloudflare) replaces thes-maxage, in seconds, in the page’scache-control. A page has onecache-control, and every CDN in front reads it, so this sets the lifetime at all of them, not only at this edge. The store’sttldoesn’t change. It defaults to thettl, and isn’t held to a day, so the CDNs can keep a page longer than the store does.0leaves thecache-controlalone. Every Akamai or Cloudflare edge withoutmaxAge: 0writes acache-control(itsmaxAge, or else thettl), and the last such edge in the list wins, even one you gave nomaxAge.baseUrl(every edge) sends the adapter’s API calls to another address, such as an emulator in your tests.
import { sequence } from '@sveltejs/kit/hooks';
import * as ogygia from 'ogygia/server';
import * as secrets from '$env/static/private';
import {
postrender,
ValkeyStore,
AkamaiEdge,
CloudFrontEdge
} from '@ogygia/postrender';
import { redis } from '$lib/server/redis';
export const handle = sequence(
postrender.handle({
store: new ValkeyStore(redis),
edge: [
new AkamaiEdge({
host: secrets.AKAMAI_HOST,
clientToken: secrets.AKAMAI_CLIENT_TOKEN,
clientSecret: secrets.AKAMAI_CLIENT_SECRET,
accessToken: secrets.AKAMAI_ACCESS_TOKEN,
site: 'https://www.example.com',
maxAge: 600
}),
new CloudFrontEdge({
distributionId: secrets.CF_DISTRIBUTION_ID,
accessKeyId: secrets.AWS_ACCESS_KEY_ID,
secretAccessKey: secrets.AWS_SECRET_ACCESS_KEY
})
]
}),
ogygia.handle()
);CDN headers
Postrender tells the CDN per page what it may keep, so you don’t need a blanket rule for HTML:
- A stored page goes out with
cache-control: public, s-maxage=<ttl>, anetagand alast-modified, plus each edge’s headers. Edges are applied in order, so a later edge’scache-controlreplaces an earlier one’s. - A
200HTML page that’s refused, rendered for a request with a cookie, or rendered while it was being cleared goes out withcache-control: private, no-storewhen your app set none. A refused404, JSON or other answer keeps the headers it had. - A stored permanent redirect goes out with no
cache-controland no edge headers (What the response has to be). - A page with a
stitch: 'serve'hole goes out withprivate, no-storeand no edge headers (Personal parts). One with onlystitch: 'edge'holes addssurrogate-control: content="ESI/1.0". - A request postrender doesn’t look up (a query string, a method other than
GET, an opted-out route) gets nocache-controlfrom it at all, so set your CDN not to cache what has none, and setprivate, no-storeyourself on opted-out personal pages (Opt out pages that depend on the visitor).
A CDN that revalidates a stored page with If-None-Match or If-Modified-Since gets a 304 with no body from the store. What a stored page keeps lists every header.
Error handling
A store or edge that fails never fails a request or a clear:
- A store call that throws is logged once (
postrender_store_failed), and again only after a call has worked in between, so an outage doesn’t fill the log. Meanwhile a read is a miss and a write is skipped: every page renders fresh and nothing is kept. A store whose reads work but whose writes fail logs on every write, since each read that works ends the streak. - A write that fails still reads as stored for now: the response says
x-ogygia-postrender: stored, and requests that waited on the render are served it as if it were (#2297, item 10). Check the log, not the header, when you suspect the store. - A clear runs the store and every edge at once. One that fails is logged with what failed (
postrender_fanout_failed), and the others still run. The page may stay at that store or edge until its TTL ends. - A source clear that fails for one tag is logged (
postrender_tag_evict_failed), and the other tags are still cleared and purged. - An edge’s
headers()that throws is skipped: the page is stored without that edge’s headers. - Storing a page that throws, because a
stitch: 'edge'hole’sendpointisn’t a valid URL, sends the page as rendered, withprivate, no-store, and logs it once per page (postrender_capture_failed). That message’s details also name an edge adapter, which can’t cause it (#2297, item 11).