Skip to content

feat(ppr): opt-in partial prerendering and static full-page cache - #606

Open
AshrefRaj wants to merge 6 commits into
mainfrom
feat/ppr-main
Open

AshrefRaj wants to merge 6 commits into
mainfrom
feat/ppr-main

Conversation

@AshrefRaj

@AshrefRaj AshrefRaj commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

What

Two opt-in render modes per route, set on the route component:

  • renderMode = "ppr": partial prerendering. The document (<head>, inlined CSS, preloads) and the route's pprFallback skeleton are prerendered once and replayed from memory. They are written as soon as App.serverSideFunction has run, before route data is fetched. The app is a postponed hole that resumes with this request's serverFetcher data, so existing fetchers work unchanged. It also needs PPR_ENABLE: true in config.json (off by default), which doubles as the kill switch.
  • renderMode = "static": full-page cache. The page is rendered once and replayed byte for byte after App.serverSideFunction.

Routes without renderMode keep the streaming path, unchanged.

This is the main (TypeScript) port of #602, which targets the 0.x line. Docs: docs/content/09-Core Concepts/07-Rendering-Modes.md.

How a PPR response is built

  1. Shell: prerenderToNodeStream with an abort once the static parts are done. It is cached per pathname | getPPRShellKey() in a bounded LRU (PPR_SHELL_CACHE_MAX), with at most PPR_SHELL_BUILDS_MAX builds at once. Concurrent misses share one build, and stale builds don't publish. The shell is rebuilt when the route learns new deferred CSS/JS.
  2. App: resumeToPipeableStream with this request's store, inside PPRRouteBoundary. PPR_RESUME_TIMEOUT_MS bounds it; on timeout the rest renders on the client.
  3. Trailer: this request's __INITIAL_STATE__, router data, split() keys, deferred CSS/JS, and any cookies or redirects set after the headers went out (replayed client-side by guardLateResponseCalls).

Isolation

  • The whole app is in the hole. Per-request markup in a custom Document goes in <PPRDynamic>.
  • A shell (or static page) that contains a request cookie value is not cached.
  • A CSP nonce from res.locals.cspNonce is rendered as a placeholder and replaced per response.
  • split() now registers chunks with the request's own ChunkExtractor (via SsrRequestContext), since global.__CHUNK_EXTRACTOR__ can point at another request once rendering resumes after an await.
  • These take the streaming path: bots, getPPRShellKey returning null, requests with native safe-area headers, and keys whose shell failed to build in the last 60 s.

API

  • Exports: PPRDynamic, PPRHydrationBoundary, usePPRPhase, useIsPPRShell, usePPRRouteData, clearPPRCache.
  • Optional hooks in server/index.js:
    • getPPRShellKey({ req, res, store, matches }): request properties the shell depends on.
    • getPPRPreloadKey({ req, res, store }): keys the learned LCP image preloads.
    • beforePPRFlush({ req, res, store }): last point to set headers before the shell.
  • Learned LCP image preloads are placed at the top of the head only after two responses for the key agree. PPR_LEARN_PRELOADS=false turns this off.

Dependency change

React and react-dom go from 19.0.0 to 19.2.9, because the resume APIs need 19.2. This also covers the create-catalyst-app templates, the docs site and the examples, plus root overrides so there is a single copy.

Behaviour on PPR responses

  • The status line goes out with the shell, so it is 200 even when serverFetcher fails. The app renders its error state, and window.__STATUS_CODE__ has the real code.
  • Meta tags that depend on fetcher data arrive in the body.

Tests

  • New test/server/handler.ppr.test.ts:
    • shell miss then hit; per-user data stays in its own response; the replayed shell is identical bytes with no state script;
    • bots, PPR_ENABLE off and getPPRShellKey → null all take the streaming path;
    • static: rendered once, then replayed.
  • New test/server/ppr.test.ts: helper unit tests (shell cache, nonce placeholder, script serialization, late-call guard, preload learning).
  • Also covered: fetcher errors (window.__STATUS_CODE__), usePPRRouteData → window.cachedData, late cookies, per-response nonces, resume errors and timeouts, the shell-key and preload-key hooks, the cookie-leak guards (PPR and static), shell build saturation; client tests for usePPRRouteData and the PPR components.
  • npm test in packages/catalyst-core: 527 passed; tsc --noEmit and test:types clean.
  • Fixture e2e (scripts/test-catalyst-core.sh, React 19.2.9): build passes and 6 Playwright tests pass with the packed core

Closes #601

Routes opt in per component with renderMode "ppr" or "static".

ppr (needs PPR_ENABLE: true in config.json, off by default): the document and
the route's pprFallback are prerendered once per pathname and getPPRShellKey()
value with prerenderToNodeStream, cached in a bounded LRU and written as soon
as App.serverSideFunction has run. The app is a postponed hole, resumed with
resumeToPipeableStream when this request's serverFetcher data is ready. The
trailer carries this request's state, router data, split() keys, deferred
assets and any cookies or redirects set after the headers went out. A shell
that contains a request cookie value is not cached. Bots, getPPRShellKey
returning null, native safe-area requests and failed shell builds take the
streaming path. Learned LCP image preloads (keyed by getPPRPreloadKey) are
written at the top of the head once two responses agree.

static: the whole page is rendered once and replayed byte for byte, after
App.serverSideFunction.

Also: PPRDynamic, PPRHydrationBoundary, usePPRPhase, useIsPPRShell,
usePPRRouteData and clearPPRCache exports; split() registers chunks with the
request's extractor from SsrRequestContext; React and react-dom 19.0.0 ->
19.2.9 (the resume APIs need 19.2), with root overrides for a single copy;
Rendering Modes docs page.
@deputydev-agent

Copy link
Copy Markdown

DeputyDev has started reviewing your pull request.

// Static: replay a cached page only after App.serverSideFunction, so its redirects,
// auth checks and cookies still apply to every request.
if (isStaticRoute && !isStaticCacheBypassRequested(req)) {
const cached = staticPageCache.get(getStaticCacheKey(req))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PERFORMANCE_OPTIMIZATION: A cold static-cache key has no single-flight protection: concurrent requests can all miss this get, run serverDataFetcher and the full prerenderToNodeStream, then race to publish their buffers. Put static page construction behind a per-key in-flight build, as the PPR shell path already does.
The cache is populated only after the complete render, so multiple requests can duplicate the most expensive work before any entry exists.

Refactor static construction to return a verified `{ buffer, statusCode }` and share one promise per cache key, using `staticPageCache.build` or a dedicated in-flight map before sending the result.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this for a follow-up. serverFetcher runs in _handler before renderMarkUp, so single-flight would have to cover fetch plus render, not just the render. It would also need a fallback: the first request's page may not be cacheable (non-200, or it contains that visitor's cookie values), and then the waiting requests must render their own page instead of reusing it. The cost today is duplicate renders for one URL on a cold key, once per process.

const { pipe } = stream
abort = stream.abort
// On timeout React marks what is still pending for client rendering and ends.
timeout = setTimeout(() => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PERFORMANCE_OPTIMIZATION: The resume timeout and disconnect handling abort only the React stream, not the independent routeData promise. A hanging serverFetcher can therefore continue retaining the request/store after the response ends, while guard.restore() remains deferred until that unbounded promise settles. Propagate cancellation to route-data fetching and restore the response guard synchronously on terminal response paths.
PPR_RESUME_TIMEOUT_MS can finish the response without stopping upstream work or restoring the monkey-patched response methods.

Create an AbortController for route data, pass its signal through the server-fetcher path, abort it on timeout or disconnect, and call `guard.restore()` directly from finish/close cleanup with routeData.finally retained only as an idempotent fallback.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this in this PR. The guard is meant to stay in place until route data settles. A fetcher that is still running may call res.cookie/res.redirect after the response has finished, and without the guard that throws ERR_HTTP_HEADERS_SENT; restore() is idempotent. Cancelling the fetcher itself would need an AbortSignal in the serverFetcher contract, which is a public API change. On the classic path a hanging fetcher already holds the request, and there it also holds back the whole response. Worth a separate issue.

@deputydev-agent

Copy link
Copy Markdown

DeputyDev has completed a review of your pull request for commit 9bae9b8.

Ashref Raj added 3 commits November 12, 2026 13:04
…examples

CI failed on two counts:
- docs: the docs site installs its own React (19.0.0), so the server
  bundle could not import resumeToPipeableStream. The docs app and the
  examples now pin 19.2.9 like the core.
- web line coverage fell below the release baseline. New tests cover
  usePPRRouteData and the PPR components on the client, and the handler's
  PPR paths: fetcher errors, window.cachedData, late cookies, per-response
  nonces, resume errors and timeouts, the shell-key and preload-key hooks,
  the cookie-leak guard, shell build saturation and the static cache
  guards.
# Conflicts:
#	packages/create-catalyst-app/templates/none-js/package.json
#	packages/create-catalyst-app/templates/none-ts/package.json
#	packages/create-catalyst-app/templates/redux-js/package.json
#	packages/create-catalyst-app/templates/redux-ts/package.json
#	packages/create-catalyst-app/templates/rtk-js/package.json
#	packages/create-catalyst-app/templates/rtk-ts/package.json
…ache, more tests

- Decide static-page eligibility after App.serverSideFunction and
  onAppServerSideSuccess, so a nonce those hooks set keeps the request off the
  shared cache. A serverSideFunction error renders fresh instead of through the
  static path, which could cache the error page as a 200.
- Cache PPR shells for nonce and no-nonce requests under separate keys: a shell
  built without a nonce has no placeholder, so a later nonce request lost it.
- Bound the static page cache in bytes as well as entries
  (STATIC_PAGE_CACHE_MAX, STATIC_PAGE_CACHE_MAX_BYTES, default 50 / 64 MiB);
  ShellCache takes maxEntries/maxBytes/sizeOf options and reports bytes.
- SplitComponent declares renderMode and pprFallback.
- Docs: renderMode may sit on a direct component; the cookie guard only checks
  values of 12+ characters and why; static cache limits.
- Tests: shell failure branches, fetcher throws, dev rebuild, flush,
  disconnect, client cache bound, guard pass-through, ShellCache bytes. Fix a
  flaky Document mock in handler.ppr.test.ts (a second vi.doMock of the same
  path raced the beforeEach one; now mocked once, reading the test's Document).
Comment thread packages/catalyst-core/package.json Outdated
"express-static-gzip": "^2.1.7",
"react": "19.0.0",
"react-dom": "19.0.0",
"react": "19.2.9",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (blocking): Pinning react/react-dom to exactly 19.2.9 in dependencies gives existing apps two copies of React. Apps scaffolded from the current templates pin "react": "19.0.0", so npm keeps 19.0.0 at the root and nests 19.2.9 under catalyst-core/node_modules. The Vite-bundled server code resolves the root react-dom, but externalized CJS subpaths such as catalyst-core/hooks require("react") and get the nested copy, so any SSR'd component using those hooks throws "Invalid hook call". The root overrides don't apply to consumers. On a 19.0 app PPR also fails silently: resumeToPipeableStream is undefined, the shell is "nothing was postponed" (handler.tsx:822), and each key retries a full prerender every 60 s (handler.tsx:917).

Suggested fix: move react/react-dom to peerDependencies (^19.2.0, keep them in devDependencies); at module load, if PPR is enabled and typeof resumeToPipeableStream !== "function", log one error and disable PPR; add an upgrade note (changelog + Version-Upgrades) telling apps to bump React to 19.2.x.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 41f843e. react/react-dom are now peerDependencies (^19.0.0; devDependencies keep 19.2.9), so the app's React is the only copy. I used ^19.0.0 rather than ^19.2.0 because PPR is opt-in: a 19.0 app that doesn't use it shouldn't hit ERESOLVE on upgrade. With PPR_ENABLE on and no resumeToPipeableStream, PPR routes take the classic path and one error is logged (read through a namespace import, so an older react-dom doesn't fail at load). Upgrade note added to the changelog and Version Upgrades.

* boundary (see PPRRouteBoundary), so the client tree needs one at the same position or
* hydration mismatches. On a classic response it renders children as they are.
*/
export function PPRHydrationBoundary({ children }: { children?: any }) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (non-blocking): None of the six create-catalyst-app templates wraps its root in PPRHydrationBoundary, and nothing warns when it's missing. The server always puts a Suspense boundary first inside #app (PPRRouteBoundary, handler.tsx:716), so a client tree without the matching boundary will most likely fail hydration: React discards the server DOM, re-renders the page on the client and logs #418. The e2e run in the description doesn't catch this, because examples/catalyst-core-test has no renderMode route. Add the boundary to the template client/index.js files (it is a no-op on classic responses) and a PPR route with a "hydrates without console errors" check to the e2e fixture.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 41f843e. All six templates now wrap the root in <PPRHydrationBoundary>, and on a PPR response without it clientRouter logs an error naming the fix. The e2e fixture has a /ppr route and a "hydrates without console errors" test (miss + hit). With the boundary removed, it fails on #418.


it("replays a cookie set after the shell went out with document.cookie", async () => {
const get = await load()
const page = await get("/ppr", { cookies: USER_A, query: { late: "" } })

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (non-blocking): get("/ppr", { query: { late: "" } }) sets req.query but leaves the query out of the URL. serverFetcher data is stored under /ppr?late= while the router reads /ppr, so the page renders no user. This test, the resume-timeout test and the disconnect test (L404, which asserts not.toContain(user)) therefore pass without the user's data ever being rendered. Put the query in the URL (get("/ppr?late=", ...)). Also worth one test with overlapping requests (Promise.all, several users, some on ?slow=) asserting each response holds only its own user and its own __SSR_RENDERED_COMPONENTS__; today all isolation checks are sequential and no PPR fixture route calls split().

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 41f843e. makeReqRes now parses req.query from the URL like Express, and the tests use /ppr?late= / /ppr?slow=. The late-cookie test now asserts the user renders, and the timeout/disconnect tests assert it doesn't. Added an overlapping-requests test on a new /ppr-split route (4 users, half on ?slow=, all ppr-hit): each response holds only its own user and its own __SSR_RENDERED_COMPONENTS__. It fails if split() falls back to the global extractor.

return !!(deviceDetails.googleBot || deviceDetails.aiBot || deviceDetails.statusCakeBot)
}

const getPathname = (req: any) => new URL(req.originalUrl, "http://localhost").pathname

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (non-blocking): getPathname calls new URL(req.originalUrl, "http://localhost"), which throws ERR_INVALID_URL for paths Express accepts, such as // or //[x. It now runs on every route, including classic ones, via getComponent (L362) and _renderMarkUp (L495, outside its try). The throw isn't marked as a render failure, so the fetcher catch and then the serverSideFunction catch each re-render and throw again, firing onFetcherError, onAppServerSideError and onRequestError before a 500. On main the same URL renders normally, and scanners send these paths often. Make it total, e.g. wrap in try/catch and fall back to req.path; same for getStaticCacheKey (L297-298).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 41f843e. Path parsing no longer throws: the path goes after a fixed origin instead of being resolved against it, so // and //[x parse and //host/x keeps its own key instead of becoming /x, with a req.path fallback. getStaticCacheKey uses the same helper. Tests cover //, //[x and //[x?y=1, with no error hooks firing.

const nonceAttr = nonce ? ` nonce="${nonce}"` : ""
let js = ""
for (const c of cookies) js += `document.cookie=${serializeForScript(c)};`
if (redirectTo) js += `window.location.replace(${serializeForScript(redirectTo)});`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (non-blocking): A redirect made after the shell is sent becomes window.location.replace(url) with no scheme check (stored at L243-248, written here). A Location: javascript:... header is ignored by browsers, but location.replace("javascript:...") executes it. So an app whose fetcher redirects to a request-derived URL (e.g. ?next=) has an open redirect on streaming routes but XSS on PPR routes. Only replay relative URLs and http:/https:; log and drop anything else.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 41f843e. A late redirect is replayed only for relative or http(s) URLs (checked with the WHATWG URL parser, which strips tabs and control characters the way browsers do). javascript:, data: and the rest are logged and dropped. Tests included.

remember(cache.data, cacheKey, value)
return value
})
remember(cache.promises, cacheKey, promise)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (non-blocking): The promise is cached before it settles, and a rejection is never removed. After one failed client fetch, every later render or visit to that path in the session gets the same rejected promise and throws into the error boundary, until clearPPRCache() or a reload. Evict on failure, e.g. .catch((e) => { if (cache.promises.get(cacheKey) === promise) cache.promises.delete(cacheKey); throw e }).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 41f843e, with one change: evicting on rejection loops. React's retry renders after a rejection have no memoized promise, so each one started a new fetch, and an always-failing fetcher never reached the error boundary (the test timed out). Instead, the failed promise is kept for 2 s, which covers the retry renders, and then dropped, so later renders and visits fetch again. Tests cover both the refetch and the no-loop case.

Ashref Raj added 2 commits November 17, 2026 15:49
# Conflicts:
#	packages/create-catalyst-app/templates/none-js/package.json
#	packages/create-catalyst-app/templates/none-ts/package.json
#	packages/create-catalyst-app/templates/redux-js/package.json
#	packages/create-catalyst-app/templates/redux-ts/package.json
#	packages/create-catalyst-app/templates/rtk-js/package.json
#	packages/create-catalyst-app/templates/rtk-ts/package.json
…templates, safe paths and redirects

- react/react-dom move to peerDependencies (^19.0.0; devDependencies keep 19.2.9), so
  an app's own React is the only copy. With PPR_ENABLE on and no
  resumeToPipeableStream (React < 19.2), PPR routes use the classic path and one error
  is logged. resumeToPipeableStream is read through a namespace import so an older
  react-dom does not fail at module load. Changelog + Version Upgrades note.
- Templates wrap the hydrated root in <PPRHydrationBoundary>; on a PPR response
  without it, clientRouter logs an error naming the fix. The e2e fixture gets a /ppr
  route and a "hydrates without console errors" test (fails with #418 when the
  boundary is removed).
- getPathname / getStaticCacheKey never throw (`//`, `//[x`), and `//host/x` keeps its
  own key instead of collapsing to `/x`.
- A redirect made after the shell was sent is replayed only to relative or http(s)
  URLs; anything else (javascript:, data:) is logged and dropped.
- usePPRRouteData drops a failed fetch after 2 s, so later renders and visits fetch
  again (dropping it at once loops on React's retry renders).
- Tests: req.query is parsed from the URL in the PPR handler tests, so ?late / ?slow
  actually render the user's data; new overlapping-requests isolation test on a
  split() route; tests for invalid paths, the React < 19.2 fallback, unsafe redirects,
  failed-fetch eviction and the missing-boundary warning.

@vmlgtm vmlgtm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All six review findings are fixed and verified at 41f843e; CI is green.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Partial prerendering (PPR): stream a cached shell before route data is ready

2 participants