@ogygia/postrender
What gets stored
A page is stored when the request may use the store, its render read nothing personal, and the response can be shared. Each stored page is keyed by its path alone, so one copy serves every visitor, and a request with a cookie stores its own render only where the route allows it.
On this page
Postrender never asks you to mark a page as safe to share. It watches the render instead. When the first request for a page comes in, it notes everything the render reads that could differ between visitors, and once the response is ready it decides: store the page, or send it as it is and render it again next time. That decision is the verdict.
Three things have to hold for a page to be stored. The request has to be one that may use the store. The render has to read nothing personal. And the response has to be one a stranger could be sent. Each is a section below. The rest of the page covers how a stored page is keyed, what happens to requests with cookies, and what the stored copy keeps.
This load reads only its params, so /blog/hello is stored on its first request and served as bytes after that. A slug with no post answers 404, which is never stored.
import { error } from '@sveltejs/kit';
import { posts } from '$lib/server/posts';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params }) => {
const post = await posts.get(params.slug);
if (!post) error(404, 'No such post');
return { post };
};Eligible requests
A request is looked up in the store, and its render may be stored, only when all of these hold:
- It’s a
GET. AHEAD, aPOSTor any other method renders as usual, and today clears the stored page when it succeeds, so check pages with aGET, nevercurl -I(A post on a page clears it). - Its URL has no query string.
/blog?page=2and even/blog?utm_source=mailrender on every request, and are never served the stored/blog. - It’s a page request: not a remote function call (Kit hands those the page’s URL), and not a server island’s fetch. Kit’s own data requests are the exception today, below.
- The route may be stored (Route config).
- The app is running from a build, not
vite devand not prerendering. In dev the verdict still runs and tells you roughly what it would do, though it ignores the request’s cookies (Debugging). - The browser hasn’t switched devtools on. Its pages carry its own events, so they’re never stored or served from the store.
Don’t store a page with csr = true today. Kit rewrites a data request’s URL (/page/__data.json) to the page’s own URL before any hook runs, so postrender looks it up as the page and answers it with the stored HTML. Kit expects data there, so a client-side navigation to that page fails, and a CDN keeps the HTML under the __data.json URL, where clearing the page doesn’t reach it. Opt every csr = true route out with postrender: false until this is fixed (#2299). Pages with csr = false, ogygia’s default, have no data requests and aren’t affected.
Don’t turn on serverDelta with postrender yet. With it, an SPA navigation asks the server to skip the regions the browser already holds. Postrender stores that partial render as the page, and every full page load then gets the skipped regions empty (#2300). Leave serverDelta off in an app that uses postrender.
curl -s -o /dev/null -D - 'http://localhost:4173/blog' | grep -i x-ogygia-postrender
# x-ogygia-postrender: hit
curl -s -o /dev/null -D - 'http://localhost:4173/blog?utm_source=mail' | grep -i x-ogygia-postrender
# (nothing: rendered, not looked up)Per-request reads
During the render, postrender notes any read of something that belongs to the visitor. The first one it sees is the refusal, and the page isn’t stored. These count:
- A cookie read with
cookies.get()that returns a value, orcookies.getAll()when there are any (refusalcookie:<name>,cookies.getAll). - A personal header read with
request.headers.get()orhas()when it’s present (header:<name>). Personal headers arecookie,authorization,proxy-authorization,accept-language,user-agent,referer,forwarded,x-forwarded-for,x-forwarded-host,x-real-ip,x-client-ip,x-api-key,x-user,x-user-id,x-session,x-session-id, and any header whose name speaks of the client’s address, place or identity (containingclient-ip,connecting-ip,country,city,geo,timezone,session,auth,token,user-idand the like). Delivery headers such ashost,accept-encodingandsec-fetch-*don’t count. - All the headers at once while a personal one is present: a loop over them,
Object.fromEntries(request.headers), copying them into a newHeadersorRequest, or any of these on arequest.clone()(headers). - A
localsvalue that isn’t empty, including a function such as a session getter, anincheck or a listing of its keys (locals.<key>). getClientAddress()(client-address), and anyplatformvalue exceptplatform.env,platform.cachesand the platform’swaitUntil(platform.<key>).- A
fetchto your own origin or a subdomain from a request that carries a cookie orauthorization, since Kit forwards them (fetch:credentials). - A feature flag (
flag:<name>), so a page under an A/B test never stores one variant. Theflags()plugin has to be listed. - Writing a cookie with
cookies.set()orcookies.delete()(a cookie write). - Load promises streamed after the document. The refusal is
streamed load (promise in page data)when the promise is in the page’s data or form, andstreamed load promisesotherwise.
In dev, the refusal is printed once per path (postrender_stays_per_request), so a page that’s almost shareable tells you which read keeps it per-request.
A visitor with a currency cookie makes this render per-request (cookie:currency). To store the page and still show their currency, move the prices into a server island.
The canonical copy
A read that comes back empty doesn’t count. cookies.get() returning undefined, a header that isn’t there, locals.user as null, an empty string, false, or an empty object or array: each is the same for every visitor without that cookie or session, so the page can still be stored.
That render is the canonical copy: the page as a first-time, signed-out visitor sees it. In the pricing example, a visitor with no currency cookie renders the USD page, and it’s stored. Once it’s stored, every visitor is served it, those with a currency cookie included, because a hit is served before any load runs. Everything that has to differ per visitor belongs in one of the personal parts instead.
The same rule makes a signed-in page unsafe to leave eligible; see Opt out pages that depend on the visitor.
import { prices } from '$lib/server/prices';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ cookies }) => {
const currency = cookies.get('currency') ?? 'USD';
return { prices: await prices.list(currency) };
};Response requirements
After the render, the response itself is checked. It’s stored when it is:
- a
200with atext/htmlcontent type, a+server.tsthat answers HTML included, or - a permanent redirect,
301or308, with alocation. Only its status and location are stored, and it’s served with no body, nocache-controland no edge headers. Browsers and CDNs keep permanent redirects by their own rules, often for a long time, and since it carries no cache tags, an Akamai or Cloudflare prefix clear doesn’t reach it. Clear it by its path, and purge it in the CDN if you change where it points.
Anything else is sent as it is and never stored: another status (status 404, a 302 or 307 redirect), a set-cookie header (a set-cookie response header), a non-HTML body (a non-html response), or a cache-control your app set that says private or no-store (the app's cache-control (…)). A page that streams Kit’s load promises is refused even when no island reads them.
A refused 200 HTML page with no cache-control of its own is stamped cache-control: private, no-store, so a CDN rule that caches HTML can’t keep it. Other refused responses keep their headers.
Setting private or no-store yourself is another way to keep one page out of the store, and it also tells any cache in front.
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = ({ setHeaders }) => {
setHeaders({ 'cache-control': 'private, no-store' });
return {};
};Stampedes
When fifty requests for a page that isn’t stored yet arrive together, only the first renders it. The others wait for that render. If it’s stored, they’re all served the stored copy and get x-ogygia-postrender: join. If it’s refused, each renders the page for itself, since a refused page is per-request anyway.
The wait never hangs. If the first render throws, or another plugin answers that request itself, the waiting requests are let go and render the page themselves. A clear that lands while the page renders is covered in Invalidation.
Cache keys
A stored page is keyed by its URL’s decoded pathname, exactly, and nothing else. There’s one copy of /blog/hello for every visitor:
- The trailing slash counts.
/docs/introand/docs/intro/are two pages, as they are to Kit and to a CDN. - The pathname is decoded.
/caf%C3%A9is stored as/café, and that’s the string you clear it with. - An encoded slash is decoded too, so
/a%2Fband/a/bshare one key. Kit doesn’t decode%2Fwhen it picks a route, so/docs/a%2Fbrendersdocs/[slug]with the sluga/b, and that render is stored under/docs/a/b, the key of a different page. From then on,/docs/a/bis served the wrong page, for up to a day. Any anonymous request can cause it (#2300). Until it’s fixed, reject%2Fin ahandlethat runs beforepostrender.handle(), as below, or opt out every route with a dynamic segment that could hold one. The CSP section shows it insequence()together with the other stopgap handle. - The host doesn’t count. A server that answers for
a.example.comandb.example.comstores one/aboutfor both, and serves the copy the first host rendered to the second. Readingurl.hostdoesn’t make the render personal. Don’t store pages whose content depends on the host; opt their routes out (#2297, item 1). - No header varies it. Language, device and cookies don’t pick a copy. A page that would differ by
accept-languagereads that header, which keeps it per-request. - The query string never reaches the store, as above.
Each copy also records the build that stored it, Kit’s version.name. A copy is served only to that build, so after a deploy every page renders once more (A deploy clears the old build).
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = ({ url }) => {
// stored once, then served to every host: don't do this on a stored page
return { brand: url.host === 'b.example.com' ? 'B' : 'A' };
};import type { Handle } from '@sveltejs/kit';
export const noEncodedSlash: Handle = ({ event, resolve }) =>
/%2f/i.test(event.url.pathname)
? new Response('Not found', { status: 404 })
: resolve(event);Requests with cookies
A request that carries a cookie or authorization header is treated with care, even when its render reads neither:
- When the page is stored, the request is served the stored copy, like any other.
- When it isn’t, the page renders for that request, the render is not stored, and the response is stamped
private, no-storeif the app set nocache-control.
So a stored page only ever comes from a request with no cookie and no authorization. The reason is that the render isn’t the only code that can read them. A handle that runs before ogygia.handle() can read the session and change the page without the render reading anything, and postrender only watches from inside ogygia’s handle. A server you call can see cookies your code passed along without reading them. Storing only renders made without credentials rules those out.
The cost is on sites where every visitor has a cookie (an analytics or consent cookie set on the first visit): such a page is stored only when a request without cookies comes, a crawler or a CDN’s own fetch. For a route whose pages are the same with or without those headers, set postrender: 'with-credentials' and its renders are stored whatever the request carried. Every read in the list above still refuses a render.
Stored contents
A stored page keeps the HTML exactly as rendered and its content-type. Postrender adds its own headers, and these are what every hit is sent with:
cache-control: public, s-maxage=<ttl>, the TTL frompostrender({ ttl }), or an edge’s ownmaxAge(see Stores and CDNs).etag, a hash of the stored HTML, andlast-modified, when it was stored. A request with a matchingIf-None-Match(a weakW/"…"tag or*included), or, when it sends noIf-None-Match, anIf-Modified-Sinceat or afterlast-modified, gets a304with no body, so a CDN’s revalidation or a browser’s reload costs no body bytes.- each edge’s own headers, such as cache tags (Stores and CDNs).
x-ogygia-postrenderwithstored,hitorjoin(Read the header).
Every other header on the response is dropped, whether your load, a hook or Kit itself set it, and the cache-control you set is replaced by postrender’s. That applies to the first response too, the one whose render was stored. A page that needs its own headers, such as a content-language or a link, has to be opted out for now (#2297, item 4).
A server island inside a stored page is signed for a long time, so keep OGYGIA_SECRET stable (Fetch it in the browser with a server island).
A content security policy on a stored page
This matters most for Kit’s own content-security-policy. With kit.csp configured, a stored page goes out with no CSP header at all, on the response that stored it and on every hit. A nonce makes it worse: one request’s nonce is baked into the HTML everyone is served. You don’t have to have picked nonces for this. Kit’s default mode: 'auto' uses a nonce on every server-rendered page that carries Kit’s inline scripts, which is every csr = true page. This is an open bug (#2297, item 6). Until it’s fixed:
- If
kit.csprestricts scripts (script-src, or adefault-srcthat covers scripts), it does so on every page, so every stored page loses that policy. Setpostrender({ default: false })and opt in only the pages you accept serving with no script policy, whatever themode. A nonce is frozen, and hashes are dropped with the rest of the header. A CSP you set on one page withsetHeaders, andcontent-security-policy-report-only, are dropped the same way. - For the directives that don’t depend on the page (
frame-ancestors,object-src,base-uri, and the like), set the header from ahandlethat runs beforepostrender.handle(). It wraps every response, stored hits and304s included. Set it only when the response has none: that fills the gap on stored pages and leaves Kit’s own policy alone on the pages that aren’t stored. Set it on a copy of the response, as below. Some responses can’t be changed, such as aResponse.redirect()from an endpoint, and setting a header on one throws, which turns the request into a500.
With the %2F guard from One copy per path, both stopgaps go before postrender.handle():
import type { Handle } from '@sveltejs/kit';
const POLICY =
"frame-ancestors 'none'; object-src 'none'; base-uri 'self'";
export const securityHeaders: Handle = async ({
event,
resolve
}) => {
const response = await resolve(event);
if (response.headers.has('content-security-policy'))
return response;
const headers = new Headers(response.headers);
headers.set('content-security-policy', POLICY);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers
});
};import { sequence } from '@sveltejs/kit/hooks';
import * as ogygia from 'ogygia/server';
import { postrender } from '@ogygia/postrender';
import { noEncodedSlash } from '$lib/server/no-encoded-slash';
import { securityHeaders } from '$lib/server/security-headers';
export const handle = sequence(
noEncodedSlash,
securityHeaders ,
postrender.handle(),
ogygia.handle()
);Blind spots
Postrender knows only what the render reads through Kit’s request event. It can’t tell that these differ per visitor:
- The clock and randomness.
new Date()orMath.random()in a load is true for the first render and then stored. Render those in a server island. - A per-request value in the HTML, such as a CSP nonce, which is frozen into the stored copy (above).
- A hook before ogygia’s. A
handleplaced beforeogygia.handle()that reads a cookie and changes the response, or picks a different route, isn’t watched. Alocalsvalue it sets is seen when the render reads it. - The host, as above.
- A module-level value that one request sets and the next one reads, such as a cache keyed by user in a module.