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
18 changes: 17 additions & 1 deletion docs/guide/pages-routing/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,23 @@ Void renders the error inside the layouts at or above the `_error` file, includi

Put an error component in a subdirectory to customize that section. Void uses the closest one and keeps its surrounding layouts. If a layout fails, an error component outside that layout handles it. If an error component fails, Void tries an outer one, then its built-in error page.

Boundary components don't have `.server` companions, actions, or their own `layout` export. They aren't routes: `/error` and `/not-found` remain available for ordinary pages. `.dev` and `.prod` variants work like other Pages components.
Boundary components don't have loaders, actions, or their own `layout` export. A `.server` companion is allowed only for [`head()`](#page-titles). They aren't routes: `/error` and `/not-found` remain available for ordinary pages. `.dev` and `.prod` variants work like other Pages components.

## Page titles

Error pages use the default titles `Not Found` and `Internal Server Error`, with your [`titleTemplate`](./head.md#page-title-templates) applied. To set your own, add an optional `.server.ts` file next to `_not-found` or `_error` and export a [`head()`](./head.md) from it. It receives the Hono context and the same `error` the component renders:

```ts
// pages/_error.server.ts (or pages/_not-found.server.ts)
import { defineHead } from 'void/handler';
import type { ErrorPageProps } from 'void/pages';

export const head = defineHead<ErrorPageProps>((c, { error }) => ({
title: error.status === 404 ? 'Page not found' : 'Something went wrong',
}));
```

`head()` can return anything a page's head can, and it merges with your config and middleware the same way, so `titleTemplate` still applies. A boundary whose `head()` sets no `title` keeps the default one. The file can only export `head()`; a loader or action is an error. If `head()` throws, Void logs the error and renders the page with the default title.

## Recovery

Expand Down
18 changes: 15 additions & 3 deletions packages/void/src/pages/boundary-plans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ export type BoundaryManifest = {
root?: string;
rootErrors?: Array<string>;
};
/** What the client manifest carries; the server companion stays out of it. */
const planFields = ({ kind, directory, componentId, filePath }: PageBoundaryDefinition) => ({
kind,
directory,
componentId,
filePath,
});
const encloses = (outer: string, inner: string) =>
!outer || outer === inner || inner.startsWith(outer + '/');

Expand All @@ -45,7 +52,7 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest {
.filter((l) => encloses(l.directory, boundary.directory))
.map((l) => layoutKey(l.id));
const id = `_void:boundary:${JSON.stringify([page.componentId, boundary.componentId, retained])}`;
plans[id] = { id, ...boundary, source: page.componentId, layouts: retained };
plans[id] = { id, ...planFields(boundary), source: page.componentId, layouts: retained };
return id;
};
const errors = candidates.filter((b) => b.kind === 'error');
Expand All @@ -71,7 +78,7 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest {
const id = `_void:boundary:root-not-found:${JSON.stringify(scan.layouts.filter((l) => !l.directory).map((l) => l.filePath))}`;
plans[id] = {
id,
...root,
...planFields(root),
source: id,
layouts: scan.layouts
.filter((l) => !l.directory)
Expand All @@ -81,7 +88,12 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest {
const rootErrors: Array<string> = [];
if (error) {
const errorId = `_void:boundary:root-error:${id}`;
plans[errorId] = { ...error, id: errorId, source: id, layouts: [...plans[id].layouts] };
plans[errorId] = {
...planFields(error),
id: errorId,
source: id,
layouts: [...plans[id].layouts],
};
rootErrors.push(errorId);
}
pages[id] = {
Expand Down
36 changes: 33 additions & 3 deletions packages/void/src/pages/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ type PageHandler = ((c: CloudContext) => unknown | Promise<unknown>) | undefined
type PageHeadHandler =
| ((c: CloudContext, props: Record<string, unknown>) => HeadConfig | undefined)
| undefined;
type BoundaryHeadHandler = (
c: CloudContext,
props: { error: { status: number; message: string } },
) => HeadConfig | undefined;
type PageRequestContext = Context | CloudContext;
type PageRenderOptions = {
renderMode?: PageRenderMode;
Expand Down Expand Up @@ -466,6 +470,26 @@ export async function recoverPageHttpException(
return renderPageFailure(context, error, undefined, renderFn, getAssetTags, configHead, options);
}

/**
* The head() a boundary's `.server` companion exports. An error page must still render when
* that file fails, so a failure is logged and the built-in title applies.
*/
async function declaredHead(
load: (() => Promise<{ head?: BoundaryHeadHandler }>) | undefined,
c: CloudContext,
props: Parameters<BoundaryHeadHandler>[1],
): Promise<HeadConfig | undefined> {
if (!load) {
return undefined;
}
try {
return (await load()).head?.(c, props);
} catch (failure) {
console.error(failure);
return undefined;
}
}

/** Recover one completed GET operation without replaying its middleware or loader. */
async function renderPageFailure(
c: CloudContext,
Expand Down Expand Up @@ -529,18 +553,24 @@ async function renderPageFailure(
continue;
}
attempted.add(component);
const props = { error: { status, message } };
const boundaryHead = await declaredHead(options?.boundaries?.loadHeads?.[component], c, props);
const resolved = boundaryHead
? resolveRequestHead(c, configHead, middlewareHead, boundaryHead)
: head;
const page: PageObject = {
component,
props: { error: { status, message } },
props,
shared,
params: requestParams(c),
url: requestPathWithSearch(c),
errors: null,
head: {
...head,
...resolved,
title:
head?.title ??
resolved?.title ??
resolveHead(configHead, middlewareHead, {
...boundaryHead,
title:
status === 404
? 'Not Found'
Expand Down
19 changes: 15 additions & 4 deletions packages/void/src/pages/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,9 +363,11 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis
continue;
}
const base = file.slice(0, -extname(file).length);
const serverPath = ROUTE_EXTENSIONS.map((ext) => `${base}.server.${ext}`).find((candidate) =>
existsSync(join(pagesDir, candidate)),
);
if (
boundary[3] ||
ROUTE_EXTENSIONS.some((ext) => existsSync(join(pagesDir, `${base}.server.${ext}`))) ||
deriveFromSource(join(pagesDir, file), 'page-boundary-layout', (source) =>
scriptBlocks(source, file).some((script) =>
readStaticExports(script.filename, script.source, new Set(['layout'])).initializers.has(
Expand All @@ -374,9 +376,7 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis
),
)
) {
throw new Error(
`pages: Boundary '${file}' cannot be an island, select a layout, or have a .server companion.`,
);
throw new Error(`pages: Boundary '${file}' cannot be an island or select a layout.`);
}
const directory = segments.slice(0, -1).join('/');
for (const prior of boundaries) {
Expand All @@ -389,11 +389,22 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis
throw new Error(`pages: Ambiguous boundary files '${prior.filePath}' and '${file}'.`);
}
}
if (serverPath) {
const { methods } = deriveFromSource(join(pagesDir, serverPath), 'page-server', (source) =>
detectPageServerMetadata(source, serverPath),
);
if (methods.length > 0) {
throw new Error(
`pages: '${serverPath}' can only export head(). Boundaries have no loader or actions, so remove ${methods.join(', ')}.`,
);
}
}
boundaries.push({
kind: boundary[1] as PageBoundaryDefinition['kind'],
directory,
componentId: base,
filePath: file,
...(serverPath && { serverPath }),
});
continue;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/void/src/pages/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ export type PageBoundaryDefinition = {
directory: string;
componentId: string;
filePath: string;
/** Optional `.server` companion that exports `head()`, relative to pages/. */
serverPath?: string;
};

export type PageError = Readonly<{ status: number; message: string }>;
Expand Down
29 changes: 27 additions & 2 deletions packages/void/src/router/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1057,6 +1057,31 @@ function compilePageRoutes(
];
}
lines.push('const __loadPagesManifest = __createManifestLoader();');
// A boundary's optional `.server` companion supplies head(); its module loads only when that boundary renders.
const boundaryHeadLoaders: Record<string, string> = {};
const boundaryHeadModules = new Map<string, string>();
for (const plan of Object.values(boundaryManifest.plans)) {
const serverPath = scan.pages.boundaries?.find(
(boundary) => boundary.filePath === plan.filePath,
)?.serverPath;
if (!serverPath) {
continue;
}
let loader = boundaryHeadModules.get(serverPath);
if (!loader) {
loader = `__boundaryHead${boundaryHeadModules.size}`;
boundaryHeadModules.set(serverPath, loader);
lines.push(
`const ${loader} = __createModuleLoader(() => import(${JSON.stringify(`${pages.pagesDir}/${serverPath}`)}));`,
);
}
boundaryHeadLoaders[plan.id] = loader;
}
const boundaryHeadsOption = boundaryHeadModules.size
? `boundaryHeads: { ${Object.entries(boundaryHeadLoaders)
.map(([id, loader]) => `${JSON.stringify(id)}: ${loader}`)
.join(', ')} }, `
: '';
const assetMetadata = {
pageCssKeys,
devRootPhases: options.dev ? pageDevRootPhases : undefined,
Expand All @@ -1075,7 +1100,7 @@ function compilePageRoutes(
if (boundaryManifest.root) {
const island = scan.pages.pages.length > 0 && scan.pages.pages.every((page) => page.island);
lines.push(
`const __voidRootNotFoundOptions = { componentId: ${JSON.stringify(boundaryManifest.root)}, load: async () => ({ loader: () => new Response(null, { status: 404 }) }), render: ${island ? 'renderIslandPage' : 'renderPage'}, assets: ${island && pages.islandClientEntryId ? 'getIslandsAssetTags' : 'getPagesAssetTags'}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: island ? 'island' : 'server', dev: options.dev === true, boundaries: { notFound: boundaryManifest.root, errors: boundaryManifest.rootErrors ?? [] } })} }; const __voidRootNotFound = __createPageGetHandler(__voidRootNotFoundOptions); export const __voidRenderStaticNotFound = __createStaticNotFound({ ...__voidRootNotFoundOptions, render: renderPage, assets: getPagesAssetTags });`,
`const __voidRootNotFoundOptions = { ${boundaryHeadsOption}componentId: ${JSON.stringify(boundaryManifest.root)}, load: async () => ({ loader: () => new Response(null, { status: 404 }) }), render: ${island ? 'renderIslandPage' : 'renderPage'}, assets: ${island && pages.islandClientEntryId ? 'getIslandsAssetTags' : 'getPagesAssetTags'}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: island ? 'island' : 'server', dev: options.dev === true, boundaries: { notFound: boundaryManifest.root, errors: boundaryManifest.rootErrors ?? [] } })} }; const __voidRootNotFound = __createPageGetHandler(__voidRootNotFoundOptions); export const __voidRenderStaticNotFound = __createStaticNotFound({ ...__voidRootNotFoundOptions, render: renderPage, assets: getPagesAssetTags });`,
);
}

Expand Down Expand Up @@ -1121,7 +1146,7 @@ function compilePageRoutes(
const pattern = trailingCatchAll ? page.pattern.slice(0, -1) : page.pattern;
const catchAllParam = page.pattern.match(/:([^/{}]+)\{\.\+\}\/$/)?.[1];
const middlewareBoundaries = `middlewareBoundaries: ${JSON.stringify({ notFound: boundaryManifest.root, errors: (boundaryManifest.pages[page.componentId]?.errors ?? []).filter((id) => !boundaryManifest.plans[id].directory) })}, `;
const routeOptions = `{ ${serverImportPath ? 'load: _pload_' + safeId + ', ' : ''}${mdHeadRef ? 'head: ' + mdHeadRef + ', ' : ''}${trailingCatchAll ? `trailingSlash: true, catchAllParam: ${JSON.stringify(catchAllParam)}, ` : ''}${middlewareBoundaries}componentId: ${JSON.stringify(page.componentId)}, render: ${renderer}, assets: ${assetTags}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: page.renderMode, ...(options.dev === true ? { dev: true } : {}), ...(boundaryManifest.pages[page.componentId] && { boundaries: boundaryManifest.pages[page.componentId] }) })} }`;
const routeOptions = `{ ${boundaryHeadsOption}${serverImportPath ? 'load: _pload_' + safeId + ', ' : ''}${mdHeadRef ? 'head: ' + mdHeadRef + ', ' : ''}${trailingCatchAll ? `trailingSlash: true, catchAllParam: ${JSON.stringify(catchAllParam)}, ` : ''}${middlewareBoundaries}componentId: ${JSON.stringify(page.componentId)}, render: ${renderer}, assets: ${assetTags}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: page.renderMode, ...(options.dev === true ? { dev: true } : {}), ...(boundaryManifest.pages[page.componentId] && { boundaries: boundaryManifest.pages[page.componentId] }) })} }`;
lines.push(`app.get(${JSON.stringify(pattern)}, __createPageGetHandler(${routeOptions}));`);
if (page.methods.includes('action') || page.methods.includes('actions')) {
lines.push(
Expand Down
24 changes: 20 additions & 4 deletions packages/void/src/runtime/routing/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,26 @@ export type PageRouteOptions = {
headConfig: PageGetArguments[6] | null;
renderOptions: PageGetArguments[7];
middlewareBoundaries?: NonNullable<PageGetArguments[7]>['boundaries'];
/** Loads the `.server` companion of a boundary component, by plan id. */
boundaryHeads?: NonNullable<NonNullable<PageGetArguments[7]>['boundaries']>['loadHeads'];
namedActions?: boolean;
trailingSlash?: boolean;
catchAllParam?: string;
};
/** Render options with the boundary head loaders, which the JSON-serialized options cannot carry. */
function withBoundaryHeads(
options: PageRouteOptions,
boundaries = options.renderOptions?.boundaries,
): PageGetArguments[7] {
return {
...options.renderOptions,
...(boundaries && {
boundaries: options.boundaryHeads
? { ...boundaries, loadHeads: options.boundaryHeads }
: boundaries,
}),
};
}
// Hono's trie matcher cannot match a named catch-all followed by a literal slash.
// Register that route without the slash, then enforce the public URL and exclude
// the final separator from the parameter before invoking application code.
Expand Down Expand Up @@ -113,7 +129,7 @@ export function createPageErrorHandler(
options.render,
options.assets,
options.headConfig ?? undefined,
{ ...options.renderOptions, boundaries: options.middlewareBoundaries ?? { errors: [] } },
withBoundaryHeads(options, options.middlewareBoundaries ?? { errors: [] }),
);
// oxlint-disable-next-line typescript/return-await -- Keep failures from the fallback outside boundary recovery and restore the route index immediately.
return response ?? fallback(error, c);
Expand Down Expand Up @@ -173,7 +189,7 @@ export function createPageGetHandler(options: PageRouteOptions): (c: Context) =>
options.render,
options.assets,
options.headConfig ?? undefined,
options.renderOptions,
withBoundaryHeads(options),
);
} catch (error) {
const response = await recoverPageHttpException(
Expand All @@ -182,7 +198,7 @@ export function createPageGetHandler(options: PageRouteOptions): (c: Context) =>
options.render,
options.assets,
options.headConfig ?? undefined,
options.renderOptions,
withBoundaryHeads(options),
);
if (response) {
return response;
Expand Down Expand Up @@ -247,7 +263,7 @@ export function createPageMutationHandler(
options.render,
options.assets,
options.headConfig ?? undefined,
options.renderOptions,
withBoundaryHeads(options),
);
};
if (options.namedActions) {
Expand Down
11 changes: 9 additions & 2 deletions packages/void/test/integration/page-errors-suite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ export default defineMiddleware(async (c, next) => {
),
);
write(`pages/_error.${extension}`, component('<h1>Error page</h1><p>{error.message}</p>'));
write(
'pages/_not-found.server.ts',
`import { defineHead } from 'void/handler';
export const head = defineHead<{ error: { status: number } }>((_c, { error }) => ({ title: error.status === 404 ? 'Page not found' : 'Unexpected status' }));`,
);
if (framework === 'vue') {
write(
`pages/_not-found.${extension}`,
Expand Down Expand Up @@ -386,7 +391,7 @@ export const loader = defineHandler(c => {
expect(response.headers.get('X-Security')).toBe('retained');
const text = await response.text();
expect(text).not.toContain('SECRET_');
const title = `${status === 404 ? 'Not Found' : 'Internal Server Error'} | Error tests`;
const title = `${status === 404 ? 'Page not found' : 'Internal Server Error'} | Error tests`;
if (pages) {
expect(response.headers.get('X-VoidPages')).toBe('true');
expect(deserializePageData(text)).toMatchObject({
Expand Down Expand Up @@ -476,7 +481,9 @@ export const loader = defineHandler(c => {
if (name !== 'Crash') {
await expect
.poll(() => page.title())
.toBe(`${name === 'Unexpected' ? 'Internal Server Error' : 'Not Found'} | Error tests`);
.toBe(
`${name === 'Unexpected' ? 'Internal Server Error' : 'Page not found'} | Error tests`,
);
}
expect(await page.evaluate(() => (window as unknown as { marker: boolean }).marker)).toBe(
true,
Expand Down
Loading