fix: make <Head> work in client (#3252)

Closes #3310

---------

Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Marvin Hagemeister
2026-03-29 21:21:39 +02:00
committed by GitHub
co-authored by Bartek Iwańczuk Claude Opus 4.6
parent 19d3589b9b
commit a79b155e79
19 changed files with 557 additions and 131 deletions
+29 -9
View File
@@ -43,11 +43,6 @@ export default define.page((ctx) => {
For more complex scenarios, or to set page metadata from
[islands](/docs/concepts/islands), Fresh ships with the `<Head>`-component.
> [info]: The `<Head>` component is not dynamic by default. It will not
> automatically update the document title or other head elements on the client
> side when component state changes. The head elements are set during server
> rendering or initial page load.
```tsx routes/about.tsx
import { Head } from "fresh/runtime";
@@ -64,6 +59,29 @@ export default define.page((ctx) => {
});
```
### Dynamic head updates from islands
The `<Head>` component works in [islands](/docs/concepts/islands) too. When
component state changes, the document head is updated automatically:
```tsx islands/MetaUpdater.tsx
import { useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export default function MetaUpdater() {
const [title, setTitle] = useState("Welcome");
return (
<div>
<Head>
<title>{title}</title>
</Head>
<button onClick={() => setTitle("Updated!")}>Change title</button>
</div>
);
}
```
### Avoiding duplicate tags
You might end up with duplicate tags, when multiple `<Head />` components are
@@ -75,13 +93,15 @@ the matching element:
3. Check if an element with the same `id` attribute
4. Only for `<meta>` elements: Check if there is a `<meta>` element with the
same `name` attribute
5. No matching element was found, Fresh will create a new one and append it to
5. Only for `<link>` elements: Check if there is a `<link>` element with the
same `rel` attribute
6. No matching element was found, Fresh will create a new one and append it to
`<head>`
When multiple `<Head>` components render an element with the same key, the
**last one rendered wins**. Since Fresh renders top-down (app wrapper → layout →
route → page component), a route page can override defaults set in `_app.tsx` by
using the same `key` prop.
**last one rendered wins**. Since Fresh renders top-down (app wrapper -> layout
-> route -> page component), a route page can override defaults set in
`_app.tsx` by using the same `key` prop.
> [info]: The `<title>`-tag is automatically deduplicated, even without a `key`
> prop.
@@ -1,4 +1,4 @@
import { Fragment, h, options as preactOptions } from "preact";
import { Fragment, h, options as preactOptions, type VNode } from "preact";
import {
assetHashingHook,
CLIENT_NAV_ATTR,
@@ -7,87 +7,109 @@ import {
} from "../shared_internal.ts";
import { BUILD_ID } from "@fresh/build-id";
import { renderToString } from "preact-render-to-string";
import { useEffect } from "preact/hooks";
import { useContext, useEffect } from "preact/hooks";
import { HeadContext } from "../head.ts";
// deno-lint-ignore no-explicit-any
const options: InternalPreactOptions = preactOptions as any;
function WrappedHead(
// deno-lint-ignore no-explicit-any
{ originalType, props, key }: { originalType: string; props: any; key: any },
) {
const enabled = useContext(HeadContext);
useEffect(() => {
if (!enabled) return;
const text = renderToString(h(Fragment, null, props.children));
if (originalType === "title") {
document.title = text;
return;
}
let matched: HTMLElement | null = null;
if (key) {
matched = document.head.querySelector(
`head [data-key="${key}"]`,
) as HTMLElement ?? null;
}
if (matched === null && props.id) {
matched = document.head.querySelector(
`#${props.id}`,
) as HTMLElement ??
null;
}
if (matched === null) {
if (originalType === "meta") {
matched = document.head.querySelector(
`head [name="${props.name}"]`,
) as HTMLElement ?? null;
} else if (originalType === "link" && props.rel) {
matched = document.head.querySelector(
`head link[rel="${props.rel}"]`,
) as HTMLElement ?? null;
} else if (originalType === "base") {
matched = document.head.querySelector(originalType) ?? null;
}
}
if (matched === null) {
matched = document.createElement(originalType);
}
if (matched.textContent !== text) {
matched.textContent = text;
}
applyProps(props, matched);
}, [originalType, props, key]);
if (enabled) {
return null;
}
return h(originalType, { ...props, _freshPatched: true });
}
const oldVNodeHook = options.vnode;
options.vnode = (vnode) => {
assetHashingHook(vnode, BUILD_ID);
if (typeof vnode.type === "string") {
const originalType = vnode.type;
if (typeof originalType === "string") {
if (CLIENT_NAV_ATTR in vnode.props) {
const value = vnode.props[CLIENT_NAV_ATTR];
if (typeof value === "boolean") {
vnode.props[CLIENT_NAV_ATTR] = String(value);
}
}
}
const originalType = vnode.type;
if (typeof originalType === "string") {
switch (originalType) {
case "title":
case "meta":
case "link":
case "script":
case "style":
case "base":
case "noscript":
case "template":
// deno-lint-ignore no-constant-condition
if (false) {
// deno-lint-ignore no-explicit-any
} else if (!(vnode.props as any)._freshPatched) {
switch (originalType) {
case "title":
case "meta":
case "link":
case "script":
case "style":
case "base":
case "noscript":
case "template": {
// deno-lint-ignore no-explicit-any
vnode.type = (props: any) => {
useEffect(() => {
const text = renderToString(h(Fragment, null, props.children));
if (originalType === "title") {
document.title = text;
return;
}
let matched: HTMLElement | null = null;
if (vnode.key) {
matched = document.head.querySelector(
`head [data-key="${vnode.key}"]`,
) as HTMLElement ?? null;
}
if (matched === null && props.id) {
matched = document.head.querySelector(
`#${props.name}`,
) as HTMLElement ??
null;
}
if (matched === null) {
if (originalType === "meta") {
matched = document.head.querySelector(
`head [name="${props.name}"]`,
) as HTMLElement ?? null;
} else if (originalType === "base") {
matched = document.head.querySelector(originalType) ?? null;
}
}
if (matched === null) {
matched = document.createElement(originalType as string);
}
if (matched.textContent !== text) {
matched.textContent = text;
}
applyProps(props, matched);
}, []);
return null;
const v = vnode as VNode<any>;
const props = vnode.props;
const key = vnode.key;
v.type = WrappedHead;
v.props = {
originalType,
props,
key,
};
break;
}
break;
}
}
}
@@ -367,6 +367,8 @@ options[OptionsType.DIFF] = (vnode) => {
continue;
} else if (originalType === "meta" && key === "content") {
continue;
} else if (originalType === "link" && key === "href") {
continue;
}
cacheKey += `::${props[key]}`;
@@ -0,0 +1,22 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function DynamicMetaIsland() {
const [count, setCount] = useState(0);
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready" : ""}>
<Head>
<meta name="foo" content={`value-${count}`} />
</Head>
<button type="button" onClick={() => setCount((v) => v + 1)}>
update
</button>
</div>
);
}
@@ -0,0 +1,18 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function LinkIsland() {
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready" : ""}>
<Head>
<link rel="canonical" href="https://example.com/ok" />
</Head>
</div>
);
}
@@ -0,0 +1,19 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function MultiHeadA() {
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready-a" : ""}>
<Head>
<title>from island A</title>
<meta name="author" content="island-a" />
</Head>
</div>
);
}
@@ -0,0 +1,18 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function MultiHeadB() {
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready-b" : ""}>
<Head>
<meta name="description" content="from-island-b" />
</Head>
</div>
);
}
@@ -8,6 +8,7 @@ export default function Page({ Component }: PageProps) {
<title>not ok</title>
<meta name="foo" content="not ok" />
<meta name="bar" content="not ok" />
<link rel="canonical" href="https://example.com/not-ok" />
<style>not ok</style>
<style id="style-id">not ok</style>
<template key="a">not ok</template>
@@ -0,0 +1,5 @@
import { DynamicMetaIsland } from "../islands/DynamicMetaIsland.tsx";
export default function Page() {
return <DynamicMetaIsland />;
}
@@ -0,0 +1,5 @@
import { LinkIsland } from "../islands/LinkIsland.tsx";
export default function Page() {
return <LinkIsland />;
}
@@ -0,0 +1,11 @@
import { MultiHeadA } from "../islands/MultiHeadA.tsx";
import { MultiHeadB } from "../islands/MultiHeadB.tsx";
export default function Page() {
return (
<>
<MultiHeadA />
<MultiHeadB />
</>
);
}
+198 -56
View File
@@ -4,12 +4,17 @@ import {
buildProd,
parseHtml,
waitFor,
waitForText,
withBrowserApp,
} from "./test_utils.tsx";
import { expect } from "@std/expect";
import { FakeServer } from "../src/test_utils.ts";
import * as path from "@std/path";
const applyHeadCache = await buildProd({
root: path.join(import.meta.dirname!, "fixture_head"),
});
Deno.test("Head - ssr - updates title", async () => {
const handler = new App()
.appWrapper(({ Component }) => {
@@ -151,19 +156,45 @@ Deno.test("Head - ssr - merge keyed", async () => {
expect(last?.textContent).toEqual("ok");
});
Deno.test("Head - ssr - updates link", async () => {
const handler = new App()
.appWrapper(({ Component }) => {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="canonical" href="https://example.com/not-ok" />
</head>
<body>
<Component />
</body>
</html>
);
})
.get("/", (ctx) => {
return ctx.render(
<Head>
<link rel="canonical" href="https://example.com/ok" />
</Head>,
);
}).handler();
const server = new FakeServer(handler);
const res = await server.get("/");
const doc = parseHtml(await res.text());
const link = doc.querySelector("link[rel='canonical']") as HTMLLinkElement;
expect(link.href).toEqual("https://example.com/ok");
});
Deno.test({
ignore: true, // Temporarily until client perf is fixed
name: "Head - client - set title",
fn: async () => {
const applyCache = await buildProd({
root: path.join(import.meta.dirname!, "fixture_head"),
});
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyCache(app);
applyHeadCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/title`);
@@ -171,10 +202,7 @@ Deno.test({
await page.locator(".ready").wait();
await page.locator("button").click();
await waitFor(async () => {
const title = await page.evaluate(() => document.title);
return title === "Count: 1";
});
await waitForText(page, "title", "Count: 1");
});
},
sanitizeOps: false,
@@ -182,18 +210,13 @@ Deno.test({
});
Deno.test({
ignore: true, // Temporarily until client perf is fixed
name: "Head - client - match meta",
fn: async () => {
const applyCache = await buildProd({
root: path.join(import.meta.dirname!, "fixture_head"),
});
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyCache(app);
applyHeadCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/meta`);
@@ -210,15 +233,11 @@ Deno.test({
) => ({ name: el.name, content: el.content }));
});
try {
expect(metas).toEqual([
{ name: "foo", content: "ok" },
{ name: "bar", content: "not ok" },
]);
return true;
} catch {
return false;
}
expect(metas).toEqual([
{ name: "foo", content: "ok" },
{ name: "bar", content: "not ok" },
]);
return true;
});
});
},
@@ -227,18 +246,13 @@ Deno.test({
});
Deno.test({
ignore: true, // Temporarily until client perf is fixed
name: "Head - client - match style by id",
fn: async () => {
const applyCache = await buildProd({
root: path.join(import.meta.dirname!, "fixture_head"),
});
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyCache(app);
applyHeadCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/id`);
@@ -255,15 +269,11 @@ Deno.test({
) => ({ id: el.id, text: el.textContent }));
});
try {
expect(styles).toEqual([
{ id: "", text: "not ok" },
{ id: "style-id", text: "ok" },
]);
return true;
} catch {
return false;
}
expect(styles).toEqual([
{ id: "", text: "not ok" },
{ id: "style-id", text: "ok" },
]);
return true;
});
});
},
@@ -272,18 +282,13 @@ Deno.test({
});
Deno.test({
ignore: true, // Temporarily until client perf is fixed
name: "Head - client - match key",
fn: async () => {
const applyCache = await buildProd({
root: path.join(import.meta.dirname!, "fixture_head"),
});
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyCache(app);
applyHeadCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/key`);
@@ -303,19 +308,156 @@ Deno.test({
}));
});
try {
expect(tpls).toEqual([
{ key: "a", text: "ok" },
{ key: "b", text: "not ok" },
{ key: null, text: "not ok" },
]);
return true;
} catch {
return false;
}
expect(tpls).toEqual([
{ key: "a", text: "ok" },
{ key: "b", text: "not ok" },
{ key: null, text: "not ok" },
]);
return true;
});
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Head - client - dynamic meta update",
fn: async () => {
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyHeadCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/dynamic_meta`);
await page.locator(".ready").wait();
// Verify initial meta value
await waitFor(async () => {
const content = await page.evaluate(() => {
const el = document.querySelector(
"meta[name='foo']",
) as HTMLMetaElement;
return el?.content;
});
expect(content).toEqual("value-0");
return true;
});
// Click to update and verify meta changes reactively
await page.locator("button").click();
await waitFor(async () => {
const content = await page.evaluate(() => {
const el = document.querySelector(
"meta[name='foo']",
) as HTMLMetaElement;
return el?.content;
});
expect(content).toEqual("value-1");
return true;
});
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Head - client - link element",
fn: async () => {
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyHeadCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/link`);
await page.locator(".ready").wait();
await waitFor(async () => {
const href = await page.evaluate(() => {
const el = document.querySelector(
"link[rel='canonical']",
) as HTMLLinkElement;
return el?.href;
});
expect(href).toEqual("https://example.com/ok");
return true;
});
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Head - client - multiple islands with Head",
fn: async () => {
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyHeadCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/multi`);
await page.locator(".ready-a").wait();
await page.locator(".ready-b").wait();
await waitFor(async () => {
const title = await page.evaluate(() => document.title);
expect(title).toEqual("from island A");
return true;
});
await waitFor(async () => {
const metas = await page.evaluate(() => {
return {
author: (document.querySelector(
"meta[name='author']",
) as HTMLMetaElement)?.content,
description: (document.querySelector(
"meta[name='description']",
) as HTMLMetaElement)?.content,
};
});
expect(metas.author).toEqual("island-a");
expect(metas.description).toEqual("from-island-b");
return true;
});
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Head - client - title updates multiple times",
fn: async () => {
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyHeadCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/title`);
await page.locator(".ready").wait();
await page.locator("button").click();
await waitForText(page, "title", "Count: 1");
await page.locator("button").click();
await waitForText(page, "title", "Count: 2");
await page.locator("button").click();
await waitForText(page, "title", "Count: 3");
});
},
sanitizeOps: false,
sanitizeResources: false,
});
@@ -0,0 +1,23 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function HeadCounter() {
const [ready, setReady] = useState(false);
const [v, set] = useState(0);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready" : "not-ready"}>
<Head>
<title>Count: {v}</title>
</Head>
<p class="result">Count: {v}</p>
<button type="button" onClick={() => set((v) => v + 1)}>
update
</button>
</div>
);
}
@@ -0,0 +1,20 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function HeadMeta() {
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready" : "not-ready"}>
<Head>
<meta name="custom" content="ok" />
<meta name="custom-new" content="ok" />
</Head>
<h1>check meta</h1>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import type { PageProps } from "fresh";
export default function App({ Component }: PageProps) {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="custom" content="foo" />
</head>
<body>
<Component />
</body>
</html>
);
}
@@ -0,0 +1,5 @@
import { HeadCounter } from "../../islands/tests/HeadCounter.tsx";
export default function Page() {
return <HeadCounter />;
}
@@ -0,0 +1,5 @@
import { HeadMeta } from "../../islands/tests/HeadMeta.tsx";
export default function Page() {
return <HeadMeta />;
}
+28
View File
@@ -636,3 +636,31 @@ Deno.test({
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "vite build - client side <Head>",
fn: async () => {
await launchProd(
{ cwd: viteResult.tmp },
async (address) => {
await withBrowser(async (page) => {
await page.goto(`${address}/tests/head_counter`, {
waitUntil: "networkidle2",
});
await page.locator(".ready").wait();
await page.locator("button").click();
await waitForText(page, ".result", "Count: 1");
await waitFor(async () => {
const title = await page.evaluate(() => document.title);
expect(title).toEqual("Count: 1");
return true;
});
});
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
@@ -546,3 +546,47 @@ Deno.test({
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "vite dev - client side <Head>",
fn: async () => {
await withBrowser(async (page) => {
await page.goto(`${demoServer.address()}/tests/head_counter`, {
waitUntil: "networkidle2",
});
await page.locator(".ready").wait();
await page.locator("button").click();
await waitForText(page, ".result", "Count: 1");
await waitFor(async () => {
const title = await page.evaluate(() => document.title);
expect(title).toEqual("Count: 1");
return true;
});
await page.goto(`${demoServer.address()}/tests/head_meta`, {
waitUntil: "networkidle2",
});
await page.locator(".ready").wait();
await waitFor(async () => {
const custom = await page
.locator("meta[name='custom']")
// deno-lint-ignore no-explicit-any
.evaluate((el: any) => el.content);
expect(custom).toEqual("ok");
const custom2 = await page
.locator("meta[name='custom-new']")
// deno-lint-ignore no-explicit-any
.evaluate((el: any) => el.content);
expect(custom2).toEqual("ok");
return true;
});
});
},
sanitizeOps: false,
sanitizeResources: false,
});