Skip to content
Merged
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
18 changes: 18 additions & 0 deletions docs/guide/pages-routing/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,24 @@ Production deploys exclude resources used only by `.dev` pages and their compani

The first request receives rendered HTML. Later navigations run the loader and update the page without reloading the document. Form submissions run an action, then refresh page props or redirect.

### After a deploy

An open tab keeps the code it loaded. Deploy while it stays open, and its next navigation asks for chunks that no longer exist.

Void recovers that navigation. The tab sends the build it is running with each page request, and an answer from a different build makes it load the requested page as a document instead of rendering it. The destination keeps its query string and fragment, and the current page stays visible until the load starts.

These never reload the tab:

- A prefetch drops the response and lets the next navigation decide.
- A form submission keeps its response, so the action never runs twice. If the action redirects, the destination loads as a document.
- A failed request is not treated as a deploy.

If that document load still returns the old build, for example from a CDN that caches HTML across deploys, the tab shows an error page instead of reloading again. Keep HTML out of shared caches, or purge it on deploy.

Prerendered pages of an [`output: "static"`](../ssg.md) app are served as files and are not covered: a stale tab still reaches its error boundary there.

Recovery is on by default. Set `deployRecovery: false` in your framework plugin's options to keep your own [error boundaries](./errors.md) in charge instead.

To opt a specific route out of server-rendered component HTML, export `ssr = false` from its companion `.server.ts` file:

```ts
Expand Down
4 changes: 4 additions & 0 deletions docs/reference/api/pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ interface VoidVueOptions {
hoverDelay?: number; // default: 75 (ms)
cacheFor?: number | string | [string, string]; // default: '30s'
};
deployRecovery?: boolean; // reload a tab whose build is gone. default: true
}
```

Expand Down Expand Up @@ -147,6 +148,7 @@ interface VoidReactOptions {
hoverDelay?: number; // default: 75 (ms)
cacheFor?: number | string | [string, string]; // default: '30s'
};
deployRecovery?: boolean; // reload a tab whose build is gone. default: true
}
```

Expand Down Expand Up @@ -232,6 +234,7 @@ interface VoidSvelteOptions {
hoverDelay?: number; // default: 75 (ms)
cacheFor?: number | string | [string, string]; // default: '30s'
};
deployRecovery?: boolean; // reload a tab whose build is gone. default: true
}
```

Expand Down Expand Up @@ -286,6 +289,7 @@ interface VoidSolidOptions {
hoverDelay?: number; // default: 75 (ms)
cacheFor?: number | string | [string, string]; // default: '30s'
};
deployRecovery?: boolean; // reload a tab whose build is gone. default: true
}
```

Expand Down
9 changes: 8 additions & 1 deletion packages/edge/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
export type { ProjectZeroTrustRouting } from './access.ts';
export { PAGES_PROTOCOL_VERSION } from './pages-protocol.ts';
export {
buildHeaders,
isStaleBuild,
isStaleBuildReload,
pagesPayloadFitsBuild,
PAGES_BUILD_HEADER,
PAGES_PROTOCOL_VERSION,
} from './pages-protocol.ts';
export { redirectToHttps } from './https.ts';
export {
applyHeaderRules,
Expand Down
55 changes: 55 additions & 0 deletions packages/edge/src/pages-protocol.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,57 @@
/** Current Pages wire version; a missing header identifies legacy clients. */
export const PAGES_PROTOCOL_VERSION = '2';

/**
* The build a request or response belongs to. Unlike the protocol version it
* changes with every deploy, so a tab that outlives a deployment can tell that
* the chunks it still holds are gone.
*/
export const PAGES_BUILD_HEADER = 'X-VoidPages-Build';

/**
* Whether a build id seen on the wire belongs to another deployment. A peer
* that sends no id (an older Void, or a parse of a partial response) is not
* evidence of a new build, so it never counts as a mismatch.
*/
export function isStaleBuild(buildId: string, seen: string | null | undefined): boolean {
return buildId !== '' && typeof seen === 'string' && seen !== buildId;
}

/** Request and response headers that carry a build, empty when none is known. */
export function buildHeaders(buildId: string): Record<string, string> {
return buildId === '' ? {} : { [PAGES_BUILD_HEADER]: buildId };
}

/**
* Whether a cached Pages payload may answer a request. A client that names no
* build cannot tell builds apart, so it keeps the cached payload. A client that
* names one accepts only a payload from that same build, and an entry without an
* id predates ids, so it is not trusted either.
*/
export function pagesPayloadFitsBuild(
cachedBuild: string | null,
requestBuild: string | null,
): boolean {
return requestBuild === null || cachedBuild === requestBuild;
}

/**
* Whether `response` is the app's reload answer to a Pages client from another
* build: an empty plain-text answer without page data, naming a build other than
* the one the client sent. A rendered page, such as an island route's HTML, is
* not one even when it names another build. The reload answer says nothing about
* cached copies of the page, which other tabs still use.
*/
export function isStaleBuildReload(request: Request, response: Response): boolean {
const sent = request.headers.get(PAGES_BUILD_HEADER);
const answered = response.headers.get(PAGES_BUILD_HEADER);
const type = (response.headers.get('Content-Type') ?? '').split(';', 1)[0]?.trim();
return (
request.headers.has('X-VoidPages') &&
!response.headers.has('X-VoidPages') &&
type === 'text/plain' &&
sent !== null &&
answered !== null &&
sent !== answered
Comment thread
Brooooooklyn marked this conversation as resolved.
Resolved
);
}
41 changes: 35 additions & 6 deletions packages/isr/src/runtime.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { matchSegmentPattern, PAGES_PROTOCOL_VERSION } from '@void/edge';
import {
isStaleBuildReload,
matchSegmentPattern,
pagesPayloadFitsBuild,
PAGES_BUILD_HEADER,
PAGES_PROTOCOL_VERSION,
} from '@void/edge';
import {
buildVariantOriginalUrl,
decodeIsrCacheEntry,
Expand Down Expand Up @@ -324,14 +330,22 @@ function sharedHtmlCacheHeaders(response: Response, ttl: number, state: 'HIT' |
return headers;
}

function jsonCacheResponse(pageData: string, ttl: number, state: 'HIT' | 'MISS'): Response {
function jsonCacheResponse(
pageData: string,
ttl: number,
state: 'HIT' | 'MISS',
build: string | null,
): Response {
const response = new Response(pageData, {
headers: {
'content-type': 'application/json',
// Match the live Pages JSON response: the client parses JSON only when
// `X-VoidPages` is present, and otherwise reloads the whole page.
'X-VoidPages': 'true',
'X-VoidPages-Version': PAGES_PROTOCOL_VERSION,
// Kept with the payload: a hit for a client from another build must not
// pass off this render's props as its own.
...(build ? { [PAGES_BUILD_HEADER]: build } : {}),
Vary: 'X-VoidPages, X-VoidPages-Version',
'Cache-Control': `public, s-maxage=${ttl}, max-age=0, must-revalidate`,
'x-isr-cache': state,
Expand All @@ -357,14 +371,15 @@ export async function populateJsonEdgeCache(
return;
}
try {
const build = response.headers.get(PAGES_BUILD_HEADER);
const fromHeader = response.headers.get('x-void-page-data');
const pageData = fromHeader
? normalizePageDataForJsonCache(fromHeader)
: extractPageDataFromHtml(await response.clone().text());
if (!pageData) {
return;
}
await cache.put(cacheKey, jsonCacheResponse(pageData, ttl, state));
await cache.put(cacheKey, jsonCacheResponse(pageData, ttl, state, build));
} catch {
// Fail open.
}
Expand Down Expand Up @@ -580,12 +595,26 @@ async function handleIsrInternal(
return null; // fail open → caller renders live
}
if (jsonCached && hasCurrentSharedCachePolicy(jsonCached)) {
return clientRevalidateResponse(jsonCached);
}
if (jsonCached) {
// A cached payload from another build would hand this client page props it
// has no components for. Let the app answer below, which reloads a stale
// tab, and keep the entry: it is still right for clients of its own build.
if (
pagesPayloadFitsBuild(
jsonCached.headers.get(PAGES_BUILD_HEADER),
request.headers.get(PAGES_BUILD_HEADER),
)
) {
return clientRevalidateResponse(jsonCached);
}
} else if (jsonCached) {
await safeCacheDelete(cache, jsonKey);
}
const response = await render(request);
// The app answered a stale client with its reload response. That says nothing
// about this path's cached HTML, which other tabs can still use.
if (isStaleBuildReload(request, response)) {
return response;
}
const ttl = resolveRevalidateTtl(response, isrTtl);
if (isUncacheableRender(response, ttl, false)) {
ctx.waitUntil(
Expand Down
1 change: 1 addition & 0 deletions packages/react/src/plugin-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export function pagesPlugin(pagesDir: string, options?: PagesPluginOptions): Plu
return createPagesPlugin(pagesDir, {
name: 'void-react:pages',
root,
deployRecovery: options?.deployRecovery,
generateRenderer(scan, isDev) {
return generateRendererModule(scan, pagesDir, isDev);
},
Expand Down
8 changes: 3 additions & 5 deletions packages/react/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,16 @@ export type VoidReactOptions = Readonly<{
react?: Parameters<typeof react>[0];
viewTransitions?: boolean;
prefetch?: PrefetchConfig;
deployRecovery?: boolean;
}>;

export function voidReact(options?: VoidReactOptions): Array<Plugin> {
const root = process.cwd();
const pagesDir = resolvePagesDir(root);
return [
...react(options?.react),
pagesPlugin(pagesDir, {
root,
viewTransitions: options?.viewTransitions,
prefetch: options?.prefetch,
}),
// Spread so adapter options the pages plugin owns reach it without per-option glue.
pagesPlugin(pagesDir, { ...options, root }),
...islandsPlugin(pagesDir, { root }),
];
}
1 change: 1 addition & 0 deletions packages/solid/src/plugin-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export function pagesPlugin(pagesDir: string, options?: PagesPluginOptions): Plu
return createPagesPlugin(pagesDir, {
name: 'void-solid:pages',
root: options?.root,
deployRecovery: options?.deployRecovery,
generateRenderer(scan) {
return generateRendererModule(scan, pagesDir);
},
Expand Down
8 changes: 3 additions & 5 deletions packages/solid/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type VoidSolidOptions = Readonly<{
solid?: Parameters<typeof solid>[0];
viewTransitions?: boolean;
prefetch?: PrefetchConfig;
deployRecovery?: boolean;
}>;

// The runtime entry exports raw `.tsx` source. Without these hints, Vite's SSR
Expand Down Expand Up @@ -47,11 +48,8 @@ export function voidSolid(options?: VoidSolidOptions): Array<Plugin> {
return [
configPlugin(),
solid({ ssr: true, ...options?.solid }),
pagesPlugin(pagesDir, {
root,
viewTransitions: options?.viewTransitions,
prefetch: options?.prefetch,
}),
// Spread so adapter options the pages plugin owns reach it without per-option glue.
pagesPlugin(pagesDir, { ...options, root }),
...islandsPlugin(pagesDir, { root }),
];
}
1 change: 1 addition & 0 deletions packages/svelte/src/plugin-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export function pagesPlugin(pagesDir: string, options?: PagesPluginOptions): Plu
return createPagesPlugin(pagesDir, {
name: 'void-svelte:pages',
root: options?.root,
deployRecovery: options?.deployRecovery,
generateRenderer(scan) {
return generateRendererModule(scan, pagesDir);
},
Expand Down
8 changes: 3 additions & 5 deletions packages/svelte/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,16 @@ export type VoidSvelteOptions = Readonly<{
svelte?: Parameters<typeof svelte>[0];
viewTransitions?: boolean;
prefetch?: PrefetchConfig;
deployRecovery?: boolean;
}>;

export function voidSvelte(options?: VoidSvelteOptions): Array<Plugin> {
const root = process.cwd();
const pagesDir = resolvePagesDir(root);
return [
...(svelte(options?.svelte) as ReadonlyArray<Plugin>),
pagesPlugin(pagesDir, {
root,
viewTransitions: options?.viewTransitions,
prefetch: options?.prefetch,
}),
// Spread so adapter options the pages plugin owns reach it without per-option glue.
pagesPlugin(pagesDir, { ...options, root }),
...islandsPlugin(pagesDir, { root }),
];
}
7 changes: 7 additions & 0 deletions packages/void/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Constants the build folds into both the client and server bundles, such as
* the Pages build id. Vite replaces each key at build time.
*/
interface ImportMeta {
readonly env: Record<string, unknown>;
}
2 changes: 1 addition & 1 deletion packages/void/src/installed-packages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function readManifest(dir: string): PackageManifest | undefined {
type PnpApi = { resolveToUnqualified(request: string, issuer: string): string | null };

/** The directory Node loads `name` from for code in `fromDir`. Ignores `exports`. */
function findInstalledPackage(name: string, fromDir: string): string | undefined {
export function findInstalledPackage(name: string, fromDir: string): string | undefined {
// A Yarn Plug'n'Play install has no node_modules. Under `yarn`, its runtime adds
// `findPnpApi` to `node:module` and serves the packages' files from its archives.
const pnp = (module as { findPnpApi?: (path: string) => PnpApi | null }).findPnpApi?.(fromDir);
Expand Down
3 changes: 2 additions & 1 deletion packages/void/src/pages/boundary-client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { isVoidActionError } from './action-result.ts';
import type { BoundaryManifest } from './boundary-plans.ts';
import type { PageError } from './types.ts';
import { isSameOrigin } from './url.ts';

export type ClientPageBoundary<Component = unknown> = {
id: string;
Expand Down Expand Up @@ -49,7 +50,7 @@ export function clientPageError(error: unknown, dev = false): PageError {
/** Terminal recovery cannot depend on the failed adapter, imports, or component tree. */
export function showTerminalPageError(url: string = window.location.href): void {
const target = new URL(url, window.location.href);
if (target.origin !== window.location.origin) {
if (!isSameOrigin(target, window.location.origin)) {
throw new Error('Invalid error page destination');
}
try {
Expand Down
Loading