diff --git a/docs/guide/pages-routing/errors.md b/docs/guide/pages-routing/errors.md
index dbb0f253c..7abb3f404 100644
--- a/docs/guide/pages-routing/errors.md
+++ b/docs/guide/pages-routing/errors.md
@@ -114,6 +114,40 @@ Error components handle these exceptions on page GET and HEAD requests. API rout
Use [`c.status()`](./loaders.md#response-status) instead when you want an error status while rendering the requested page with its normal props.
+## 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, export a `head` with a string `title` from `_not-found` or `_error`:
+
+::: code-group
+
+```tsx [React]
+// pages/_not-found.tsx
+export const head = { title: 'Page not found' };
+```
+
+```vue [Vue]
+
+
+```
+
+```svelte [Svelte]
+
+
+```
+
+```tsx [Solid]
+// pages/_not-found.tsx
+export const head = { title: 'Page not found' };
+```
+
+:::
+
+Declare it as an object literal with `title` as its only field; Void reads it from the source, so other forms are ignored with a warning. An `_error` title applies to every status that component renders.
+
## Nested errors
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.
diff --git a/packages/void/src/pages/boundary-plans.ts b/packages/void/src/pages/boundary-plans.ts
index d9de7e6fa..02f0cf263 100644
--- a/packages/void/src/pages/boundary-plans.ts
+++ b/packages/void/src/pages/boundary-plans.ts
@@ -9,11 +9,14 @@ export type BoundaryPlan = {
kind: 'error' | 'not-found';
source: string;
layouts: Array;
+ head?: { title: string };
};
export type PageBoundaryPlans = {
notFound?: string;
notFoundErrors?: Array;
errors: Array;
+ /** Titles a boundary component declares, by plan id. */
+ heads?: Record;
catches: Array<{ depth: number; plan: string }>;
};
export type BoundaryManifest = {
@@ -22,6 +25,20 @@ export type BoundaryManifest = {
root?: string;
rootErrors?: Array;
};
+/** The declared heads of the plans a request may render, keyed by plan id. */
+export function boundaryHeads(
+ plans: BoundaryManifest['plans'],
+ ids: ReadonlyArray,
+): Pick {
+ const heads: Record = {};
+ for (const id of ids) {
+ const head = id ? plans[id]?.head : undefined;
+ if (id && head) {
+ heads[id] = head;
+ }
+ }
+ return Object.keys(heads).length > 0 ? { heads } : {};
+}
const encloses = (outer: string, inner: string) =>
!outer || outer === inner || inner.startsWith(outer + '/');
@@ -50,7 +67,7 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest {
};
const errors = candidates.filter((b) => b.kind === 'error');
const notFound = candidates.find((b) => b.kind === 'not-found');
- pages[page.componentId] = {
+ const entry: PageBoundaryPlans = {
...(notFound
? {
notFound: add(notFound),
@@ -65,6 +82,10 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest {
plan: add(b),
})),
};
+ pages[page.componentId] = {
+ ...entry,
+ ...boundaryHeads(plans, [entry.notFound, ...(entry.notFoundErrors ?? []), ...entry.errors]),
+ };
}
const root = scan.boundaries?.find((b) => b.kind === 'not-found' && !b.directory);
if (root) {
@@ -86,6 +107,7 @@ export function createBoundaryManifest(scan: PageScanResult): BoundaryManifest {
}
pages[id] = {
errors: rootErrors,
+ ...boundaryHeads(plans, [id, ...rootErrors]),
catches: rootErrors.map((plan) => ({ depth: plans[id].layouts.length, plan })),
};
return { plans, pages, root: id, rootErrors };
diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts
index 10288cdee..d2010fee0 100644
--- a/packages/void/src/pages/protocol.ts
+++ b/packages/void/src/pages/protocol.ts
@@ -74,7 +74,13 @@ type PageRenderOptions = {
renderMode?: PageRenderMode;
/** Dev server build: rejected deferred props keep their raw error message. */
dev?: boolean;
- boundaries?: { notFound?: string; notFoundErrors?: Array; errors: Array };
+ boundaries?: {
+ notFound?: string;
+ notFoundErrors?: Array;
+ errors: Array;
+ /** Titles the boundary components declare, by plan id. */
+ heads?: Record;
+ };
};
type AssetTags = {
css: string;
@@ -529,6 +535,7 @@ async function renderPageFailure(
continue;
}
attempted.add(component);
+ const declaredTitle = options?.boundaries?.heads?.[component];
const page: PageObject = {
component,
props: { error: { status, message } },
@@ -538,16 +545,17 @@ async function renderPageFailure(
errors: null,
head: {
...head,
- title:
- head?.title ??
- resolveHead(configHead, middlewareHead, {
- title:
- status === 404
- ? 'Not Found'
- : recoverHttpError && status !== 500
- ? message
- : 'Internal Server Error',
- })?.title,
+ title: declaredTitle
+ ? resolveHead(configHead, middlewareHead, declaredTitle)?.title
+ : (head?.title ??
+ resolveHead(configHead, middlewareHead, {
+ title:
+ status === 404
+ ? 'Not Found'
+ : recoverHttpError && status !== 500
+ ? message
+ : 'Internal Server Error',
+ })?.title),
},
};
try {
diff --git a/packages/void/src/pages/scan.ts b/packages/void/src/pages/scan.ts
index d98fecd25..ba196e34d 100644
--- a/packages/void/src/pages/scan.ts
+++ b/packages/void/src/pages/scan.ts
@@ -26,6 +26,7 @@ import {
readStaticExports,
staticExports,
staticLiteral,
+ unwrapStaticExpression,
} from '../shared/static-exports.ts';
import { MARKDOWN_SCRIPT_RE, scriptBlocks } from './island-imports.ts';
import { resolveNamedLayout } from './layout-resolution.ts';
@@ -161,6 +162,53 @@ function componentLayout(source: string, filename: string): ComponentLayout {
return { layout: undefined, warnings: [] };
}
+type BoundaryHead = {
+ head: { title: string } | undefined;
+ /** Head exports the scan ignores, reported once by scanPages. */
+ warnings: Array;
+};
+
+const HEAD_EXPORT: ReadonlySet = new Set(['head']);
+
+/** The `title` of an `export const head = { title: '...' }` in a boundary component. */
+function boundaryHead(source: string, filename: string): BoundaryHead {
+ const ignored = (reason: string) =>
+ `pages: head in '${filename}' is ignored. ${reason} Declare it as \`export const head = { title: 'Page not found' }\`.`;
+ for (const script of scriptBlocks(source, filename)) {
+ // `export let head` in a Svelte instance script declares a prop of that name.
+ if (script.instance || !script.source.includes('head')) {
+ continue;
+ }
+ const exports = readStaticExports(script.filename, script.source, HEAD_EXPORT);
+ if (exports.unreadable.has('head')) {
+ return {
+ head: undefined,
+ warnings: [ignored('Re-exported heads and other export forms are not read.')],
+ };
+ }
+ const initializer = unwrapStaticExpression(exports.initializers.get('head'));
+ if (!initializer) {
+ continue;
+ }
+ const properties = (
+ initializer.type === 'ObjectExpression' ? initializer.properties : []
+ ) as Array;
+ const only = properties.length === 1 ? properties[0] : undefined;
+ const key = only?.type === 'Property' && !only.computed ? (only.key as AstNode) : undefined;
+ const title =
+ (isIdentifier(key) ? key.name : staticLiteral(key)) === 'title'
+ ? staticLiteral(only?.value as AstNode | undefined)
+ : undefined;
+ return typeof title === 'string'
+ ? { head: { title }, warnings: [] }
+ : {
+ head: undefined,
+ warnings: [ignored('It must be an object literal whose only field is a string `title`.')],
+ };
+ }
+ return { head: undefined, warnings: [] };
+}
+
const TRANSPARENT_EXPRESSION_TYPES = new Set([
'ParenthesizedExpression',
'TSAsExpression',
@@ -389,11 +437,18 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis
throw new Error(`pages: Ambiguous boundary files '${prior.filePath}' and '${file}'.`);
}
}
+ const { head, warnings } = deriveFromSource(
+ join(pagesDir, file),
+ 'page-boundary-head',
+ (source) => boundaryHead(source, file),
+ );
+ warnPageSettings(pagesDir, warnings);
boundaries.push({
kind: boundary[1] as PageBoundaryDefinition['kind'],
directory,
componentId: base,
filePath: file,
+ ...(head && { head }),
});
continue;
}
diff --git a/packages/void/src/pages/types.ts b/packages/void/src/pages/types.ts
index ce3cbdaba..503e4a935 100644
--- a/packages/void/src/pages/types.ts
+++ b/packages/void/src/pages/types.ts
@@ -76,6 +76,8 @@ export type PageBoundaryDefinition = {
directory: string;
componentId: string;
filePath: string;
+ /** From `export const head = { title }` in the boundary component. */
+ head?: { title: string };
};
export type PageError = Readonly<{ status: number; message: string }>;
diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts
index 968366150..0b35d118b 100644
--- a/packages/void/src/router/compile.ts
+++ b/packages/void/src/router/compile.ts
@@ -4,7 +4,7 @@ import type { VoidAuthProvider } from '../auth/providers.ts';
import type { DevRedirectRule, HeaderRule } from '../cli/types.ts';
import type { NotFoundHandling } from '../config.ts';
import type { MigrationPlanBundle } from '../migrations/plan.ts';
-import { createBoundaryManifest } from '../pages/boundary-plans.ts';
+import { boundaryHeads, createBoundaryManifest } from '../pages/boundary-plans.ts';
import { resolveLayoutIds } from '../pages/layout-resolution.ts';
import { patternToRegex } from '../pages/manifest.ts';
import { cloudflareQueueName } from '../queues/cloudflare-names.ts';
@@ -1074,7 +1074,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 = { 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 ?? [], ...boundaryHeads(boundaryManifest.plans, [boundaryManifest.root, ...(boundaryManifest.rootErrors ?? [])]) } })} }; const __voidRootNotFound = __createPageGetHandler(__voidRootNotFoundOptions); export const __voidRenderStaticNotFound = __createStaticNotFound({ ...__voidRootNotFoundOptions, render: renderPage, assets: getPagesAssetTags });`,
);
}
@@ -1119,7 +1119,10 @@ function compilePageRoutes(
const trailingCatchAll = options.trailingSlash && page.catchAll;
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 middlewareErrors = (boundaryManifest.pages[page.componentId]?.errors ?? []).filter(
+ (id) => !boundaryManifest.plans[id].directory,
+ );
+ const middlewareBoundaries = `middlewareBoundaries: ${JSON.stringify({ notFound: boundaryManifest.root, errors: middlewareErrors, ...boundaryHeads(boundaryManifest.plans, [boundaryManifest.root, ...middlewareErrors]) })}, `;
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] }) })} }`;
lines.push(`app.get(${JSON.stringify(pattern)}, __createPageGetHandler(${routeOptions}));`);
if (page.methods.includes('action') || page.methods.includes('actions')) {
diff --git a/packages/void/test/unit/page-boundaries.test.ts b/packages/void/test/unit/page-boundaries.test.ts
index 9f6435906..df8734af1 100644
--- a/packages/void/test/unit/page-boundaries.test.ts
+++ b/packages/void/test/unit/page-boundaries.test.ts
@@ -127,6 +127,72 @@ describe('Pages boundary inventory', () => {
});
});
+describe('boundary head exports', () => {
+ it.each([
+ [
+ '_not-found.tsx',
+ `export const head = { title: 'Page not found' }; export default () => null`,
+ ],
+ [
+ '_not-found.vue',
+ `\n\n`,
+ ],
+ [
+ '_not-found.svelte',
+ `\n`,
+ ],
+ ])('reads a static title from %s', async (file, source) => {
+ const scan = await scanPages(fixture({ [file]: source }));
+ expect(scan.boundaries).toEqual([
+ {
+ kind: 'not-found',
+ directory: '',
+ componentId: '_not-found',
+ filePath: file,
+ head: { title: 'Page not found' },
+ },
+ ]);
+ });
+
+ it.each([
+ `const title = 'Page not found'; export const head = { title }; export default () => null`,
+ `export const head = { title: 'Gone', meta: [] }; export default () => null`,
+ `export const head = () => ({ title: 'Gone' }); export default () => null`,
+ `export let head = { title: 'Gone' }; export default () => null`,
+ ])('ignores a head it cannot read statically: %s', async (source) => {
+ const scan = await scanPages(fixture({ '_error.tsx': source }));
+ expect(scan.boundaries).toEqual([
+ { kind: 'error', directory: '', componentId: '_error', filePath: '_error.tsx' },
+ ]);
+ });
+
+ it('hands the declared titles to every plan a page can render', async () => {
+ const root = fixture({
+ 'layout.tsx': 'export default () => null',
+ 'items/page.tsx': 'export default () => null',
+ '_not-found.tsx': `export const head = { title: 'Page not found' }; export default () => null`,
+ '_error.tsx': 'export default () => null',
+ 'items/_error.tsx': `export const head = { title: 'Items broke' }; export default () => null`,
+ });
+ const manifest = createBoundaryManifest(await scanPages(root));
+ const titles = (id: string) =>
+ Object.fromEntries(
+ Object.entries(manifest.pages[id].heads ?? {}).map(([plan, head]) => [
+ manifest.plans[plan].componentId,
+ head.title,
+ ]),
+ );
+ expect(titles('items/page')).toEqual({
+ '_not-found': 'Page not found',
+ 'items/_error': 'Items broke',
+ });
+ expect(manifest.pages['items/page'].errors).toHaveLength(2);
+ // The root not-found page and its error page render outside any route.
+ expect(manifest.root).toBeDefined();
+ expect(titles(manifest.root ?? '')).toEqual({ '_not-found': 'Page not found' });
+ });
+});
+
describe('boundary render plans', () => {
it('keeps named replacements at their logical slot instead of their file directory', async () => {
const root = fixture({
@@ -658,6 +724,92 @@ describe.each([false, true])('boundary titles (Pages: %s)', (pages) => {
);
});
+describe.each([false, true])('declared boundary titles (Pages: %s)', (pages) => {
+ it.each([
+ { status: 404, expected: 'Page not found | Site' },
+ { status: 500, expected: 'Something went wrong | Site' },
+ {
+ status: 404,
+ middlewareTitle: 'Ignored',
+ middlewareTemplate: '%s | Admin',
+ expected: 'Page not found | Admin',
+ },
+ ])(
+ 'renders $expected for status $status',
+ async ({ status, expected, middlewareTitle, middlewareTemplate }) => {
+ const app = new Hono();
+ app.use(async (c, next) => {
+ if (middlewareTemplate) {
+ c.set('headDefaults', { title: middlewareTitle, titleTemplate: middlewareTemplate });
+ }
+ await next();
+ });
+ app.get(
+ '/',
+ createPageGetHandler({
+ componentId: 'index',
+ load: async () => ({
+ loader: () => {
+ if (status === 404) {
+ return new Response(null, { status: 404 });
+ }
+ throw new Error('SECRET_FAILURE');
+ },
+ }),
+ assets: async () => ({ css: '', body: '', preloads: '' }),
+ headConfig: { titleTemplate: '%s | Site' },
+ renderOptions: {
+ boundaries: {
+ notFound: 'missing-plan',
+ errors: ['error-plan'],
+ heads: {
+ 'missing-plan': { title: 'Page not found' },
+ 'error-plan': { title: 'Something went wrong' },
+ },
+ },
+ },
+ render: async (page) => renderHeadToString(page.head!),
+ }),
+ );
+ const response = await app.request('https://app.test/', {
+ headers: pages
+ ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
+ : {},
+ });
+ expect(response.status).toBe(status);
+ const body = await response.text();
+ if (pages) {
+ expect(deserializePageData(body)).toMatchObject({ head: { title: expected } });
+ } else {
+ expect(body).toContain(`${expected}`);
+ }
+ },
+ );
+
+ it('keeps the default title for a boundary that declares none', async () => {
+ const app = new Hono();
+ app.get(
+ '/',
+ createPageGetHandler({
+ componentId: 'index',
+ load: async () => ({ loader: () => new Response(null, { status: 404 }) }),
+ assets: async () => ({ css: '', body: '', preloads: '' }),
+ headConfig: { titleTemplate: '%s | Site' },
+ renderOptions: {
+ boundaries: {
+ notFound: 'missing-plan',
+ errors: ['error-plan'],
+ heads: { 'error-plan': { title: 'Something went wrong' } },
+ },
+ },
+ render: async (page) => renderHeadToString(page.head!),
+ }),
+ );
+ const response = await app.request('https://app.test/');
+ expect(await response.text()).toContain('Not Found | Site');
+ });
+});
+
describe('boundary recovery failures', () => {
it.each(['malformed JSON', 'body rejection', 'exhausted fallback'])(
'handles %s without replaying the loader',