Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions docs/content/09-Core Concepts/07-Rendering-Modes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
---
title: Rendering Modes
slug: rendering-modes
id: rendering-modes
---

# Rendering Modes

Every route in Catalyst renders in one of three modes. They trade off how fresh the content is against how cheap it is to serve — pick per route based on whether the content is personalized, semi-dynamic, or truly the same for everyone. PPR and static are explicit per-route opt-ins via `Component.renderMode`; an unset `renderMode` is the streaming default. PPR also needs `PPR_ENABLE: true` in `config.json` (default off), which doubles as its kill switch.

| Mode | What's cached | What's fresh per request | Applies to bots | Data fetching API |
| --------- | ------------------- | ----------------------------------- | ---------------- | ------------------- |
| Streaming | Nothing | Everything (data + render) | Yes (always) | `serverFetcher` / `clientFetcher` |
| PPR | Document + route skeleton (`pprFallback`) | The whole app, rendered with this request's data | No (bots get streaming) | `serverFetcher` / `clientFetcher`, or `usePPRRouteData()` |
| Static | The entire page | Nothing, until cache is refreshed | Yes | `serverFetcher` / `clientFetcher` |

## Streaming (default)

The classic path: `serverFetcher` runs on every request, the fully-resolved tree is rendered with `renderToPipeableStream`, and the response streams to the client as it renders. This is what a route gets by default — no `renderMode` to set — and what bot/crawler requests always get regardless of any other mode.

```js
import { useCurrentRouteData } from "catalyst-core"

function LiveOrders() {
const { data } = useCurrentRouteData()
return <p>{data.orderCount} orders right now, fetched at {data.fetchedAt}</p>
}

// Runs on every single request — no shell, no cache, the whole page waits
// on this before anything renders.
LiveOrders.serverFetcher = async () => {
return fetch("/api/live-order-stats").then((res) => res.json())
}

export default LiveOrders
```

Unlike PPR, there's no static/dynamic split here — the entire page is gated on `serverFetcher` resolving, every time. That's the tradeoff: simplest mental model (one fetch, one render, nothing cached), at the cost of paying full data-fetch + render latency on every request, for every visitor.

## Partial Prerendering (PPR)

Opt a route in by setting `renderMode` (and optionally a static skeleton) on its component, and turn PPR on with `PPR_ENABLE: true` in `config.json`:

```js
Home.renderMode = "ppr"
Home.pprFallback = <HomeSkeleton /> // what the cached shell shows until the app streams in
```

A PPR response is written in three parts:

1. **Shell**, prerendered once per `pathname | getPPRShellKey()` with `prerenderToNodeStream` and replayed from an in-memory LRU: the document (`<head>`, inlined CSS, preloads) and `pprFallback`. It is written as soon as `App.serverSideFunction` has run, before route data is fetched.
2. **App**, the postponed hole: resumed with `resumeToPipeableStream` when this request's `serverFetcher` data is ready, so existing fetchers work unchanged.
3. **Trailer**: this request's `__INITIAL_STATE__`, router data, rendered `split()` keys, deferred CSS/JS, and any cookies/redirects set after the headers went out (replayed client-side; a late redirect is replayed only to a relative or `http(s)` URL, and any other is logged and dropped).

The whole app is inside the hole, so the shell never contains request data. Per-request markup in the app's custom Document (CSRF inputs, per-user scripts) must be wrapped in `<PPRDynamic>`. As a safety net, a shell that contains one of the request's cookie values (or a `|`, `:` or `.` separated part of one) of 12 or more characters is not cached. Shorter values are not checked, because short strings such as `1`, `true` or `en` also occur in ordinary markup and would stop every page from caching; keeping per-request values out of the shell is the app's job. On the client, wrap the hydrated root in `<PPRHydrationBoundary>` so it has a Suspense boundary at the same position as the server (apps created from the current templates already do). Without it hydration fails and the page re-renders on the client; on a PPR response the browser console then shows an error naming the fix.

```jsx
// server/document.js (custom Document): per-request markup stays out of the shared shell
import { PPRDynamic } from "catalyst-core"

<Body {...props}>
<PPRDynamic>
<input type="hidden" id="_csrf" value={csrfToken} />
</PPRDynamic>
</Body>

// client/index.js
import { PPRHydrationBoundary } from "catalyst-core"

hydrateRoot(container, <PPRHydrationBoundary>{Application}</PPRHydrationBoundary>)
```

On a streaming (non-PPR) response both render their children as they are.

Optional app hooks (`server/index.js`):

| Hook | Purpose |
| --- | --- |
| `getPPRShellKey({ req, res, store, matches })` | Added to the shell cache key for every request property the shell markup depends on (language, platform). Return `null`/`false` to serve the request on the streaming path. |
| `getPPRPreloadKey({ req, res, store })` | Request properties that change image URLs but not the shell (e.g. device pixel ratio). Keys learned LCP image preloads. |
| `beforePPRFlush({ req, res, store })` | Last point to set headers/cookies before the shell is written (e.g. create a CSRF token). Must be synchronous: its return value is not awaited. |

Config (`config.json`): `PPR_ENABLE` (default `false`), `PPR_SHELL_CACHE_MAX` (50), `PPR_SHELL_BUILDS_MAX` (8 shell prerenders at a time; a miss beyond that takes the streaming path), `PPR_RESUME_TIMEOUT_MS` (15000; on timeout the rest renders on the client), `PPR_PRERENDER_SETTLE_MS` (50), `PPR_PROGRESSIVE_CHUNK_SIZE`, `PPR_LEARN_PRELOADS` (default on), `PPR_REVEAL_THROTTLE` (default off: resumed content is revealed without React 19.2's 300 ms batching).

Bots, requests with native safe-area headers (`X-Safe-Area-*`), `getPPRShellKey` returning `null`, a shell that could not be built (retried after 60 s) and `PPR_ENABLE=false` all take the streaming path. Requires React 19.2 (`resume` APIs): on an older React, PPR routes take the streaming path and the server logs one error.

**Behaviour changes 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; `window.__STATUS_CODE__` has the real code); meta tags that depend on fetcher data arrive in the body.

### `usePPRRouteData()`

Components can also read data with `usePPRRouteData(fetcher)` (React `use()`). It suspends without calling the fetcher while the shell is prerendered, caches per request on the server (never across users), and seeds the client from `window.cachedData` so hydration does not refetch. It works on the streaming path too.

**Caveat:** the cache is keyed by pathname, not per call site. If a route calls it more than once with different fetchers, the second call reuses the first call's result. Fetch everything the route needs in a single call.

## Static (full-page cache)

For content that's genuinely identical for every visitor — marketing pages, pricing, docs — opt a route into full-page caching by setting `renderMode` on its component:

```js
StaticDemo.serverFetcher = async () => {
return { generatedAt: new Date().toISOString() }
}

StaticDemo.renderMode = "static"
```

The entire page — not just a shell — is rendered once (via `prerenderToNodeStream` with no abort/postpone, so it waits for the whole tree, including `serverFetcher` data, to fully resolve) and cached in full, keyed by pathname plus the sorted query string. Every later request, bots included, runs `App.serverSideFunction` (so its redirects, auth checks and cookies still apply) and then replays those bytes with no data fetch and no render.

Requests with a CSP nonce in `res.locals.cspNonce` or native safe-area headers are rendered fresh instead. The cached page includes the store state of the request that rendered it, so use static mode only for routes whose store holds nothing per-user. As a safety net, a page that contains one of the request's cookie values of 12 or more characters is not cached (the same check as for PPR shells; shorter values are not detected).

`renderMode` is read from the matched route's component. On a directly imported component, set it on the component as above. When the route is wrapped with `split()`, set it on the wrapper too: the server checks it synchronously and can't await the lazy import.

```js
import { split } from "catalyst-core"

const StaticDemo = split(() => import("@containers/StaticDemo/StaticDemo"))
StaticDemo.renderMode = "static"
Comment thread
AshrefRaj marked this conversation as resolved.
Resolved
```

**Refreshing the cache during development:** append `?__refresh_static_cache` to the URL to force one request to bypass the cache and re-render (which also repopulates that route's cache entry with the new output). This only works when `NODE_ENV !== "production"` — in production the query param is ignored and the cached page is always served, since a client-controlled way to force a full re-render would defeat the point of the cache.

The cache is in-process and per-server, bounded by `STATIC_PAGE_CACHE_MAX` pages (default 50) and `STATIC_PAGE_CACHE_MAX_BYTES` of HTML (default 64 MiB; least recently used pages are evicted first, a page larger than the whole budget is not cached, and a negative value means no byte budget). It's cleared on restart/redeploy, and (like the PPR shell cache) isn't currently exposed as a public API for a consuming app to clear programmatically at runtime.

## x-rendering-mode reference

PPR and static responses carry an `x-rendering-mode` header useful for debugging which path served a given request. Streaming responses carry **no such header at all**.

| Value | Meaning |
| -------------------------- | ------------------------------------------------------------- |
| *(header absent)* | Streaming: classic path, rendered fresh, nothing cached |
| `ppr-miss` | PPR: shell built for this request (and cached), app resumed |
| `ppr-hit` | PPR: shell served from cache, app resumed with this request's data |
| `static-cache-miss` | Static: no cache entry (or dev bypass) — rendered fresh |
| `static-cache-hit` | Static: entire response served from cache |
20 changes: 20 additions & 0 deletions docs/content/12-Migration/02-Version-Upgrades.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,26 @@ id: 0.0.1-beta.4

# Catalyst Version Upgrades

## Upgrading To The Release With Partial Prerendering

`react` and `react-dom` are now peer dependencies of `catalyst-core` (`^19.0.0`), so the app's own React is the copy everything uses. Keep both in the app's `dependencies`. Apps that stay on React 19.0 or 19.1 need no other change.

To use partial prerendering (`renderMode = "ppr"`), move to React 19.2, which has the APIs PPR resumes with:

```bash
npm install react@19.2.9 react-dom@19.2.9
```

Then wrap the hydrated root in `client/index.js` in `<PPRHydrationBoundary>`. It renders its children as they are on a non-PPR response:

```jsx title="client/index.js"
import { hydrationReady, PPRHydrationBoundary } from "catalyst-core"

hydrateRoot(container, <PPRHydrationBoundary>{Application}</PPRHydrationBoundary>)
```

With `PPR_ENABLE` on and React older than 19.2, PPR routes render on the streaming path and the server logs one error that says so.

## Upgrading From 1.2.0 To 1.2.1

`1.2.1` adds `openInBrowser(url)` to `useIntent()` and an `X-App-Info` request header to the native apps. Web-only apps have nothing to change.
Expand Down
53 changes: 40 additions & 13 deletions docs/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
"@mdx-js/react": "^3.1.1",
"catalyst-core": "1.0.3-canary.1",
"prism-react-renderer": "^2.4.1",
"react": "19.0.0",
"react-dom": "19.0.0"
"react": "19.2.9",
"react-dom": "19.2.9"
},
"devDependencies": {
"@mdx-js/mdx": "^3.1.1",
Expand Down
10 changes: 6 additions & 4 deletions examples/catalyst-core-test/client/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from "react"
import "./styles"
import { hydrateRoot } from "react-dom/client"
import { hydrationReady } from "catalyst-core"
import { hydrationReady, PPRHydrationBoundary } from "catalyst-core"
import { RouterProvider } from "react-router/dom"
import clientRouter from "catalyst-core/router/ClientRouter"

Expand All @@ -12,9 +12,11 @@ window.addEventListener("load", () => {
const router = clientRouter({ routerInitialState: routerInitialData })

const Application = (
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
<PPRHydrationBoundary>
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
</PPRHydrationBoundary>
)

const container = document.getElementById("app")
Expand Down
1 change: 1 addition & 0 deletions examples/catalyst-core-test/config/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@
"PUBLIC_STATIC_ASSET_URL": "http://localhost:3005",
"API_URL": "random_api_url",
"CUSTOM_VAR": "custom",
"PPR_ENABLE": true,
"CLIENT_ENV_VARIABLES": ["API_URL", "CUSTOM_VAR"]
}
4 changes: 2 additions & 2 deletions examples/catalyst-core-test/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
},
"dependencies": {
"catalyst-core": "0.3.0-beta.2",
"react": "19.0.0",
"react-dom": "19.0.0",
"react": "19.2.9",
"react-dom": "19.2.9",
"react-router": "^7.18.2"
},
"devDependencies": {
Expand Down
27 changes: 27 additions & 0 deletions examples/catalyst-core-test/src/js/pages/PPRPage/PPRPage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import React, { useState } from "react"
import { useCurrentRouteData } from "catalyst-core"

// Partial prerendering route: the cached shell holds the skeleton (pprFallback in routes),
// and this page streams in per request with its serverFetcher data.
const PPRPage = () => {
const { data } = useCurrentRouteData()
const [clicks, setClicks] = useState(0)

return (
<div className="container">
<h1>Partial prerendering</h1>
<p data-testid="ppr-data">{data?.message}</p>
<button type="button" data-testid="ppr-counter" onClick={() => setClicks((n) => n + 1)}>
clicked {clicks}
</button>
</div>
)
}

PPRPage.serverFetcher = async () => ({ message: "ppr data" })

PPRPage.clientFetcher = async () => ({ message: "ppr data" })

PPRPage.setMetaData = () => [<title key="title">PPR</title>]

export default PPRPage
12 changes: 12 additions & 0 deletions examples/catalyst-core-test/src/js/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ const About = split(() => import("../pages/About/About"), {
fallback: <div>Loading about page...</div>,
})

// renderMode and pprFallback go on the split() wrapper: the server reads them before the
// page module has loaded.
const PPRPage = split(() => import("../pages/PPRPage/PPRPage"), {
ssr: true,
})
PPRPage.renderMode = "ppr"
PPRPage.pprFallback = <div data-testid="ppr-skeleton">Loading PPR page...</div>

const routes = [
{
path: "/",
Expand All @@ -32,6 +40,10 @@ const routes = [
path: "about",
component: About,
},
{
path: "ppr",
component: PPRPage,
},
],
},
]
Expand Down
Loading
Loading