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
34 changes: 34 additions & 0 deletions docs/guide/pages-routing/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
<!-- pages/_not-found.vue -->
<script lang="ts">
export const head = { title: 'Page not found' };
</script>
```

```svelte [Svelte]
<!-- pages/_not-found.svelte -->
<script module lang="ts">
export const head = { title: 'Page not found' };
</script>
```

```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.
Expand Down
24 changes: 23 additions & 1 deletion packages/void/src/pages/boundary-plans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ export type BoundaryPlan = {
kind: 'error' | 'not-found';
source: string;
layouts: Array<string>;
head?: { title: string };
};
export type PageBoundaryPlans = {
notFound?: string;
notFoundErrors?: Array<string>;
errors: Array<string>;
/** Titles a boundary component declares, by plan id. */
heads?: Record<string, { title: string }>;
catches: Array<{ depth: number; plan: string }>;
};
export type BoundaryManifest = {
Expand All @@ -22,6 +25,20 @@ export type BoundaryManifest = {
root?: string;
rootErrors?: Array<string>;
};
/** The declared heads of the plans a request may render, keyed by plan id. */
export function boundaryHeads(
plans: BoundaryManifest['plans'],
ids: ReadonlyArray<string | undefined>,
): Pick<PageBoundaryPlans, 'heads'> {
const heads: Record<string, { title: string }> = {};
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 + '/');

Expand Down Expand Up @@ -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),
Expand All @@ -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) {
Expand All @@ -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 };
Expand Down
30 changes: 19 additions & 11 deletions packages/void/src/pages/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>; errors: Array<string> };
boundaries?: {
notFound?: string;
notFoundErrors?: Array<string>;
errors: Array<string>;
/** Titles the boundary components declare, by plan id. */
heads?: Record<string, { title: string }>;
};
};
type AssetTags = {
css: string;
Expand Down Expand Up @@ -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 } },
Expand All @@ -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 {
Expand Down
55 changes: 55 additions & 0 deletions packages/void/src/pages/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string>;
};

const HEAD_EXPORT: ReadonlySet<string> = 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<AstNode>;
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',
Expand Down Expand Up @@ -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;
}
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;
/** From `export const head = { title }` in the boundary component. */
head?: { title: string };
};

export type PageError = Readonly<{ status: number; message: string }>;
Expand Down
9 changes: 6 additions & 3 deletions packages/void/src/router/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 });`,
);
}

Expand Down Expand Up @@ -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')) {
Expand Down
Loading