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
22 changes: 20 additions & 2 deletions docs/guide/pages-routing/head.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Set page titles and metadata with `head()`, middleware, or site-wide defaults. P

## Page titles and metadata

Export a `head()` function from your `.server.ts` file. It receives the Hono context and the resolved loader props, and returns a `HeadDescriptor`:
Export a `head()` function from your `.server.ts` file. It receives the Hono context and the resolved loader props, and returns a `HeadConfig`: the [head fields](#headdescriptor) plus an optional [`titleTemplate`](#page-title-templates):

```ts
// pages/posts/[slug].server.ts
Expand Down Expand Up @@ -98,13 +98,29 @@ A page returning `{ title: "Users" }` under `/admin` produces `<title>Users | Ad

To drop the suffix entirely for a section, including the config's, set the template to an empty string: `c.set('headDefaults', { ...c.get('headDefaults'), titleTemplate: '' })`. A page returning `{ title: "Users" }` under `/admin` then produces `<title>Users</title>`.

## Page title templates

A page's `head()` can also return `titleTemplate`. It replaces the template from middleware and config for that page. Use it when a page's title already names the site, such as a home page:

```ts
// pages/index.server.ts
import { defineHead } from 'void';

export const head = defineHead(() => ({
title: 'My Site | Guides and Tutorials',
titleTemplate: '', // [!code highlight]
}));
```

With `"titleTemplate": "%s | My Site"` in config, this page produces `<title>My Site | Guides and Tutorials</title>`, while other pages keep the suffix. An empty string drops the template. Any other value replaces it, so `titleTemplate: '%s - Docs'` gives the page its own suffix.

## Precedence

When multiple layers provide head data, they merge with this precedence:

| Field | Behavior |
| ----------- | -------------------------------------------------------------------------------------------------------------------- |
| `title` | Page wins. `titleTemplate` from middleware, or else from config, wraps the winning title. |
| `title` | Page wins. `titleTemplate` from the page, or else middleware, or else config, wraps the winning title. |
| `meta` | Deduplicates by `name` or `property`. Page entries override matching keys, and non-conflicting entries are appended. |
| `link` | Concatenated: config first, then middleware, then page. |
| `script` | Concatenated: config first, then middleware, then page. |
Expand Down Expand Up @@ -143,6 +159,8 @@ Absolute URLs and other tags keep the values you provide. For prerendered pages,

## HeadDescriptor

Page `head()`, middleware `headDefaults` and the `head` config also accept `titleTemplate?: string` (the `HeadConfig` type).

```ts
interface HeadDescriptor {
title?: string;
Expand Down
6 changes: 3 additions & 3 deletions docs/reference/api/handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ interface RenderAssetTags {

## `defineHead<P>(handler)` {#definehead-p-handler}

Type-safe wrapper for the page `head()` export in `.server.ts` files. Provides [`CloudContext`](./types.md#cloudcontext) typing for the first argument and generic props typing for the second.
Type-safe wrapper for the page `head()` export in `.server.ts` files. It returns a [`HeadConfig`](./types.md#headconfig). Provides [`CloudContext`](./types.md#cloudcontext) typing for the first argument and generic props typing for the second.

```ts
import { defineHandler, defineHead } from 'void';
Expand Down Expand Up @@ -254,6 +254,6 @@ export const head = defineHead<Props>((c, props) => {

```ts
function defineHead<P = Record<string, unknown>>(
handler: (c: CloudContext, props: P) => HeadDescriptor | undefined,
): (c: CloudContext, props: P) => HeadDescriptor | undefined;
handler: (c: CloudContext, props: P) => HeadConfig | undefined,
): (c: CloudContext, props: P) => HeadConfig | undefined;
```
12 changes: 11 additions & 1 deletion docs/reference/api/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ interface TypedHandler<V extends ValidatorSlots = {}, R = unknown> {

## `HeadDescriptor` {#headdescriptor}

Shape of page head metadata returned by `defineHead`. All fields are optional.
Shape of page head metadata. All fields are optional.

```ts
interface HeadDescriptor {
Expand All @@ -85,6 +85,16 @@ interface HeadDescriptor {
}
```

## `HeadConfig` {#headconfig}

Head metadata returned by `defineHead`, set as middleware `headDefaults`, or set as `head` in `void.config.ts`. It adds `titleTemplate` to [`HeadDescriptor`](#headdescriptor). `%s` is replaced with the page title. A page's template replaces the middleware's, which replaces the config's. An empty string drops the template.

```ts
type HeadConfig = HeadDescriptor & {
titleTemplate?: string;
};
```

## `RouteMap` {#routemap}

Generated route types used by the typed `fetch` client. Contains each route’s methods, inputs, and outputs.
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ Site-wide HTML `<head>` defaults for pages mode. Sets a title template, default
| Field | Type | Description |
| --------------- | ------------------------ | ---------------------------------------------------------------- |
| `title` | `string` | Default page title (overridden by page `head()`) |
| `titleTemplate` | `string` | Wraps the resolved title. `%s` is replaced with the page title. |
| `titleTemplate` | `string` | Wraps the title at `%s`. Page or middleware templates replace it |
| `meta` | `Array<object>` | Default `<meta>` tags (deduped by `name`/`property`, page wins) |
| `link` | `Array<object>` | Default `<link>` tags (concatenated: config, middleware, page) |
| `script` | `Array<object>` | Default `<script>` tags (concatenated: config, middleware, page) |
Expand Down
16 changes: 11 additions & 5 deletions packages/void/src/pages/head.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,29 @@ export type HeadDescriptor = {
bodyAttrs?: Record<string, string>;
};

/** Project-level head config with template support. */
/** Head metadata with title template support, for config, middleware and pages. */
export type HeadConfig = HeadDescriptor & {
/** Title template — `%s` is replaced with the page title. */
/**
* Title template — `%s` is replaced with the page title. A page or
* middleware value replaces the one from a lower layer; an empty string
* drops the template.
*/
titleTemplate?: string;
};

/**
* Merge head descriptors with precedence: page > middleware > config.
*
* - `title`: page wins; `titleTemplate` from middleware, else config, wraps it (`%s` replaced)
* - `title`: page wins; `titleTemplate` from the page, else middleware, else config, wraps it
* (`%s` replaced). An empty template drops the ones below it.
* - `meta`: page overrides entries with same `name`/`property`; others appended
* - `link`/`script`: concatenated (config first, then middleware, then page)
* - `htmlAttrs`/`bodyAttrs`: shallow merge, page wins conflicts
*/
export function resolveHead(
configHead: HeadConfig | undefined,
middlewareHead: HeadConfig | undefined,
pageHead: HeadDescriptor | undefined,
pageHead: HeadConfig | undefined,
): HeadDescriptor | undefined {
if (!configHead && !middlewareHead && !pageHead) {
return undefined;
Expand All @@ -36,7 +41,8 @@ export function resolveHead(

const title = pageHead?.title ?? middlewareHead?.title ?? configHead?.title;
if (title !== undefined) {
const template = middlewareHead?.titleTemplate ?? configHead?.titleTemplate;
const template =
pageHead?.titleTemplate ?? middlewareHead?.titleTemplate ?? configHead?.titleTemplate;
result.title = template ? template.replace('%s', () => title) : title;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/void/src/pages/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ type ValidationErrorBody = {

type PageHandler = ((c: CloudContext) => unknown | Promise<unknown>) | undefined;
type PageHeadHandler =
| ((c: CloudContext, props: Record<string, unknown>) => HeadDescriptor | undefined)
| ((c: CloudContext, props: Record<string, unknown>) => HeadConfig | undefined)
| undefined;
type PageRequestContext = Context | CloudContext;
type PageRenderOptions = {
Expand Down Expand Up @@ -763,7 +763,7 @@ function resolveRequestHead(
c: CloudContext,
configHead: HeadConfig | undefined,
middlewareHead: HeadConfig | undefined,
pageHead: HeadDescriptor | undefined,
pageHead: HeadConfig | undefined,
): HeadDescriptor | undefined {
const head = resolveHead(configHead, middlewareHead, pageHead);
return absolutizeHead(
Expand Down
6 changes: 3 additions & 3 deletions packages/void/src/runtime/handler/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Context, Env, MiddlewareHandler, Next, TypedResponse } from 'hono';
import type { RedirectStatusCode } from 'hono/utils/http-status';
import type { RewriteDestination, RouteDestination, RouteUrl, RouteUrlInput } from 'void/routes';
import type { HeadConfig, HeadDescriptor } from '../../pages/head.ts';
import type { HeadConfig } from '../../pages/head.ts';
import { base64ToBytes } from '../../shared/base64.ts';
import type { AuthSession, AuthUser } from '../auth/index.ts';
import type { TypedRoutes } from '../routing/route-url.ts';
Expand Down Expand Up @@ -498,8 +498,8 @@ export function defineRender(handler: RenderFn): RenderFn {
* At runtime it simply returns the function passed to it.
*/
export function defineHead<P = Record<string, unknown>>(
handler: (c: CloudContext, props: P) => HeadDescriptor | undefined,
): (c: CloudContext, props: P) => HeadDescriptor | undefined {
handler: (c: CloudContext, props: P) => HeadConfig | undefined,
): (c: CloudContext, props: P) => HeadConfig | undefined {
return handler;
}

Expand Down
38 changes: 38 additions & 0 deletions packages/void/test/unit/pages-head.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,44 @@ describe('resolveHead', () => {
expect(resolveHead(config, middleware, page)?.title).toBe('Users');
});

it('page titleTemplate wins over middleware and config', () => {
const config: HeadConfig = { titleTemplate: '%s | My Site' };
const middleware: HeadConfig = { titleTemplate: '%s | Admin' };
const page: HeadConfig = { title: 'Users', titleTemplate: '%s - Team' };
expect(resolveHead(config, middleware, page)?.title).toBe('Users - Team');
expect(resolveHead(config, undefined, page)?.title).toBe('Users - Team');
});

it('lets a page skip the template with an empty string or `%s`', () => {
const config: HeadConfig = { titleTemplate: '%s | My App' };
const middleware: HeadConfig = { titleTemplate: '%s | Admin' };
const title = 'My App | Questions & Answers';
for (const titleTemplate of ['', '%s']) {
expect(resolveHead(config, middleware, { title, titleTemplate })?.title).toBe(title);
expect(resolveHead(config, undefined, { title, titleTemplate })?.title).toBe(title);
}
});

it('wraps a lower-layer title with the page titleTemplate', () => {
const middleware: HeadConfig = { title: 'Dashboard', titleTemplate: '%s | Admin' };
const page: HeadConfig = { titleTemplate: '%s | Reports' };
expect(resolveHead(undefined, middleware, page)?.title).toBe('Dashboard | Reports');
});

it('keeps the middleware or config template when the page sets none', () => {
const config: HeadConfig = { titleTemplate: '%s | My Site' };
const middleware: HeadConfig = { titleTemplate: '%s | Admin' };
const page: HeadConfig = { title: 'Users', titleTemplate: undefined };
expect(resolveHead(config, middleware, page)?.title).toBe('Users | Admin');
expect(resolveHead(config, undefined, page)?.title).toBe('Users | My Site');
});

it('does not emit a page titleTemplate, or a head for a template alone', () => {
const page: HeadConfig = { title: 'Users', titleTemplate: '%s | Team' };
expect(resolveHead(undefined, undefined, page)).toEqual({ title: 'Users | Team' });
expect(resolveHead(undefined, undefined, { titleTemplate: '%s | Team' })).toBeUndefined();
});

it('inserts a title containing `$` replacement patterns as written', () => {
const middleware: HeadConfig = { titleTemplate: '%s | Admin' };
for (const title of ['A $& B', 'Price $` x', "x $' y", 'Tom $$ Jerry', '$1 off']) {
Expand Down
35 changes: 35 additions & 0 deletions packages/void/test/unit/routing-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { _validateEnvOnce, defineEnv, env } from '../../src/runtime/env/public.t
import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts';
import {
defineHandler,
defineHead,
defineMiddleware,
type CloudContext,
} from '../../src/runtime/handler/index.ts';
Expand Down Expand Up @@ -1266,6 +1267,40 @@ describe('typed Pages and SSR execution', () => {
expect(await title('/admin/users')).toBe('Users | Admin');
expect(await title('/users')).toBe('Users | My Site');
});
it('lets a page head replace or skip the titleTemplate', async () => {
const app = new Hono();
app.use(
'/admin/*',
defineMiddleware(async (c, next) => {
c.set('headDefaults', { ...c.get('headDefaults'), titleTemplate: '%s | Admin' });
await next();
}),
);
const own = defineHead(() => ({ title: 'Reports', titleTemplate: '%s - Team' }));
const skip = defineHead(() => ({ title: 'My App | Q&A', titleTemplate: '' }));
const page = (head: typeof own) =>
createPageGetHandler({
...pageOptions,
headConfig: { titleTemplate: '%s | My App' },
load: async () => ({ loader: () => ({}), head }),
});
app.get('/admin/reports', page(own));
app.get('/reports', page(own));
app.get('/admin/home', page(skip));
app.get('/', page(skip));
const title = async (path: string) => {
const response = await app.fetch(
new Request('https://app.test' + path, {
headers: { 'x-voidpages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION },
}),
);
return (decodePageData(await response.json()) as { head?: { title?: string } }).head?.title;
};
expect(await title('/admin/reports')).toBe('Reports - Team');
expect(await title('/reports')).toBe('Reports - Team');
expect(await title('/admin/home')).toBe('My App | Q&A');
expect(await title('/')).toBe('My App | Q&A');
});
it('redirects extensionless Pages requests to trailing slashes without changing APIs or files', async () => {
const app = new Hono();
const routing = createRoutingRuntime(app, { nodeTarget: true });
Expand Down