# Islands and streaming

This page covers the parts of a page that do not follow the plain render-and-hydrate path: a document that streams, values that arrive later, components that hydrate late or never, parts that run only on the server, and pages that hydrate only their islands. [Rendering modes](/rendering-modes) lists every mode and how to set it.

## Streaming per adapter

A streamed render sends the document while the page still renders. The order is the head (with the import map), the body as the adapter writes it, the teleports, the payload script, the entry script, then one resolve script for each deferred value as it settles, then `</body></html>`. Status and headers are those set before the first body chunk. A `setResponseStatus`, a header or a redirect written after that is dropped, with a dev warning such as `setResponseStatus(404) after the response started streaming on /x; ignored`.

### The `stream` rule

`stream` is a route rule. Set it on a pattern in `routeRules`, or on one page in `meta.rules`. The merged rule of the path decides, and without one the adapter's default applies: every adapter streams except Vue.

```ts
routeRules: { "/report/**": { stream: false } }
```

There is no `meta.stream`. The scan refuses it and names the rule: `meta.stream in app/pages/feed.vue is not a page meta key; write meta.rules: { stream: true }`. A value that is not a boolean fails at load. The build warns once for a pattern that sets `stream: true` together with `prerender`, `swr` or `cache`, since such an answer is written or kept whole.

Vue sends a string unless a page opts in. This page streams:

````vue [rendering/vue/streamed.vue]
<script lang="ts">
import type { PageMeta } from "hamur/app"

export const meta = { rules: { stream: true } } satisfies PageMeta
</script>

<script setup lang="ts">
import { Await, useData } from "@hamur/adapter-vue"

const data = useData<{ title: string; reviews: Promise<string[]> }>()
</script>

<template>
  <main>
    <h1>{{ data.title }}</h1>
    <Await :resolve="data.reviews">
      <template #fallback><p>Loading reviews</p></template>
      <template #default="{ value }">
        <ul>
          <li v-for="text in value" :key="text">{{ text }}</li>
        </ul>
      </template>
      <template #error="{ error }"
        ><p>{{ error.message }}</p></template
      >
    </Await>
  </main>
</template>
````

The adapter holds Vue's web stream until its first chunk. A `setup` error in the shell answers the error page with its status; an error after the first chunk is logged, the stream ends, and the browser renders the error page after hydration. A streamed Vue page returns no teleports, since they are complete only when the stream ends.

### What is sent whole

These answers are sent whole whatever the rule says. The core reads the adapter's stream to its end and then writes the document, so the HTML holds every deferred value and a `useHead` call made late lands in `<head>`.

| Case                                                               | Why                                                                                                                        |
| ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| `HEAD`                                                             | no body is sent, so the headers must be final                                                                              |
| a path under `swr` or `cache`                                      | the cache keeps one finished answer                                                                                        |
| the prerender and `hamur generate`                                 | a file is written whole                                                                                                    |
| a request whose `user-agent` matches `app.htmlLimitedBots`         | the bot reads `<head>` once and runs no script                                                                             |
| a script-free page                                                 | the swap scripts of React and Solid are inline scripts                                                                     |
| a hash-mode CSP page                                               | each inline script's hash is recorded where it is written, so the document is buffered and holds no resolve or swap script |
| the answer of a form post that restores its fields, the error page | they are buffered                                                                                                          |
| an island page                                                     | the islands it rendered, with their chunks and stylesheets, are known only at the end                                      |

### HTML-limited bots

`app.htmlLimitedBots` is a `RegExp` or `false`. The default, [`HTML_LIMITED_BOTS`](/api-reference/server) from `hamur/server`, lists link-preview and indexing bots (`facebookexternalhit`, `Twitterbot`, `Slackbot`, `bingbot` and others). `Googlebot` is not in it: it runs scripts and reads a streamed document. `false` streams to every client. The config reaches the server bundle as JSON, so write the key as a `RegExp`; a value that is neither fails at load, and so does a pattern with the `g` or `y` flag. The pattern is tested once per request, before routing, so server routes and middleware read `event.context.htmlLimitedBot` too.

### Per adapter

| Adapter | Server render                                                                                                                                                                      | Default            |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| react   | `renderToReadableStream`; `Suspense` boundaries stream their fallback, then their content                                                                                          | streams            |
| preact  | `renderToReadableStream` of `preact-render-to-string/stream`; each suspended boundary is written when it settles, so boundaries arrive in the order they settle, not tree order    | streams            |
| vue     | `renderToWebStream` only where the rule says `stream: true`, else `renderToString`                                                                                                 | buffered           |
| svelte  | `svelte/server` has no streaming render, so the body is the string sent as one chunk; the page still takes the streamed path (bot buffering, dropped late writes, resolve scripts) | streams, one chunk |
| solid   | `renderToStream`                                                                                                                                                                   | streams            |
| html    | the page string, then the templates of its deferred parts                                                                                                                          | streams, one chunk |

**Svelte async SSR.** `experimental.svelteAsync: true` lets a component use `await` in its script or markup. `render` waits for Svelte's promise, and hydration waits for the same promises. Without the key such a component fails the build with Svelte's error followed by `Svelte async SSR is experimental: set experimental.svelteAsync: true`. The key fails at load in an app of another library. Under it `Await` renders the value in order and `fallback` is not shown, on the server or in a client navigation.

### Hooks on the answer

The server hook `render:stream` may return a replacement stream for the whole document of a streamed page (head, body, resolve scripts and close). `injectBefore(marker, html)` from `hamur/server` is the usual body of such a hook: it writes `html` before the first `marker`, finds a marker split across chunks and passes a stream without the marker through. `render:response` runs once for each page answer, document or error page, and may return a replacement `Response`; it never runs for a server route, a handler call or a `/_hamur/*` endpoint. The app hook `app:rendered` runs after the adapter render and before the document is joined, and has no `html` for a stream. See [`injectBefore`](/api-reference/server).

## Deferred values

A deferred value is a promise that is a top-level value of the object a `load` returns. The page renders without waiting for it, and the value reaches the browser later in the same answer.

````ts [rendering/app/pages/streamed.load.ts]
const fetchReviews = (): Promise<string[]> =>
  new Promise((resolve) => setTimeout(() => resolve(["Bright", "Sturdy"]), 300))

export function load() {
  return { title: "Lamp", reviews: fetchReviews() }
}
````

A promise anywhere else, nested or in an array or in the answer of a handler, is an error: `Cannot serialize a Promise at payload.data.<route>.a.b`. `useData` types a top-level `Promise<V>` as a promise. After a client navigation `load` runs in the browser and its promise is the deferred value, so there is no second request.

### Reading one: `Await` and `useDeferred`

`Await` takes the promise, a `fallback` shown while it is pending and an `error` render for a rejection. The form follows the library:

````tsx [rendering/app/pages/streamed.tsx]
import { Await, useData } from "@hamur/adapter-react"

export default function Streamed() {
  const { title, reviews } = useData<{ title: string; reviews: Promise<string[]> }>()
  return (
    <main>
      <h1>{title}</h1>
      <Await resolve={reviews} fallback={<p>Loading reviews</p>} error={(error) => <p>{error.message}</p>}>
        {(list) => (
          <ul>
            {list.map((text) => (
              <li key={text}>{text}</li>
            ))}
          </ul>
        )}
      </Await>
    </main>
  )
}
````

Solid takes the same props. Preact is the same code as React, imported from `@hamur/adapter-preact`.

````tsx [rendering/solid/streamed.tsx]
import { Await, useData } from "@hamur/adapter-solid"

export default function Streamed() {
  const data = useData<{ title: string; reviews: Promise<string[]> }>()
  return (
    <main>
      <h1>{data().title}</h1>
      <Await resolve={data().reviews} fallback={<p>Loading reviews</p>} error={(error) => <p>{error.message}</p>}>
        {(list) => (
          <ul>
            {list.map((text) => (
              <li>{text}</li>
            ))}
          </ul>
        )}
      </Await>
    </main>
  )
}
````

Svelte takes snippets named `children`, `fallback` and `error`:

````svelte [rendering/svelte/streamed.svelte]
<script lang="ts">
  import { Await, useData } from "@hamur/adapter-svelte"

  const data = useData<{ title: string; reviews: Promise<string[]> }>()
</script>

<main>
  <h1>{data.value.title}</h1>
  <Await resolve={data.value.reviews}>
    {#snippet fallback()}<p>Loading reviews</p>{/snippet}
    {#snippet children(list)}
      <ul>
        {#each list as text (text)}
          <li>{text}</li>
        {/each}
      </ul>
    {/snippet}
    {#snippet error(error)}<p>{error.message}</p>{/snippet}
  </Await>
</main>
````

Angular has no `Await`. `injectDeferred(promise)` returns a `Resource`, and the template reads it with `@if (value.hasValue())`, `@else if (value.error())` and `@else`. The adapter renders a string, so the server waits for the value and the fallback is never in the HTML:

````ts [angular/streamed.ts]
import { Component } from "@angular/core"
import { injectData, injectDeferred } from "@hamur/adapter-angular"
import type { PageMeta } from "hamur/app"

export const meta = { rules: { stream: true } } satisfies PageMeta

@Component({
  template: `<main>
    <h1>{{ data().title }}</h1>
    @if (reviews.hasValue()) {
      <ul>
        @for (text of reviews.value(); track text) {
          <li>{{ text }}</li>
        }
      </ul>
    } @else if (reviews.error()) {
      <p>{{ reviews.error()?.message }}</p>
    } @else {
      <p>Loading reviews</p>
    }
  </main>`,
})
export default class Reviews {
  readonly data = injectData<{ title: string; reviews: Promise<string[]> }>()
  readonly reviews = injectDeferred(this.data().reviews)
}
````

html has no components, so `Await` is a function that returns a string, and a pending value becomes a placeholder:

````ts [rendering/html/streamed.ts]
import { Await, useData } from "@hamur/adapter-html"

const escape = (value: unknown) => String(value).replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`)

export default function Streamed(): string {
  const { title, reviews } = useData<{ title: string; reviews: Promise<string[]> }>()
  const list = Await(reviews, {
    fallback: "<p>Loading reviews</p>",
    then: (items) => `<ul>${items.map((text) => `<li>${escape(text)}</li>`).join("")}</ul>`,
    error: (error) => `<p>${escape(error.message)}</p>`,
  })
  return `<main><h1>${escape(title)}</h1>${list}</main>`
}
````

Vue takes the slots `default({ value })`, `fallback` and `error({ error })`, as the sample above shows.

| Adapter | `Await`                                                                     | `useDeferred(promise)`                                                   |
| ------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| react   | `<Await resolve fallback error?>{(value) => …}</Await>`                     | `use(promise)`, inside a `Suspense`                                      |
| preact  | the same props                                                              | the value, throwing the promise while it is pending                      |
| vue     | `<Await :resolve>` with slots                                               | `await useDeferred(p)` in an async `<script setup>`, inside a `Suspense` |
| svelte  | `<Await {resolve}>` with snippets                                           | a getter object `{ current, error, pending }`                            |
| solid   | `<Await resolve fallback error?>{(value) => …}</Await>`                     | an accessor of the value                                                 |
| angular | not exported: `@if (value.hasValue()) … @else if (value.error()) … @else …` | `injectDeferred(promise)`, a `Resource` of the value                     |
| html    | `Await(promise, { fallback, then, error? }): string`                        | not exported: an html page renders synchronously                         |

A rejected value renders `error`. With no `error` the rejection is thrown into the nearest `ErrorBoundary`. It never shows the error page and never changes the status. An `Await` whose `resolve` is not a promise renders the value as fulfilled.

On a streamed render the fallback is in the HTML and the value follows in a script: React and Solid swap their own boundaries, Preact streams the content when it settles, and html writes `<hamur-defer>` with the fallback and sends `<template>` and a swap script after it. In html, with JavaScript off, the HTML keeps the fallback and the template. Vue and Svelte differ, as the table of [Rendering modes](/rendering-modes#what-each-adapter-supports) shows: Vue waits in order, and Svelte writes the fallback in the HTML and renders the value in the browser when its script arrives, unless `experimental.svelteAsync` is on.

### Timeouts and errors

`app.streamTimeout` (default `10000` milliseconds, a positive integer) is how long a deferred value may stay pending after the render started. After that it is rejected with a 504 `Deferred value timed out`, its script is written, and the stream closes once nothing else is pending. A rejection is masked like a loader error: the browser sees `createError` messages and nothing else, and the original is logged. The status of the answer never changes for a deferred value.

A render that is sent whole, a script-free page and any adapter whose rule says `stream: false` wait for every deferred value, up to the same timeout, before the adapter renders. There the promises are settled, so every `Await` renders its value in place and no resolve script is written. The prerender writes the settled values into `_payload.json`.

### `blocking = false`

A load file that exports `blocking = false` does not delay the render. Its whole result is one deferred value: `useData()` returns a promise of it, which you read with `Await` or `useDeferred`.

````ts [rendering/app/pages/stats.load.ts]
export const blocking = false

export async function load() {
  await new Promise((resolve) => setTimeout(resolve, 300))
  return { visits: 1024 }
}
````

````tsx [rendering/app/pages/stats.tsx]
import { Await, useData } from "@hamur/adapter-react"

export default function Stats() {
  const stats = useData<Promise<{ visits: number }>>()
  return (
    <main>
      <h1>Stats</h1>
      <Await resolve={stats} fallback={<p>Counting</p>}>
        {({ visits }) => <p>{`${visits} visits`}</p>}
      </Await>
    </main>
  )
}
````

The scan reads the export from the source and needs the literal `false`: `blocking in app/pages/stats.load.ts must be the literal false`. Such a load cannot redirect or set the status or a header, since the answer may have started: `redirect()`, `setResponseStatus` and a header write from it are dropped, with a dev line `load of app/pages/stats.load.ts has blocking = false and cannot redirect or set the status`, and the page answers 200. A thrown error is a rejection of the deferred value. Its `head` export does not run, a file that also exports `headers` fails the scan, and a dependency the load records after its first `await` is not in the payload, so `refresh(key)` of it does not re-run the route until a client navigation ran it.

## Lazy hydration

A lazy component renders on the server as usual and hydrates in the browser only when its trigger fires. Until then its chunk is not requested and the server HTML stays as it is. After a client navigation it mounts at once.

````tsx [rendering/app/components/Comments.tsx]
export default function Comments({ postId }: { postId: string }) {
  return <section>{`Comments of post ${postId}`}</section>
}
````

````tsx [rendering/app/pages/lazy.tsx]
import { defineLazyHydrationComponent } from "@hamur/adapter-react"

const Comments = defineLazyHydrationComponent("visible", () => import("../components/Comments"), {
  rootMargin: "200px",
})

export default function Lazy() {
  return (
    <main>
      <h1>A post</h1>
      <Comments postId="42" onHydrated={() => console.log("comments hydrated")} />
    </main>
  )
}
````

`defineLazyHydrationComponent(on, loader, options?)` is exported by every adapter. The loader is a dynamic import, so the component is its own chunk. The returned component takes the props of the wrapped one and `onHydrated`, called once after it hydrated or mounted.

| Trigger         | Fires                                                                                                  | Options                  |
| --------------- | ------------------------------------------------------------------------------------------------------ | ------------------------ |
| `"load"`        | at once, after the app hydrated                                                                        |                          |
| `"idle"`        | `requestIdleCallback`, else a 200 ms timer                                                             | `timeout` (default 2000) |
| `"visible"`     | `IntersectionObserver` on the first element child                                                      | `rootMargin`             |
| `"interaction"` | the first of `pointerenter`, `focusin` and `click`; a `click` is replayed once on the hydrated element | `events`                 |
| `{ media }`     | `matchMedia(media)` matches, now or on change                                                          |                          |
| `{ time }`      | a timer of that many milliseconds                                                                      |                          |
| `"never"`       | never                                                                                                  |                          |

An unknown trigger throws `TypeError: defineLazyHydrationComponent: unknown trigger "hover"; use load, idle, visible, interaction, never, { media } or { time }`. `useAsyncData` and `useFetch` called under a `"never"` component leave their entries out of the payload, since nothing in the browser reads them; a key that is used both inside and outside such a component stays, with a dev log.

Per adapter:

- **react, preact.** The part sits in a `Suspense` that waits for the trigger, so the server HTML of the boundary stays until then. Preact keeps only the first DOM node of a suspended child, so write a lazy part with one root element.
- **vue.** A `defineAsyncComponent` whose loader waits for the trigger, so every trigger behaves alike.
- **svelte.** Write the definition in `<script module>`, not in the instance script, which would start a new load on every pass. A nested `<svelte:head>` of the part is dropped.
- **solid.** The wrapper keeps the hydration context of its position and creates the child when the trigger fires. After Solid's first delegated event the child is created fresh and replaces the server nodes.
- **html.** There are no client components: `on` is ignored and the children render in place.

## Server-only components and pages

### Server-only components

A file `app/components/**/<Name>.server.<ext>` is a server-only component. It renders to HTML on the server and never hydrates, and neither it nor its imports are in the client build. The name is the component name of the path without `.server`: `app/components/code/Highlight.server.tsx` is `CodeHighlight`.

````tsx [rendering/app/components/Highlight.server.tsx]
export default function Highlight({ code, lang }: { code: string; lang: string }) {
  return (
    <pre data-lang={lang}>
      <code>{code}</code>
    </pre>
  )
}
````

````tsx [rendering/app/pages/snippet.tsx]
import Highlight from "../components/Highlight.server"

export default function Snippet() {
  return <Highlight code="const answer = 42;" lang="ts" />
}
````

The server renders it inside `<hamur-component name uid>`, and the browser keeps that HTML as it is. When a client render needs it anew, after a client navigation or with changed props, the wrapper requests `GET /_hamur/components/<Name>?props=<serialized>` and renders the answer `{ html, css, head? }`. A props text over 2048 bytes is sent as a `POST` body.

- **Props** go through the payload serializer on the server render too, so a prop that would fail in the browser fails on the first render: `Prop "onClick" of Highlight.server cannot be serialized`. An optional `propsSchema` export (a Standard Schema) validates them, and the endpoint answers 400 `Invalid props for server-only component Highlight`. Without it any serializable props pass. An unknown name answers 404; asked by a tab of another build (its `x-hamur-build` names another build id), it answers 409 `{"reload":true}` and the tab reloads the page once, so a deploy that removed the component sends that tab to the new build instead of an error.
- **No children.** A child or slot passed to a server-only component fails the render: `Highlight.server takes no children; pass data as props`.
- **The endpoint is public.** Anyone may call `/_hamur/components/<Name>` with any props. Server middleware and the route rules of the path run (`swr`, `cache`, `headers`, `rateLimit`, `basicAuth`); page and route middleware do not. A component that shows one visitor's data authorizes itself from the request, in the handler it reads through: the first line of that handler is `const { user } = await requireUserSession(event)` from `@hamur/auth/server` (or `useSession(event)` of `hamur/server`), and it answers only data of `user`. See [Sessions and security](/sessions-and-security).
- **It is not a door to server code.** The import guard of the client build runs over its imports in the server build too: `hamur/server`, `server/`, `node:*` and `bun:*` fail with `<file> is server-only (<reason>) and cannot be imported from a server-only component: <chain>`.
- **Not built.** A server-only component's own stylesheets reach no page yet: `css` is always empty.

### Server-only pages

`meta.serverOnly: true` makes a page that renders on the server only. The page's component and imports are not in the client build; the layouts and the app root still hydrate, and the page's markup stays as the server wrote it.

````tsx [rendering/app/pages/terms.tsx]
import type { PageMeta } from "hamur/app"

export const meta = { serverOnly: true } satisfies PageMeta

export default function Terms() {
  return (
    <article>
      <h1>Terms</h1>
      <p>This page is rendered on the server and never hydrated.</p>
    </article>
  )
}
````

A client navigation to it fetches the target URL as a document (`GET <href>` with `accept: text/html`) and takes the page's markup from it, so server middleware, route rules, route middleware and the page's `load` run exactly as on a reload. It adds no endpoint. Layout state survives, and a prerendered server-only page works on `static`.

The scan asks for what the build must read: the whole `meta` is a literal object, so middleware is named; the file exports only its component and `meta`; `meta.ssr` is not `false` or `"data-only"`; the page has no child routes, slots or intercepting folder; and `meta.serverOnly` is the literal `true`. It cannot be combined with `meta.hydrate: "islands"`, since an island page already renders on the server only. Limits: the page's own head (a `useHead` in the page, the `head` of its load) is not applied on a client navigation, `meta.head` is, and `refresh()` re-runs the layout loads but keeps the page's markup until the next navigation to it.

### Why there is no React Server Components mode

`@hamur/adapter-react` has no RSC mode: no `"use client"` boundary, no Flight payload, no server component tree. Server-only components, server-only pages and server islands give the same results in all six adapters with one contract: server code and its dependencies stay out of the browser, and personal parts live in cached pages. A page you write for React and a page you write for Vue move between adapters the same way.

## Islands

An island page renders on the server like any page, but its document carries no app entry. It ships the island runtime and the chunks of the islands it rendered, nothing else. An island is a component from `app/islands/` that the page renders through `Island`; it hydrates on its own, as its own root. Turn it on with `experimental.islands: true`; without the key a page with `meta.hydrate` fails the build, and so does a file in `app/server-islands/`.

````tsx [rendering/app/islands/Counter.tsx]
import { useState } from "react"

export default function Counter({ start }: { start: number }) {
  const [count, setCount] = useState(start)
  return (
    <button type="button" onClick={() => setCount(count + 1)}>
      {`Likes ${count}`}
    </button>
  )
}
````

````tsx [rendering/app/pages/post.tsx]
import { Island } from "@hamur/adapter-react"
import type { PageMeta } from "hamur/app"
import Counter from "../islands/Counter"

export const meta = { hydrate: "islands" } satisfies PageMeta

export default function Post() {
  return (
    <article>
      <h1>A post</h1>
      <p>Only the button below ships JavaScript.</p>
      <Island component={Counter} props={{ start: 2 }} on="visible" />
    </article>
  )
}
````

`meta.hydrate` is the literal `"full"` (the default) or `"islands"`; the build reads it to leave the page and its layouts out of the client build. The document has the import map, a payload script `{ route, state, config, islands: true }` with no `data`, and a module script for the runtime, only when the page rendered at least one island. It is buffered, not streamed.

- **Navigation** from or to an island page is a document load, unless a [swap](#swaps-and-partials) takes it.
- **Inside an island,** `useRoute`, `useState`, `useHead` and `useRuntimeConfig` read the frozen route, state and config of the payload, `useData` reads `null`, `Link` takes a path only, and `useRouter().navigate` throws. A `useHead` change after hydration applies to the document head.
- **Props** go through the payload serializer, attribute-escaped. A function prop fails the render: `Island prop "onClick" of Counter cannot be serialized`.
- **Rendering** is by the page's adapter, with the island as a root of its own. The page must render its server HTML: `meta.ssr` or `ssr` other than `true`, or a rule with `ssr: false` or `"data-only"`, fails the build.
- **Errors.** `Island` on a fully hydrated page fails the render: `Island Counter on a fully hydrated page: use defineLazyHydrationComponent for a component that hydrates later, or set meta.hydrate: "islands"`. A component that is not from `app/islands/` fails it too.
- **`hamur dev`** serves one HTML shell, so an island page there shows its islands' server HTML and warns once that island pages do not hydrate under dev.

### Directives

`on` says when an island hydrates. It takes any trigger of [Lazy hydration](#lazy-hydration) except `"never"` (it fails: `Island Counter has on="never", which ships no code; render the component without Island`), the default `"load"`, and `"only"`, which renders `fallback` on the server and mounts the island in the browser alone. Each directive is a small module loaded only on a page that uses it, and an island whose every use waits for a directive requests its code only when the directive fires.

A module can add a directive with `addIslandDirective({ name, entry })` from `hamur/kit`; `entry` default-exports `(load, options, el) => void` and calls `load()` when it decides. Then `on="hover"` or `on={{ hover: options }}` works and typegen adds the name to the type. A built-in name fails: `Island directive "idle" is built in`. An unknown name fails the render: `Island Counter has on="hover", which no module adds`. See [`addIslandDirective`](/api-reference/kit).

### State, children and persisted islands

The islands of one page share one state store, made from the payload's `state`: `useState("count", 0)` in two islands reads one value, and a change in one shows in the other (islands of the same library).

An island's children are rendered by the page on the server only, written inside `<hamur-slot>`, and given to the island where it renders its children. They are never hydrated or rendered again, and they are not in the island's chunk or its props. `on="only"` with children fails, since there is no server HTML to hold them.

`persist="player"` names an island across swaps: a swap to a page with the same id keeps its element and its state, so an `<audio>` keeps playing. With `persistProps` the island keeps its old props too; without it a changed `props` attribute reaches the island through `updateIsland`, where the adapter has one. Two islands with one `persist` id fail the render: `Island persist id "player" is used twice`.

### html islands and second-library islands

An html page has no components. Its island is a file `app/islands/<name>.ts` that default-exports `defineIsland({ render(props): string, hydrate(el, props), update? })` from `@hamur/adapter-html`; `hydrate` may return a cleanup. The page writes `island(Counter, props, { on })` with the imported value. An html island reads no route or state: it takes props only.

An html app may also host islands of another library. `experimental.islands: { libraries: ["react", "svelte"] }` makes the files of `app/islands/` with those libraries' extensions islands rendered and hydrated by that adapter. The page still writes `island(component, props, { on })`, and only a page that uses a library's island loads its runtime. The key fails at load in any other adapter, for a library that is not installed, and for two libraries that share an extension (`react` and `preact`, `react` and `solid`, `preact` and `solid` are each refused together). A component an island imports must live under `app/islands/` too, where it is an island of its own.

## Server islands

A server island is a component in `app/server-islands/` that renders only on the server, in its own request after the page arrived. A cached or prerendered page can hold a personal or slow part this way. It needs `experimental.islands`; without it the scan fails: `app/server-islands/Cart.tsx needs experimental.islands`.

````tsx [rendering/app/server-islands/Cart.tsx]
import { useCookie } from "@hamur/adapter-react"

export default function Cart() {
  const [items] = useCookie<string>("cart-items")
  return <p>{`${items ?? 0} items in your cart`}</p>
}
````

````tsx [rendering/app/pages/shop.tsx]
import { ServerIsland } from "@hamur/adapter-react"
import type { PageMeta } from "hamur/app"

export const meta = { rules: { swr: 60 } } satisfies PageMeta

export default function Shop() {
  return (
    <main>
      <h1>Shop</h1>
      <ServerIsland name="Cart" fallback={<p>Loading your cart</p>} />
    </main>
  )
}
````

Every component adapter exports `ServerIsland` (`name`, `props?`, `fallback?`), and html has `serverIsland(name, props, { fallback })`. The name is the component name of the path. It works in island pages and in fully hydrated pages.

1. The page writes `<hamur-server-island name="Cart" uid="s0" p="…">` around the fallback. `p` is the props sealed with the **app key** `HAMUR_KEY`, bound to the island's name and to the build, so the props are not readable in the page. Without props there is no `p`.
2. After `DOMContentLoaded` the browser requests `GET /_hamur/islands/Cart?p=…` (a `POST` over 2048 bytes) and swaps the answer `{ html, css, head? }` into the element. The library never hydrates or renders it again, and no hydration warning shows.
3. Set `HAMUR_KEY` in production, with the same value on every instance and at build. After a new build an old page's `p` no longer opens: a tab of the old build reloads the page (see Answers below), a request without `x-hamur-build` gets 400 and keeps its fallback, and a prerendered page is written again by the build. See [Sessions and security](/sessions-and-security).

The endpoint runs server middleware and the route rules of `/_hamur/islands/<name>` (`swr`, `cache`, `headers`, `rateLimit`, `basicAuth`, `ipRestriction`, `bodyLimit`, `timeout`), and may set cookies. Page and route middleware, `validate` and the page's loaders do not run, since the request names no page. A `p` proves only that this server rendered this island with these props in this build; anyone who has the page's HTML can replay it. An island that shows one visitor's data authorizes itself from the request, as a server-only component does.

- **Caching.** Under `swr` or `cache` a `GET` is kept by island name and the opened props, not by the URL, since every render seals anew. The cached render has no cookie and no `authorization`, and an answer that sets a cookie or says `private` or `no-store` is never kept. A cache rule makes an island the same for everyone.
- **Props a browser sends.** On a client navigation to a fully hydrated page there is no server to seal the props, so the wrapper sends them in the clear as `props=`. The endpoint takes them only when the island exports a `propsSchema`, and answers 400 `Server island Cart takes sealed props only; export propsSchema to accept props a browser sends` otherwise. An island without props needs neither.
- **Answers.** 400 `Invalid server island props` for a `p` that does not open, 404 `Unknown server island Cart`, and the island's own masked error status for a throw. To a tab of another build (its `x-hamur-build` names another build id), an unknown name or a `p` that does not open answers 409 `{"reload":true}` with the server's `x-hamur-build` instead, and the tab reloads the page once through `reloadApp`; an island the server still has runs as usual. `hamur dev` never answers it.
- **Prerender.** A prerendered page may hold server islands and they stay dynamic. On `static` the build fails: `Server islands need a server preset (page /x uses Cart)`.
- **Limits.** A server island's own stylesheets reach no page yet. Under `hamur dev` island pages do not hydrate, so their server islands keep the fallback. An html page that repaints needs a `propsSchema` on an island that takes props.

In [partial prerendering](/rendering-modes#partial-prerendering) a server island is rendered in the same answer as the shell, with no second request.

## Swaps and partials

An island page navigates by document loads. A link inside an element with `data-hamur-swap` swaps instead: the browser fetches the target document and updates the page in place, with no document load. It is for island pages only: fully hydrated pages have the navigator, and script-free pages have no script.

```html
<nav data-hamur-swap><a href="/docs/a">A</a> <a href="/docs/b">B</a></nav>
<hamur-partial name="main"> … </hamur-partial>
```

When both documents have `<hamur-partial name>` regions with the same names, only those regions are replaced; otherwise `<body>` is. The head is merged, and an island whose `persist` id the new document also has keeps its element. A name that two partials of a page carry is no region, so a swap from or to that page replaces `<body>`, and `hamur dev` logs `Partial name "main" is used twice; swaps replace the body`. Components write `hamur-partial` as a plain element; html writes the string.

A link swaps only for a primary click without a modifier on a same-origin `a[href]`, not `download`, `data-hamur-reload`, `rel="external"` or another `target`. A redirect, a status outside 2xx, an answer that is not HTML or a network error ends in a full load of the link, so a swap is never worse than a link. The scripts of the new document do not run: a page that needs code on arrival uses an island. History, scroll, focus and `data-hamur-view-transition` follow the navigator's rules.

## Client-only parts and hydration helpers

- **`ClientOnly`** renders `fallback` on the server and in the hydration render, and its children after mount. In html it takes a function, `ClientOnly(() => html, { fallback })`, which writes the fallback and a template the client swaps in. A script-free page keeps the fallback.
- **Client-only components.** A file `app/components/**/<Name>.client.<ext>` in react, preact, vue, svelte or solid is a component that renders only in the browser. Import it by its path like any component. On the server the import renders nothing, and the browser loads the file's own chunk after mount and renders it then, so the file and its imports are in no other chunk and never in the server build. For a placeholder, put it in `ClientOnly`: the `fallback` stays while the chunk loads. A client-only component exports only its default; a named export fails the build. A `ref` reaches the loaded component in react, preact and vue (`defineExpose` members); svelte's `bind:` does not pass through. A `.client` and a `.server` file of one name fail the scan: `Component Map is defined twice: app/components/Map.client.vue and app/components/Map.server.vue`. html has no such file; use `ClientOnly` or an island.

````tsx [rendering/app/pages/map.tsx]
import { ClientOnly } from "@hamur/adapter-react"
import Map from "../components/Map.client"

export default function Place() {
  return (
    <ClientOnly fallback={<p>Loading the map</p>}>
      <Map city="Izmir" />
    </ClientOnly>
  )
}
````

- **`DevOnly`** renders its children under `import.meta.dev` and `fallback` otherwise. A production build removes the children's code, so the output holds none of their strings.
- **`ClientFallback`** renders `fallback` when its children throw during the server render, and the browser renders the children fresh instead of hydrating them. The error goes to `onSsrError` and to the `error` hook with `handled: true`, and the page answers 200. `keepFallback` keeps the fallback until the children rendered; svelte accepts it and ignores it. It is not exported in html.

````tsx [rendering/app/components/Widgets.tsx]
import { ClientFallback, ClientOnly, DevOnly, useHydrated, useId } from "@hamur/adapter-react"

function MapView() {
  if (typeof window === "undefined") throw new Error("The map needs a browser")
  return <div id="map" />
}

export default function Widgets() {
  const hydrated = useHydrated()
  const id = useId()
  return (
    <section>
      <label htmlFor={id}>Search</label>
      <input id={id} disabled={!hydrated} />
      <ClientOnly fallback={<span>Loading chart</span>}>
        <canvas />
      </ClientOnly>
      <DevOnly>
        <pre>debug panel</pre>
      </DevOnly>
      <ClientFallback fallback={<p>The map shows after the page loads</p>}>
        <MapView />
      </ClientFallback>
    </section>
  )
}
````

- **`onPrehydrate(fn)`** runs `fn(el)` as an inline script before hydration, with the first element of the component. It returns an id that the component writes as `data-hamur-p` on its first element. The script carries the request's nonce, or its hash in hash mode. `fn` runs as a standalone script, so it must not read a variable from its closure; in dev that is an error naming the variable. In the browser the hook does nothing and returns `undefined`.

````tsx [rendering/app/components/ThemeBox.tsx]
import { onPrehydrate } from "@hamur/adapter-react"

export default function ThemeBox() {
  const mark = onPrehydrate((element) => {
    element.classList.add(localStorage.getItem("theme") === "dark" ? "dark" : "light")
  })
  return <div data-hamur-p={mark}>Themed content</div>
}
````

For a script in `<head>`, such as a theme class on `<html>` before the first paint, give `useHead` a script whose `innerHTML` is a function; it is written as `(<source>)()` with the same check. `hydrationSafe: ["class", "data-theme"]` on `htmlAttrs` or `bodyAttrs` keeps the attributes as the script set them. A script-free page writes neither script.

- **`useHydrated()`** is `false` on the server and in the hydration render and `true` after the app mounted. A component mounted after a client navigation gets `true` at once. It is a boolean in react and preact, a `Ref` in vue, `{ current }` in svelte, an accessor in solid and a function in html.
- **`useId()`** gives an id that is the same on the server and in hydration. React, preact and vue re-export the library's own; solid wraps `createUniqueId`; svelte and html give `s-<n>` in render order. Two calls in one component give two ids. In svelte and html it throws outside a Hamur app.
