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.