# rshono — full documentation

> rshono is a minimalist web framework built on Hono, Rspack and React Server Components. One required file (src/routes.ts), one optional file (src/server.ts), and you get a dev server with HMR, streaming SSR with RSC hydration, server actions with progressive enhancement, soft navigation, build-time prerendering, and hard env/secret safety.

## Optional

- [Hono llms.txt](https://hono.dev/llms.txt): The server rshono runs on — `src/server.ts` is a Hono app, and an endpoint handler is a Hono handler.
- [Rspack llms.txt](https://rspack.rs/llms.txt): The bundler behind `rshono dev` and `rshono build`. rshono writes the config; the `rspack` hook extends it.
- [React llms.txt](https://react.dev/llms.txt): Server and client components, hooks, and the rest of the model pages are written in.

---

<!-- source: https://www.rshono.com/docs/getting-started.md -->

---
title: Getting started
description: Scaffold an app, run the dev server, ship a production build.
---

rshono is a web framework built on [Hono](https://hono.dev), [Rspack](https://rspack.rs) and
[React Server Components](https://react.dev/reference/rsc/server-components). One required file
(`src/routes.ts`), one optional file (`src/server.ts`), nine exported values.

> **Alpha.** Built on Rspack's experimental RSC support (`rspack.experiments.rsc`) and
> `react-server-dom-rspack`, which has not reached 1.0. Both are pinned to exact versions, so a release of
> rshono is what moves them.

## Scaffold

```bash
npx @rshono/create@latest my-app
```

The runner you use is the package manager the project gets — read from `npm_config_user_agent`, written
into `packageManager`, and used for the install. `--pm npm|pnpm|yarn|bun` overrides the guess.

The scaffolder asks for a deploy target, a styling choice and a formatter/linter preset. Every question
is also a flag, and a non-interactive terminal implies `--yes`:

```bash
npx @rshono/create@latest my-app -y --deploy cloudflare --tailwind --quality biome
```

## Commands

```bash
rshono dev     # dev server with HMR (default port 3000)
rshono build   # production build: client + server bundles + prerendered pages
rshono start   # run the production build
```

`rshono dev` always runs the Node dev server, whatever deploy target you picked. The target is a
property of the build, not of developing.

## Requirements

- **Node ≥ 22.18** — worker threads, `process.loadEnvFile`, `Promise.withResolvers`, `URL.parse`, and
  native TypeScript stripping, so a `.ts` config needs no loader.
- **React ≥ 19.1** — the floor `react-server-dom-rspack` requires.

## Next

- [Project layout](/docs/project-layout) — what the framework knows about.
- [Routing](/docs/routing) — the one required file.
- [Pages](/docs/pages) — how a server component becomes a page.
- [API reference](/docs/api) — every export.

---

<!-- source: https://www.rshono.com/docs/project-layout.md -->

---
title: Project layout
description: The two files the framework knows about — everything else is yours to arrange.
---

```
rshono.config.ts   optional — every field has a default
public/            optional — served verbatim at the web root
src/
  routes.ts        required — the route table
  server.ts        optional — a Hono sub-app mounted ahead of the page routes
  …                everything else is yours to arrange
```

Only those two files under `src/` mean anything to the framework. No convention is attached to any other
name or directory: no `pages/`, no `app/`, no `*.server.ts`. Arrange `src/` by domain, by feature, by
team — routes are one explicit array, so moving a page is an edit to one line.

## Path aliases

`@/…` resolves to `src/…` in both compilers. Tell TypeScript the same thing — relative, and with no
`baseUrl`, which TypeScript 7 removed:

```json
{ "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }
```

## What the build produces

| Output                 | Contents                                                                                        |
| ---------------------- | ----------------------------------------------------------------------------------------------- |
| `dist/static`          | Hydration runtime, `'use client'` chunks, CSS. Served under `/_static`, cached immutably.       |
| `dist/server/main.mjs` | The app server, self-contained.                                                                 |
| Prerendered pages      | A document and a flight payload per [`render: 'static'`](/docs/routing#static-rendering) route. |
| A copy of `public/`    | So a deployed build needs nothing beside it.                                                    |

Where those land, and what the entry's default export looks like, depends on the
[deploy target](/docs/deployment).

---

<!-- source: https://www.rshono.com/docs/routing.md -->

---
title: Routing
description: src/routes.ts — the one file rshono requires, and the only place routes are declared.
---

Routes are an explicit table, not a directory scan. One file lists every page and endpoint, matched in
order.

```ts
import { defineRoutes } from '@rshono/core';

export const routes = defineRoutes({
  routes: [
    { path: '/', component: () => import('./components/home') },
    { path: '/profile/:id', component: () => import('./components/profile') },
    {
      path: '/docs/:slug',
      render: 'static',
      component: () => import('./components/documentation'),
      staticPaths: async () => [{ slug: 'getting-started' }, { slug: 'deployment' }],
    },
    { type: 'endpoint', path: '/api/health', server: () => import('./health') },
  ],
  notFound: { component: () => import('./components/404') },
  error: { component: () => import('./components/500') },
});
```

`routes.ts` only ever runs on the server, so importing server-only modules from it — inside
`staticPaths`, say — is safe. A plain array is shorthand when there are no `notFound` / `error` pages:

```ts
export const routes = defineRoutes([{ path: '/', component: () => import('./components/home') }]);
```

## Paths

Paths use Hono's syntax: `:id`, `:id{[0-9]+}` and `*` all work.

`PageProps<'/users/:id/posts/:postId'>` turns that literal into `{ id: string; postId: string }`, and
`defineRoutes` checks each page's props against the path it is mounted at. Out of step, and the
`component` field errors with `component props are not satisfied by PageProps<'/…'>` — at the route
definition, not at runtime.

## Page routes

`type` can be omitted; `'page'` is the default.

| Field         | Meaning                                                                             |
| ------------- | ----------------------------------------------------------------------------------- |
| `path`        | Hono-style pattern, e.g. `/`, `/profile/:id`, `/files/*`.                           |
| `component`   | Dynamic import of the page module; its default export is the page.                  |
| `render`      | `'static'` prerenders at build time; `'dynamic'` (the default) renders per request. |
| `staticPaths` | For a parameterised static route: the param sets to prerender, one file each.       |

Write `component` inline as `() => import('…')`. The framework detects that exact form and injects
Rspack's `'use server-entry'` directive for you, which is what attaches each page's client JS and CSS to
its component — per-route code splitting with no asset manifest. Wire a component up some other way
(variable indirection, barrel re-exports, computed specifiers) and the build throws a descriptive error
telling you to write the directive at the top of the page module yourself.

## Static rendering

`render: 'static'` builds a route once, at build time, in **both** the forms a page is asked for:
`index.html` for a hard load, and `index.rsc` — the flight payload — for a soft navigation. Both carry a
weak `ETag`, so a revalidation costs a 304 rather than the page.

A static route **with params** needs `staticPaths`. It runs at build time only, on the server, so it may
hit a database or the filesystem:

```ts
staticPaths: async () => (await db.docs.all()).map((d) => ({ slug: d.slug })),
```

`defineRoutes` checks the param sets against the route's own path, the same way it checks a page's props:
a set that does not carry every `:param` of the path is a type error where the route is declared, not a
build-time throw. Keys only — a `staticPaths` typed as returning `Record<string, string>` has none to
check, so it is accepted and the build reports the mismatch instead.

Rules worth knowing:

- **Reading `ctx` throws.** There is no request at build time. Use `params` and `url`, or make the route
  dynamic.
- **Set [`siteUrl`](/docs/configuration#siteurl)** if the page builds absolute URLs. Without it the
  origin is `http://localhost` and the build warns.
- **Wildcard, optional and regex params cannot be prerendered.** A parameterised static route without
  `staticPaths` falls back to per-request rendering, and the build warns. So does a page that did not
  render cleanly.
- **Under a [nonce-based CSP](/docs/configuration#csp)** the document is rendered per request — a
  prerendered file cannot carry a per-request nonce. The flight payload is still served from the
  prerender, and a policy with no nonce in it keeps its prerendered documents too.
- **`Cache-Control: public, max-age=300`**, with a weak `ETag`. To promise more — a longer `max-age`, a
  `stale-while-revalidate` — set it from middleware [after `await next()`](/docs/configuration#response-headers-and-caching).

## Endpoint routes

An endpoint route is served by a raw Hono handler instead of a component — JSON APIs, webhooks,
redirects, feeds. `method` defaults to `'all'`, takes one method or a list of them, and there is no
`'head'`: Hono dispatches a `HEAD` as a `GET` and strips the body off the response, so `'get'` already
answers both.

It is also how you answer a method a page does not. A page route is registered for `GET` and `POST` — plus
the `HEAD` that rides the `GET` — and anything else is a 404 rather than a 405, deliberately: the `Allow`
header a 405 owes the client would mean tracking the methods registered per path, for a distinction no client
here acts on differently.

```ts
{ type: 'endpoint', path: '/api/health', method: 'get', server: () => import('./health') }

// Two methods, one handler. Without the list this would be `'all'` plus a hand-rolled method check,
// which also answers every method you did not mean to. `'all'` inside a list is refused.
{ type: 'endpoint', path: '/api/session', method: ['get', 'delete'], server: () => import('./session') }
```

```ts
// src/health.ts
import type { Handler } from 'hono';

export const handler: Handler = (c) => c.json({ ok: true });
```

The module only ever loads on the server, so reading secrets from it is safe.

## notFound and error

Both are optional, and both are real server components with a page's contract minus a path of their own.

- **`notFound`** — rendered with a 404 for unmatched paths and for `notFound()` calls.
- **`error`** — rendered with a 500 when a request throws, and given an extra `error` prop: message-only
  in production, message plus stack in dev. `error.stack` is `undefined` in every build and
  `error.message` is the generic `'Internal Server Error'`, so render the stack behind a check on the
  stack itself — there is no mode flag to check:

  ```tsx
  export default function ServerError({ error }: ErrorPageProps) {
    return (
      <Layout>
        <p>{error.message}</p>
        {error.stack && <pre>{error.stack}</pre>}
      </Layout>
    );
  }
  ```

See [Configuration & security](/docs/configuration#no-blank-screens) for what happens when a failure is
bad enough that the `error` page itself cannot be reached.

---

<!-- source: https://www.rshono.com/docs/pages.md -->

---
title: Pages
description: A page is a React server component that renders the whole document and receives the request — and the 'use server' actions it mutates through.
---

Every page module **default-exports a server component** — nothing else. It may be `async` and await
data directly.

```tsx
import type { PageProps } from '@rshono/core';
import { db } from '../db';

export default async function Profile({ params, ctx }: PageProps<'/profile/:id'>) {
  const user = await db.getUser(params.id);
  const theme = ctx.cookies.get('theme') ?? 'light';
  return <Layout theme={theme}>{user.name}</Layout>;
}
```

Pages render the **entire document** (`<html>…</html>`), usually through a shared layout component.
Interactive parts are `'use client'` components the page imports — only those ship JavaScript.

There is no `<Link>`, `<Image>`, `<Script>` or `<Head>`: links are `<a href>`, images are `<img>`, forms
are `<form action>`. Same-origin anchors are soft-navigated automatically, except a destination whose last
path segment carries a dot (`/llms.txt`, `/report.pdf`) — that is a file, not a page, so the browser loads it
as a document. `data-native` opts any link out by hand; an endpoint with no extension in its path
(`/download?id=3`) still needs it.

## Page props

Every page receives `{ url, params, ctx }`. They are server-only and never serialized — React puts a
server component's _output_ on the wire, not its props.

| Prop     | What it is                                                                                                                                                                                   |
| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `url`    | The absolute browser-facing `URL`, proxy-header aware. A fresh instance per request.                                                                                                         |
| `params` | The matched route params. `PageProps<'/profile/:id'>` types `params.id` as `string`.                                                                                                         |
| `ctx`    | The request context — `req`, cookies, env, middleware variables. Same object `getRequestContext()` returns. Reads only in a page: [writes throw](/docs/api#writes-happen-before-the-render). |

Type `ctx.var` and `ctx.env` for your app by passing its Hono `Env`:

```tsx
export default function Dashboard({ ctx }: PageProps<'/dashboard', AppEnv>) {
  const session = ctx.cookies.get('session');
  if (!session) redirect('/login');
  return <Layout>Signed in as {session}</Layout>;
}
```

`ctx` is **non-enumerable**, which is the one place these props break a JavaScript expectation: a
`<Child {...props} />` spread hands the child `ctx: undefined` — silently, since a spread copies
enumerables only, and the type still says `ctx` is there. It has to be that way; an enumerable `ctx`
would put `ctx.hono.env`, every binding and secret, into React's dev-only serialization of a server
component's props. Don't spread page props: nested server components are meant to ask for the context
themselves.

Nested server components and `'use server'` actions get no props — they call `getRequestContext()` from
`@rshono/core/server` for the same object. There, `ctx.params` stands in for the `params` prop and
`ctx.req` for the parsed request:

```tsx
import { getRequestContext } from '@rshono/core/server';

async function Breadcrumb() {
  const ctx = getRequestContext(); // no props down here
  return (
    <nav>
      {ctx.params.id} · {ctx.req.method}
    </nav>
  );
}
```

### A page can read `ctx`, not write to it

`ctx.cookies.set()`, `ctx.cookies.delete()` and `ctx.setHeader()` **throw inside a page**. A page
streams, so its response head is committed before the component runs — a cookie set here would arrive
on a full page load and silently vanish on a soft navigation. Write it from a
[server action](#cookies-and-headers) or from
[middleware](/docs/hono#response-headers-and-cookies), both of which run first.

Hono's response builders are the same story, and say so: `ctx.redirect()`, `ctx.notFound()`, `ctx.json()`
and friends throw with a pointer to the API that works — `redirect()` and `notFound()` from
`@rshono/core/server`, or an [endpoint route](/docs/routing#endpoint-routes) for a non-HTML response.
`ctx.hono` is the full Hono `Context` for the long tail, and going through it bypasses the error rather
than fixing it.

### `ctx` cannot cross into the client

`ctx` wraps the live request and response, so it is non-enumerable and never reaches the browser.

- Passing it explicitly (`<Counter ctx={ctx} />`) fails the render with React's _"Only plain objects …
  can be passed to Client Components"_.
- Spreading page props (`<Counter {...props} />`) drops it silently — a spread copies enumerables only.
  That spread still fails, on `url`, which is enumerable and just as unserializable. Into a **server**
  child the same spread fails at nothing: `ctx` is simply `undefined` there. Call `getRequestContext()`
  in the child.

Read what you need on the server and pass plain values down: `url.href`, not `url`.

On a [prerendered page](/docs/routing#static-rendering) reading `ctx` throws — there is no request.

## Client components

A `'use client'` module is the interactive part, and `useNavigation()` is the whole client-side routing
API:

```tsx
'use client';
import { useNavigation } from '@rshono/core/client';

export function NextPage() {
  const { url, router } = useNavigation();
  const page = Number(url.searchParams.get('page') ?? '1');
  return (
    <button disabled={router.pending} onClick={() => router.push(`${url.pathname}?page=${page + 1}`)}>
      Next
    </button>
  );
}
```

`url` and `params` have the same names and types as page props. During SSR and hydration they come
from the server payload; after hydration, `url` follows the browser address, including its query and
fragment, even on static pages. `params` remains tied to the displayed page until its replacement
commits. `router` holds `push`, `replace`, `back`, `forward`, `refresh` and `pending`. Intercepted
navigations preserve client state outside the changed subtree; navigation to another site loads a document.

`<AsyncBoundary>` pairs a Suspense fallback with an error fallback, and `<CatchBoundary>` is the error
half alone. Both are `'use client'` modules a server component can render directly. A `redirect()` is
never absorbed by either — it is navigation, not failure.

## Server actions

A `'use server'` module exports functions a client component can call directly, with typed arguments and
result:

```ts
'use server';

export async function createUser(data: { name: string; email: string }) {
  // runs on the server, always
}
```

There is no route handler in between, and no client bundle carries the body — only a reference to it.
[Usage](/docs/usage) covers wiring them into components with `useActionState`, `useTransition` and
`useOptimistic`; what follows is what an action _is_ on this side of the wire.

### Progressive enhancement

A `<form action={createUser}>` posts **before hydration and with JavaScript disabled**. The client
runtime upgrades it to a fetch once loaded; until then the browser's own form post does the job.

Every action response carries a fresh page payload, so server-rendered UI updates after a mutation with
no refetch and no cache invalidation call.

### Cookies and headers

An action runs **before** the page it re-renders, which is what makes it the place to write to the
response — [the rule above](#a-page-can-read-ctx-not-write-to-it) is the other side of the same coin:

```ts
'use server';
import { getRequestContext, redirect } from '@rshono/core/server';

export async function login(form: FormData) {
  const ctx = getRequestContext();
  ctx.cookies.set('session', await createSession(form), { httpOnly: true, sameSite: 'Lax', path: '/' });
  redirect('/dashboard');
}

export async function logout() {
  const ctx = getRequestContext();
  ctx.cookies.delete('session', { path: '/' });
  ctx.setHeader('clear-site-data', '"cache", "storage"');
  redirect('/');
}
```

Both survive the `redirect()` — the signal is thrown after the cookie is already on the response.

For headers that belong to a route rather than to a mutation, use
[middleware](/docs/hono#response-headers-and-cookies).

### Every action is a public endpoint

That is the RSC model, not an rshono choice: the client is handed an id for each action and can call it
with whatever arguments it likes. A [CSRF check](/docs/configuration#security-middleware) proves a
request came from your own site; it says nothing about _who_ sent it. Authenticate, authorize and validate
arguments inside the action, exactly as in a route handler.

An action's arguments are decoded from the request body, which means the body is buffered before your code
sees any of it. Register [`bodyLimit()`](/docs/configuration#security-middleware) so there is a size past
which that never happens — `rshono build` warns when nothing under `src/` registers one.

### Errors

Thrown action errors are logged server-side and **redacted in the production payload** — React sends no
message and no digest. Return values, not throws, for anything the user should see:

```ts
'use server';

export async function createUser(data: FormData) {
  const email = String(data.get('email') ?? '');
  if (!email.includes('@')) return { ok: false, error: 'That email looks wrong.' };
  return { ok: true };
}
```

Errors that do escape reach [`onServerError`](/docs/hono#error-reporting) like everything else the
framework catches.

### Secrets

Actions compile to server references and run only on the server, so they read the real `process.env`.
See [Environment & secrets](/docs/configuration#environment-and-secrets).

## The `'use server-entry'` directive

A technical note, not a step: none of the pages above write this directive, and neither does an app. It
shows up in Rspack's output and in one error message, which is the only reason it is documented here.

Compiled pages carry Rspack's `'use server-entry'`, which hangs the page's own client JS and CSS off its
default export. The framework reads them back as the document's bootstrap scripts and stylesheet links —
per-page code splitting with no asset manifest. The build finds the pages to mark by reading `routes.ts` for
inline `component: () => import('…')` thunks and prepending the directive to exactly the modules they name.
It re-scans on every rebuild, so a route added while the dev server is running needs no restart.

Write the thunk inline and there is nothing to do. A `component` reached some other way — through a variable,
a barrel re-export, a computed specifier — is invisible to that scan, and a module that already opens with a
directive of its own is left untouched; in either case put `'use server-entry'` on the page module's first
line yourself. A page that ends up without it renders into a descriptive error naming the route and both
ways of fixing it.

---

<!-- source: https://www.rshono.com/docs/hono.md -->

---
title: Hono & middleware
description: src/server.ts is a Hono sub-app — middleware, endpoints, end-to-end types, error reporting.
---

There is a whole Hono app under the pages, and it is yours. `src/server.ts` may default-export a sub-app:
any method, streaming, cookies, middleware.

```ts
import { Hono } from 'hono';
import { trimTrailingSlash } from 'hono/trailing-slash';

export type AppEnv = { Variables: { requestId: string } };

const server = new Hono<AppEnv>();

server.use(trimTrailingSlash({ alwaysRedirect: true }));

server.use('*', async (c, next) => {
  c.set('requestId', crypto.randomUUID());
  await next();
});

server.get('/api/health', (c) => c.json({ status: 'ok', requestId: c.var.requestId }));

export default server;
export type AppType = typeof server;
```

The sub-app is mounted at `/` **ahead of the page routes**, so its middleware — auth, logging,
trailing-slash — wraps page requests too.

The flip side: a _terminal_ handler at the same path as a page route **shadows the page**. Middleware
that calls `next()` is fine; a handler that returns a response is not.

## Security middleware

Because the sub-app wraps page requests, this is also where the app's security controls go. The
framework ships none of its own — Hono's are better tested than anything rshono would write, and a
config field would only be a worse way to spell the same call. `create-rshono` puts the first two in
every new app.

### Request-body limit

Caps a body _before_ it is buffered into memory and answers `413`. Registered here it covers
everything downstream — pages, server actions and your own handlers — since any of them is exposed the
moment it calls `.json()` or `.formData()`:

```ts
import { bodyLimit } from 'hono/body-limit';

server.use(bodyLimit({ maxSize: 1024 * 1024 })); // 1 MiB
```

An over-cap `Content-Length` is refused up front; a chunked body is cut off mid-stream. Raise it on
one path rather than globally where you accept uploads:

```ts
server.use('/api/upload', bodyLimit({ maxSize: 50 * 1024 * 1024 }));
```

[Hono — Body Limit](https://hono.dev/docs/middleware/builtin/body-limit)

### CSRF

Rejects a cross-origin POST with 403 before it can reach a server action:

```ts
import { publicUrl } from '@rshono/core/server';
import { csrf } from 'hono/csrf';

server.use(csrf({ origin: (origin, c) => origin === publicUrl(c).origin }));
```

Use `publicUrl(c)` rather than Hono's default same-origin comparison, which reads `c.req.url` — the
address this server was _reached_ on, which is the internal one behind any proxy, `rshono dev`
included. It honours [`trustProxy`](/docs/configuration#proxy-headers), so it stays `c.req.url` where
no proxy is declared. To allow more origins:

```ts
server.use(
  csrf({
    origin: (origin, c) => origin === publicUrl(c).origin || origin === 'https://admin.example.com',
  }),
);
```

It only inspects the content types a browser can send cross-origin without a preflight — which is
exactly the shape a server action arrives in, so a JSON API route is unaffected.

[Hono — CSRF](https://hono.dev/docs/middleware/builtin/csrf)

### Security headers and CSP

`secureHeaders()` with no arguments sets a sensible set — HSTS, COOP, CORP, `nosniff`,
`X-Frame-Options` and more:

```ts
import { secureHeaders } from 'hono/secure-headers';

server.use(secureHeaders());
```

Add Hono's `NONCE` placeholder to `scriptSrc` and the CSP becomes per-request: Hono mints the nonce,
and rshono stamps that value onto the bootstrap scripts and the inlined flight payload.

```ts
import { NONCE, secureHeaders } from 'hono/secure-headers';

server.use(
  secureHeaders({
    contentSecurityPolicy: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", NONCE],
      styleSrc: ["'self'", "'unsafe-inline'"], // React writes inline styles
    },
  }),
);
```

Nothing there mentions `'unsafe-eval'`: React Refresh needs it, so rshono widens `script-src` under
`rshono dev` and never in a build — one policy serves both. See [CSP](/docs/configuration#csp) for the
full policy and what a nonce costs a static route.

[Hono — Secure Headers](https://hono.dev/docs/middleware/builtin/secure-headers)

### Rejections keep their status

Middleware that refuses a request by throwing an `HTTPException` — `csrf()` with a 403, `bodyLimit()`
with a 413, your own guard — is handed straight back rather than rendered as the 500 page:

```ts
import { HTTPException } from 'hono/http-exception';

server.use('/admin/*', async (c, next) => {
  if (!c.req.header('authorization')) throw new HTTPException(401, { message: 'Unauthorized' });
  await next();
});
```

One gap: `/_static` assets are served before the sub-app is reached, so middleware never sees them. The
framework sets `nosniff`, `Referrer-Policy` and `X-Frame-Options` on
[every response](/docs/configuration#response-headers-and-caching) to cover them, and stands aside
wherever your own `secureHeaders()` set the same header.

## Other middleware worth knowing

Everything Hono ships works here, because this really is a Hono app. The ones that come up most:

| Middleware                                                                 | For                                                                 |
| -------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| [`cors`](https://hono.dev/docs/middleware/builtin/cors)                    | Cross-origin access to your `{ type: 'endpoint' }` API routes       |
| [`basicAuth`](https://hono.dev/docs/middleware/builtin/basic-auth)         | Password-gating a staging deploy or an admin path                   |
| [`bearerAuth`](https://hono.dev/docs/middleware/builtin/bearer-auth)       | Static-token auth on an API route                                   |
| [`jwt`](https://hono.dev/docs/middleware/builtin/jwt)                      | Verifying a JWT and putting its payload on `c.var.jwtPayload`       |
| [`requestId`](https://hono.dev/docs/middleware/builtin/request-id)         | A trace id per request, readable from a page as `ctx.var.requestId` |
| [`logger`](https://hono.dev/docs/middleware/builtin/logger)                | Method, path, status and duration per request                       |
| [`timeout`](https://hono.dev/docs/middleware/builtin/timeout)              | Refusing a request that outruns a deadline                          |
| [`ipRestriction`](https://hono.dev/docs/middleware/builtin/ip-restriction) | Allow/deny lists in front of an internal route                      |
| [`trailingSlash`](https://hono.dev/docs/middleware/builtin/trailing-slash) | Keeping `/about` and `/about/` from being two pages                 |

Three exceptions, where the framework already owns the job or the two do not mix:

- **`etag`** digests the whole response before sending it, so it would buffer a streaming page render
  end to end. Prerendered pages already carry a weak `ETag` and answer `304`.
- **`serveStatic`** is unnecessary — `/_static` and `public/` are mounted for you.
- **`jsxRenderer`** is for Hono's own JSX; here React owns rendering.

The full list is in [Hono's docs](https://hono.dev/docs), alongside its helpers —
[`cookie`](https://hono.dev/docs/helpers/cookie), `proxy`, `streaming`, `testing` and the rest.

## Typing the context

The `Env` given to the Hono app is the same one that types `ctx` on a page. Pass it to `PageProps` and
`ctx.var` is typed key by key instead of being an open record:

```tsx
import type { PageProps } from '@rshono/core';
import type { AppEnv } from '../server';

export default function Home({ ctx }: PageProps<'/', AppEnv>) {
  return <p>Request {ctx.var.requestId}</p>; // typed
}
```

## Response headers and cookies

Middleware is where a page's response headers belong. A page renders too late to set one — its response
head is committed before the component runs, so [`ctx.setHeader()` throws
there](/docs/api#writes-happen-before-the-render). Middleware runs first, and gets Hono's `c` directly:

```ts
import { setCookie } from 'hono/cookie';

server.use('/blog/*', async (c, next) => {
  await next();
  c.header('cache-control', 'public, max-age=600, s-maxage=3600');
});

server.use('*', async (c, next) => {
  if (!c.req.header('cookie')?.includes('visitor=')) setCookie(c, 'visitor', crypto.randomUUID(), { path: '/' });
  await next();
});
```

Matching on a path pattern is deliberate: one middleware covers a group of routes, so caching policy
lives in one place rather than being repeated on every route that shares it.

`getRequestContext()` is **not** available in middleware or in `{ type: 'endpoint' }` routes — the
request context is bound around the render and the actions it runs, not around the whole Hono stack.
Neither needs it: both are handed `c`, which is a superset.

For a header that depends on a mutation rather than on the route — a session cookie after login — use a
[server action](/docs/pages#cookies-and-headers) instead.

## End-to-end types for a client

`export type AppType = typeof server` gives typed paths, params and responses with `hono/client`,
checked against the handlers themselves:

```ts
import { hc } from 'hono/client';
import type { AppType } from './server';

const client = hc<AppType>('/');
const res = await client.api.health.$get();
```

## Error reporting

One handler, registered at the top level of `src/server.ts`, catches every error the framework sees — a
thrown action, a failed render, SSR falling over, anything reaching the top-level handler:

```ts
import { onServerError } from '@rshono/core/server';

onServerError((error, { source, request, hono, waitUntil }) => {
  waitUntil(
    Sentry.captureException(error, {
      tags: { source, requestId: hono.var.requestId },
      extra: { url: request.url },
    }),
  );
});
```

`source` is `'action' | 'render' | 'ssr' | 'request'`. Errors keep going to `stderr` either way, and a
handler that throws is caught rather than failing the request.

`hono` is the request's Hono context — `hono.var` for what your middleware put there, `hono.env` for
bindings. It is handed over because `getRequestContext()` is not reachable from this handler: a
`source: 'request'` error is reported from the top-level handler, outside the ambient context.

`waitUntil` holds the invocation open until the report has been sent. On Cloudflare Workers that is
`executionCtx.waitUntil`, without which a report started here is cut off the moment the response ends. On
the `node` and `vercel` targets there is nothing to hold open — the process outlives the response — so it
is a no-op and the report finishes on its own. On `aws-lambda` it is a no-op as well, because the streaming
handler exposes no execution context to ask; a slow report there is best-effort, so prefer a tracker that
batches over one that round-trips per error.

---

<!-- source: https://www.rshono.com/docs/usage.md -->

---
title: Usage
description: Putting it together — co-located actions, streamed data and optimistic updates, in the shapes most of an app is built from.
---

A client component imports a server function and calls it. That is the whole data layer:

```tsx
import { createNote } from './action'; // runs on the server, always

await createNote('Buy milk');
```

No `/api/notes`, no `fetch`, no JSON envelope, no route handler, no client cache to invalidate. The
import compiles to a reference — the function's body, and everything it imports, stays on the server.
Arguments and the return value are typed end to end, so renaming a field is a type error rather than a
runtime surprise.

Every example below talks to one module. What it wraps — Drizzle, Prisma, D1, a `Map` — changes nothing
above it:

```ts title="src/db.ts"
export interface Note {
  id: string;
  text: string;
  done: boolean;
}

export declare const db: {
  listNotes(): Promise<Note[]>;
  createNote(text: string): Promise<Note>;
  setDone(id: string, done: boolean): Promise<void>;
};
```

## Co-locating a component and its action

A component that mutates has two halves, and they change together. Keep them in one folder:

```
src/components/new-note/
  index.tsx    'use client' — the form
  action.ts    'use server' — what it calls
```

The framework attaches no meaning to either name — [`src/` is yours to arrange](/docs/project-layout) —
but the split earns its keep. `'use server'` is a **module-level** directive, and every export of such a
module is [a public endpoint](/docs/pages#every-action-is-a-public-endpoint). One small file per
component keeps that surface readable in a glance and sitting next to the only component that calls it;
a single `src/actions.ts` for the whole app grows into a list nobody audits.

## Forms: `useActionState`

The action takes the previous state and the submitted `FormData`, and returns the next state:

```ts title="src/components/new-note/action.ts"
'use server';

import { db } from '../../db';

export interface NewNoteState {
  error?: string;
}

export async function createNote(_prev: NewNoteState, form: FormData): Promise<NewNoteState> {
  const text = String(form.get('text') ?? '').trim();
  if (!text) return { error: 'A note needs some text.' };

  await db.createNote(text);
  return {};
}
```

`useActionState` wires it to the form and hands back the pending flag:

```tsx title="src/components/new-note/index.tsx"
'use client';

import { useActionState } from 'react';
import { createNote, type NewNoteState } from './action';

const empty: NewNoteState = {};

export function NewNote() {
  const [state, formAction, pending] = useActionState(createNote, empty);

  return (
    <form action={formAction}>
      <input name="text" placeholder="Buy milk" />
      <button disabled={pending}>{pending ? 'Saving…' : 'Add note'}</button>
      {state.error && <p role="alert">{state.error}</p>}
    </form>
  );
}
```

Two things fall out of this that normally cost work, and neither is something this component opted into —
both are [what a server action is](/docs/pages#server-actions). The form works **before hydration and with
JavaScript off**. And the action's response carries a fresh page payload, so a note list rendered elsewhere
on the page already shows the new note: nothing to refetch, no cache to invalidate.

Return validation failures, as above; don't throw them.
[Thrown action errors are redacted](/docs/pages#errors) in production, so the user would see nothing
useful.

## Direct calls: `useTransition`

Not every mutation is a form. A checkbox has typed arguments, not `FormData`:

```ts title="src/components/note-toggle/action.ts"
'use server';

import { db } from '../../db';

export async function setDone(id: string, done: boolean): Promise<void> {
  await db.setDone(id, done);
}
```

```tsx title="src/components/note-toggle/index.tsx"
'use client';

import { useTransition } from 'react';
import { setDone } from './action';

export function NoteToggle({ id, done }: { id: string; done: boolean }) {
  const [pending, startTransition] = useTransition();

  return (
    <input
      type="checkbox"
      checked={done}
      disabled={pending}
      onChange={(event) => {
        const next = event.target.checked;
        startTransition(async () => {
          await setDone(id, next);
        });
      }}
    />
  );
}
```

Calling `setDone(id, next)` on its own also works — the runtime applies the action's page payload inside a
transition either way, so the list re-renders without tearing the UI down. What `startTransition` adds is a
pending flag scoped to **this** interaction: `pending` stays true for the round trip _and_ the re-render it
triggers, which is what lets the checkbox disable itself for exactly that long.
(`useNavigation().router.pending` is the whole-page equivalent, and it cannot tell you which control was
clicked.) A transition is also the scope [optimistic updates](#optimistic-updates) require.

|                   | `useActionState`               | `useTransition`                       |
| ----------------- | ------------------------------ | ------------------------------------- |
| Attaches to       | `<form action={…}>`            | any event handler                     |
| Arguments         | `FormData`                     | typed values you already hold         |
| Works without JS  | ✅                             | ❌                                    |
| Hands you         | `[state, formAction, pending]` | `[pending, startTransition]`          |
| Reach for it when | the result is state you render | you only need to know it is in flight |

## Loading data with `<AsyncBoundary>`

A server component awaits the database directly. No loader, no `useEffect`, no fetch on mount:

```tsx title="src/components/notes.tsx"
import { AsyncBoundary } from '@rshono/core/client';
import { db } from '../db';
import { Layout } from './layout';
import { NewNote } from './new-note';

async function NoteList() {
  const notes = await db.listNotes();
  return (
    <ul>
      {notes.map((note) => (
        <li key={note.id}>{note.text}</li>
      ))}
    </ul>
  );
}

export default function Notes() {
  return (
    <Layout title="Notes">
      <h1>Notes</h1>
      <NewNote />
      <AsyncBoundary loading={<p>Loading notes…</p>} error={<p>Could not load notes.</p>}>
        <NoteList />
      </AsyncBoundary>
    </Layout>
  );
}
```

The heading and the form are sent **immediately**; the `<ul>` streams in when the query resolves. A slow
query delays its own section and nothing else, and if it rejects, the error stays inside the boundary
instead of taking the page down.

`<AsyncBoundary>` is scoped to the route. A soft navigation to a different pathname mounts the incoming
route's boundary, so the `loading` state renders while the new route's data streams rather than the page
you left staying on screen. A same-page update — `router.refresh()`, a server action, or a change to the
query string — keeps the boundary and the content it has already revealed.

That scope is a **remount** on every pathname change: state and mount effects under the boundary do not
survive a navigation to another route. It is what makes the incoming `loading` state and the error reset
work, but it means a section whose state must outlive navigation — a socket, an editor, a session hook —
wants a bare `<CatchBoundary>` (with a `<Suspense>` of your own above it, or none) instead.

`<AsyncBoundary>` is a `'use client'` module, so you can render it straight from a server component like
this — but note what crosses that line. `NoteList` is still a server component and ships no JavaScript;
only the boundary itself does. And `loading` / `error` are being passed **from the server**, so they must
be nodes. The `(error, reset) => …` form of `error` needs a function, and functions cannot cross the
server→client boundary — use it from a `'use client'` component when you want a _Try again_ button. See
[`@rshono/core/client`](/docs/api#rshonocoreclient).

## Passing actions to client components

A server component can declare its actions inline and hand them down as props. The client half then knows
nothing about the database — only that it was given some functions to call:

```tsx title="src/components/note-board/index.tsx"
import { db } from '../../db';
import { Board } from './board';

export default async function NoteBoard() {
  const notes = await db.listNotes();

  async function createNote(text: string) {
    'use server';
    await db.createNote(text);
  }

  async function setDone(id: string, done: boolean) {
    'use server';
    await db.setDone(id, done);
  }

  return <Board notes={notes} onCreate={createNote} onToggle={setDone} />;
}
```

```tsx title="src/components/note-board/board.tsx"
'use client';

import { useTransition } from 'react';
import type { Note } from '../../db';

interface BoardProps {
  notes: Note[];
  onCreate: (text: string) => Promise<void>;
  onToggle: (id: string, done: boolean) => Promise<void>;
}

export function Board({ notes, onCreate, onToggle }: BoardProps) {
  const [pending, startTransition] = useTransition();

  return (
    <>
      <ul aria-busy={pending}>
        {notes.map((note) => (
          <li key={note.id}>
            <input
              type="checkbox"
              checked={note.done}
              onChange={(event) => {
                const next = event.target.checked;
                startTransition(async () => {
                  await onToggle(note.id, next);
                });
              }}
            />
            {note.text}
          </li>
        ))}
      </ul>
      <button onClick={() => startTransition(async () => await onCreate('New note'))}>Add</button>
    </>
  );
}
```

`Board` is a plain component taking two callbacks. It could be handed different implementations in a test
without knowing that the real ones are server references at all.

> **An inline action cannot close over its component's scope.** `'use server'` in a function body compiles
> to a module-level function plus _encrypted bound arguments_, and that encryption is not wired up in the
> Rspack / `react-server-dom-rspack` pair rshono currently pins — capturing anything from the enclosing
> scope fails the build with `export 'encryptActionBoundArgs' … was not found`. The functions above are
> fine because they close over nothing; `db` is a module import.

To attach per-item data, bind it to a module-scope action explicitly. `bind` is the supported spelling of
the same idea, and the bound arguments travel with the reference:

```tsx
import { setDone } from './action';

// `markDone()` now takes no arguments — the id and the flag are baked in.
<DoneButton markDone={setDone.bind(null, note.id, true)} />;
```

Have the child call it itself, inside a transition. Don't hand a bound action straight to `onClick`: React
would pass the click event along as one more argument, and a synthetic event is not serializable.

## Advanced

### Optimistic updates

`useOptimistic` shows the result before the server confirms it. The base value is whatever the server last
sent; the reducer layers the pending change on top:

```ts title="src/components/note-list/action.ts"
'use server';

import { db } from '../../db';

export async function addNote(text: string): Promise<void> {
  await db.createNote(text);
}
```

```tsx title="src/components/note-list/index.tsx"
'use client';

import { useOptimistic, useRef } from 'react';
import type { Note } from '../../db';
import { addNote } from './action';

export function NoteList({ notes }: { notes: Note[] }) {
  const form = useRef<HTMLFormElement>(null);
  const [shown, addPending] = useOptimistic(notes, (current, text: string) => [...current, { id: `pending:${text}`, text, done: false }]);

  return (
    <>
      <ul>
        {shown.map((note) => (
          <li key={note.id} data-pending={note.id.startsWith('pending:') || undefined}>
            {note.text}
          </li>
        ))}
      </ul>

      <form
        ref={form}
        action={async (data: FormData) => {
          const text = String(data.get('text') ?? '').trim();
          if (!text) return;
          addPending(text);
          form.current?.reset();
          await addNote(text);
        }}
      >
        <input name="text" />
        <button>Add</button>
      </form>
    </>
  );
}
```

An `async` function passed to `<form action>` is a React Action, so it already runs inside a transition —
which is what `addPending` requires. The optimistic note renders instantly, and when `addNote` resolves the
action's response brings a re-rendered `notes` prop down from the server: the real note replaces the
pending one and the optimistic layer drops away on its own. There is no "remove the temporary item" code
to write, and if the action throws, React reverts it for you.

Give the pending item a distinguishable `id` rather than a real-looking one. It is the only handle you
have for styling it as unconfirmed, and it must not collide with a key the server will send.

Note what this costs: the `action` here is a **client** function, so this form needs JavaScript. The
[`useActionState` form](#forms-useactionstate) hands `<form action>` the server action itself and works
without it. Optimism is for interactions where the wait is worth hiding, not for every form on the page.

---

<!-- source: https://www.rshono.com/docs/styling.md -->

---
title: Styling & assets
description: Native CSS code-split per route, the four lines that add Tailwind, and public/.
---

Import a stylesheet from any component:

```tsx
import './styles.css';
```

Rspack's native CSS pipeline compiles it, and the import **attaches the stylesheet to the importing
page's assets**. CSS is therefore code-split per route and `<link>`ed in the streamed HTML rather than
fetched after hydration. `*.module.css` gets a class map.

## No PostCSS in the framework

Not as a dependency, not as an optional one. Native CSS is everything a plain stylesheet needs — but
that parser reads _finished_ CSS, and `@import 'tailwindcss'`, `@theme` and `@apply` are not that. A
stylesheet that needs a plugin brings the plugin itself, through the
[`rspack` hook](/docs/configuration#the-rspack-hook).

## Tailwind

Four things, and `npx @rshono/create@latest --tailwind` writes all of them:

```bash
npm i -D tailwindcss @tailwindcss/postcss postcss postcss-loader
```

```ts
// rshono.config.ts — the hook is called once per compiler, so this reaches both graphs
export default defineConfig({
  rspack(config) {
    config.module!.rules!.push({ test: /\.css$/i, use: ['postcss-loader'], type: 'css/auto' });
  },
});
```

```js
// postcss.config.mjs — the plugin list, which postcss-loader finds on its own
export default { plugins: { '@tailwindcss/postcss': {} } };
```

```css
/* src/styles.css */
@import 'tailwindcss';
```

Keep `type: 'css/auto'` rather than `'css'`, or `*.module.css` stops being a CSS module. Any other
PostCSS plugin is the same shape — the rule puts postcss-loader in the chain, `postcss.config.mjs` says
which plugins run.

## public/

Anything in `public/` is served verbatim at the **web root**, and copied into `dist/` by the build:

```
public/favicon.ico       →  /favicon.ico
public/robots.txt        →  /robots.txt
public/.well-known/…     →  /.well-known/…
```

It is a fallback: routes always win, and unmatched paths still reach the `notFound` page, so a `public/`
file never shadows a route.

## Caching

| What                 | Served from | Caching                             |
| -------------------- | ----------- | ----------------------------------- |
| Hashed bundle output | `/_static/` | long-lived, `immutable`             |
| `public/` files      | web root    | short `max-age` (`no-cache` in dev) |

A bundle filename contains its content hash, so it can be cached forever. `public/favicon.svg` is the
same URL whatever its contents, so it cannot. On a platform with a CDN both go straight to the CDN;
[prerendered pages do not](/docs/deployment#prerendered-pages-are-never-cdn-served).

---

<!-- source: https://www.rshono.com/docs/configuration.md -->

---
title: Configuration & security
description: rshono.config.ts — every field, the secret boundary, and what is hardened by default.
---

An optional `rshono.config.ts` (`.js` / `.mjs` also work) at the project root tunes the framework. Every
field is optional; delete the file to accept all defaults.

```ts
import { defineConfig } from '@rshono/core';

export default defineConfig({
  deploy: 'node', // hosting platform to build for (--deploy or RSHONO_DEPLOY override)
  siteUrl: 'https://example.com', // public origin, baked into prerendered pages' absolute URLs
  trustProxy: false, // honour X-Forwarded-Host/-Proto — only behind a proxy you control
  rspack(config, { isServer, isDev }) {
    return config; // escape hatch: mutate the generated Rspack config
  },
});
```

That is the whole file, and deliberately so: it holds only what the **build** decides. Everything that
is a per-request concern — CSRF, CSP, the request-body cap — is Hono middleware in
[`src/server.ts`](/docs/hono), because Hono already ships all of it and a config field would only be a
worse way to spell the same call. See [security middleware](#security-middleware) below.

`trustProxy` is resolved at build time and **compiled into the server bundle**, so changing it means a
rebuild. Two deployment-conventional exceptions stay env-overridable: `--port` / `PORT` and `HOST`, each
winning over the file, which wins over the default. Point a build at a different file with
`--config <path>`.

## `siteUrl`

The public origin the site is served from. Used only when prerendering
[`render: 'static'`](/docs/routing#static-rendering) routes, where there is no request to read a `Host`
from. The origin is what's used; a path is **rejected** rather than silently dropped, because a base
path is not supported.

## The `rspack` hook

Mutate the generated Rspack config just before it is compiled:

```ts
rspack(config, { isServer, isDev }) {
  config.module!.rules!.push({ test: /\.md$/i, type: 'asset/source' });
}
```

Called **once per compiler** — `isServer` tells the `target: node` bundle from the `target: web` one,
`isDev` tells `rshono dev` from `rshono build`. Mutate in place and return nothing, or return a
replacement. This is how [Tailwind](/docs/styling#tailwind) is wired up.

## Environment and secrets

The client/server boundary is the RSC directives — `'use client'` and `'use server'` — not filenames,
and `process.env` follows it.

In client code `process.env` is **replaced at build time** with a literal containing only `NODE_ENV` and
`PUBLIC_`-prefixed variables. A stray `process.env.DATABASE_URL` compiles to `undefined`. That is a hard
guarantee rather than tree-shaking, and it covers `node_modules` too.

`'use client'` modules are also rendered on the server, and there they see the same `PUBLIC_`-only view,
so SSR output agrees with hydration and a secret cannot leak into the HTML stream. One boundary on that:
the SSR-side shadowing is scoped to your own `src/`, so a **third-party** client component reading
`process.env` during SSR sees the real environment.

Server components and `'use server'` actions read the **real** `process.env`. They run only on the
server, so a secret read there never reaches the browser. Read secrets in server code and pass derived
data down.

`.env.local` and `.env` are loaded automatically, and the real environment wins over both. Commit `.env`
with safe defaults; keep `.env.local` gitignored.

Both are read **once, when the process starts**, and the `PUBLIC_` view of them is compiled into the bundle by
`DefinePlugin` — so `rshono dev` does not pick up an edit to either. A rebuild is not enough and does not
look like a failure: the page rebuilds, serves, and shows the old value. Restart the dev server. It watches
both files and says so when one changes, and the same holds for `rshono.config.ts`, which is read once too.

`getRequestContext().env` is that same environment, plus the platform's own runtime bindings where it has
them — `deploy: 'cloudflare'`, where a KV namespace or a Worker secret arrives per request and wins over a
process variable of the same name. On every other target it is `process.env` alone: Hono's `c.env` there is
the adapter's private state rather than your bindings, so the framework does not merge it. `ctx.hono.env`
still reaches it if you need it.

Two things worth remembering:

- **Anything a server component renders is public.** Whatever is in the tree ships in the flight
  payload. The boundary protects `process.env`, not your JSX.
- **Keeping a server-only module out of the client bundle is the module graph's job.** For a hard
  failure if that slips, add React's `server-only` package — the RSC layer resolves its `react-server`
  condition, so importing it from client code throws.

## Security middleware

The framework runs no CSRF check, body cap or CSP of its own. All three are Hono middleware you
register in `src/server.ts`, which is mounted **ahead of the page routes** — so anything registered
there wraps page renders and server actions, not just your own handlers.

`create-rshono` scaffolds the first two into every new app. An app written by hand down to
`src/routes.ts` has neither until it adds them.

```ts
// src/server.ts
import { publicUrl } from '@rshono/core/server';
import { Hono } from 'hono';
import { bodyLimit } from 'hono/body-limit';
import { csrf } from 'hono/csrf';

const server = new Hono();

server.use(bodyLimit({ maxSize: 1024 * 1024 }));
server.use(csrf({ origin: (origin, c) => origin === publicUrl(c).origin }));

export default server;
```

**[`bodyLimit`](https://hono.dev/docs/middleware/builtin/body-limit)** caps a request body _before_ it is
buffered into memory and answers `413`. Registered here it covers every route, not just actions —
endpoint routes and your own handlers are equally exposed the moment they call `.json()` or
`.formData()`. An over-cap `Content-Length` is refused up front; a chunked body is cut off mid-stream.

**[`csrf`](https://hono.dev/docs/middleware/builtin/csrf)** rejects a cross-origin POST with 403 before it
can reach a server action. It layers `Sec-Fetch-Site` over `Origin`, and only inspects the content types
a browser can send cross-origin without a preflight — which is exactly the shape a server action arrives
in: `text/plain` for a client-initiated call, `multipart/form-data` for a no-JS form post. A JSON API
route is unaffected.

Pass `publicUrl(c)` rather than relying on the default same-origin comparison, which reads `c.req.url` —
the address the server was _reached_ on. Behind a proxy that terminates TLS or rewrites `Host` that is
the internal address, and a legitimate post would then be riding on `Sec-Fetch-Site` alone. `publicUrl`
honours [`trustProxy`](#proxy-headers), so it stays `c.req.url` where no proxy is declared. To allow
another origin:

```ts
server.use(
  csrf({
    origin: (origin, c) => origin === publicUrl(c).origin || origin === 'https://admin.example.com',
  }),
);
```

The check proves a request came from your own site. It says nothing about _who_ sent it — every
[`'use server'` export is a public endpoint](/docs/pages#every-action-is-a-public-endpoint).

Everything else Hono ships works the same way — `cors`, `basicAuth`, `jwt`, `ipRestriction`, `timeout`,
`requestId`, and [`secureHeaders`](#csp) below. A middleware that rejects by throwing an `HTTPException`
keeps its own status, rather than being rendered as the 500 page. See
[Hono & middleware](/docs/hono#security-middleware) for worked examples and
[Hono's docs](https://hono.dev/docs) for the full set.

## Proxy headers

`X-Forwarded-Host` and `X-Forwarded-Proto` are client-supplied and **not trusted by default**. Honouring
them blindly lets anyone who can reach the server dictate the origin of every absolute URL the app
builds, poisoning canonical tags, emails, redirects and any shared cache in front. Set
`trustProxy: true` only when a proxy you control sets them. `rshono dev` forces it on for its own
localhost-bound proxy.

It governs the browser-facing URL the framework builds — a page's `url` prop and
`getRequestContext().url`. Middleware is handed Hono's `c` and reads `c.req.url` on its own, so where a
middleware needs the public origin, give it `publicUrl(c)` from `@rshono/core/server`.

Leave it off on [`vercel`](/docs/deployment#vercels-request-handoff), where the request already arrives with the scheme
and host the browser used — that platform's edge sets them, and the function cannot be reached around
it. To be precise about that target: the **scheme** is taken from `X-Forwarded-Proto` whether or not
`trustProxy` is set, because there it is not client-supplied. The `Host` header is not part of the
exception. The setting is for a proxy you put in front yourself, which the framework cannot vouch for.

## Response headers and caching

A floor, on every response — including `/_static` assets, which your middleware never sees because they
are served before it:

```
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
X-Frame-Options: SAMEORIGIN
```

Each is set only if nothing already did, so
[`secureHeaders()`](https://hono.dev/docs/middleware/builtin/secure-headers) in `src/server.ts` wins
wherever both apply. That is the way to add the rest — HSTS, COOP, CORP, `Permissions-Policy`.

A **dynamic page** is answered `Cache-Control: private, no-cache` — a page is request-specific by
default, and with no directives a shared cache is free to store one user's page and serve it to the
next. Set your own value from middleware and it is left alone. **Prerendered pages** keep
`public, max-age=300` and a weak `ETag`.

Those two values are not config fields: a cache policy is a per-response header, and `rshono.config.ts`
is compiled into the bundle, so a value you cannot change without a rebuild would be the wrong shape.
Middleware is the interface — and for a **prerendered** page it has to run **after `await next()`**:

```ts
// src/server.ts — a documentation site's prerendered tree, cached for a day
server.use('/docs/*', async (c, next) => {
  await next();
  c.res.headers.set('cache-control', 'public, max-age=86400, stale-while-revalidate=604800');
});
```

After, because the prerendered response is built with `cache-control` in the header bag, which replaces
anything `c.header(...)` prepared before the handler ran. A dynamic page is the easier case: its default
is applied only if nothing else set one, so `c.header(...)` before `await next()` works there. Editing
`c.res.headers` after works for both, leaves the `ETag` alone, and so keeps revalidation at a 304.

Every page response carries `Vary: RSC`, because one URL answers with either an HTML document or a flight
payload depending on that request header — the client runtime sends `RSC: 1` to ask for a payload. A header
of its own rather than `Accept`: a browser's `Accept` string differs by vendor and version, so a CDN keyed on
it would store a copy of a prerendered page per variant, and some shared caches refuse to store such a
response at all.

## CSP

A `Content-Security-Policy` comes from
[`secureHeaders()`](https://hono.dev/docs/middleware/builtin/secure-headers) in `src/server.ts`. With no
arguments it sets the rest of the usual set — HSTS, COOP, CORP, `nosniff`, `X-Frame-Options` — and no
CSP at all:

```ts
// src/server.ts
import { secureHeaders } from 'hono/secure-headers';

server.use(secureHeaders());
```

Put Hono's `NONCE` placeholder in `scriptSrc` and the policy becomes per-request: Hono mints a nonce and
rshono stamps that value onto the bootstrap scripts, the inlined flight payload and dynamically loaded
chunks.

```ts
// src/server.ts
import { NONCE, secureHeaders } from 'hono/secure-headers';

server.use(
  secureHeaders({
    contentSecurityPolicy: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", NONCE],
      styleSrc: ["'self'", "'unsafe-inline'"], // React writes inline styles
      imgSrc: ["'self'", 'data:'],
      connectSrc: ["'self'"],
      // Not covered by default-src, and each closes an injection route of its own.
      baseUri: ["'self'"],
      objectSrc: ["'none'"],
      frameAncestors: ["'none'"],
      formAction: ["'self'"],
    },
  }),
);
```

Two things the framework does for you. React Refresh compiles updates with `eval`, so `script-src` is
widened with `'unsafe-eval'` under `rshono dev` and never in a build — one policy serves both. And while
a nonce is in play the document for a static route is
[rendered per request](/docs/routing#static-rendering), since a prerendered file is fixed bytes and
cannot carry a fresh one. That is decided per request: a policy with no `NONCE` in it keeps its
prerendered documents. The flight payload never carries a nonce and is served from the build either way.

Every directive, `Permissions-Policy` and the reporting headers are in
[Hono — Secure Headers](https://hono.dev/docs/middleware/builtin/secure-headers).

## Errors and redaction

Every error the framework catches goes through [`onServerError`](/docs/hono#error-reporting) and to
`stderr`. Thrown server-action errors are redacted in the production payload — React sends no message or
digest — so return values, not throws, for anything the user should see. The `error` page's `error` prop
is message-only in production, message plus stack in dev.

## No blank screens

Three fallbacks behind the `error` page, so a failure is always readable:

- An **uncaught client-side render error** makes React tear down its root — which here is the whole
  document. The runtime paints a fatal overlay instead: full stack in dev, a generic notice plus a
  reload button in production.
- If **SSR fails before the shell is sent**, the `error` page cannot be reached either, so the framework
  answers with its own visible 500 document. It attaches no client runtime deliberately: the flight
  payload came from the same failed render, and hydrating it would blank the message.
- A **client bootstrap failure** — a truncated or malformed initial payload — is reported and surfaced
  rather than becoming a silent unhandled rejection.

---

<!-- source: https://www.rshono.com/docs/deployment.md -->

---
title: Deployment
description: The settings each platform asks for, four targets behind one interface, and the known limitations.
---

`rshono build` targets one platform. Pick it with `deploy` in the config, `--deploy <name>` or
`RSHONO_DEPLOY`, in that precedence order. The default is `node`. `rshono dev` always runs the Node dev
server whatever you choose.

Each platform below leads with the settings its dashboard asks for, which is what importing a Git
repository puts in front of you. Commands are written for npm — substitute your package manager
(`pnpm build`, `yarn build`, `bun run build`).

## The targets

| `deploy`     | Handoff                          | Assets & prerendered pages                                      | After `build`                               |
| ------------ | -------------------------------- | --------------------------------------------------------------- | ------------------------------------------- |
| `node`       | binds a port                     | from `dist/` on disk                                            | `rshono start`                              |
| `cloudflare` | `{ fetch }` default export       | Workers Assets; prerendered pages read via the `ASSETS` binding | `wrangler deploy`                           |
| `vercel`     | Node `(req, res)` listener       | CDN for assets; prerendered pages inside the function           | `vercel deploy --prebuilt`                  |
| `aws-lambda` | streaming handler (Function URL) | from the deployment package                                     | zip `dist/`, handler `dist/server/main.mjs` |

**Every target streams** — a page's HTML reaches the browser as it renders. That is the bar a new target
has to clear. Bun and Deno run the `node` build through their `node:` compatibility
(`bun dist/server/main.mjs`), so neither needs a preset of its own.

## Node

The default, and what any host that runs a Node process wants: a VPS, a container, or a PaaS such as
Render, Railway, Fly or App Platform. There is no single dashboard, but they all ask for the same four
things.

| Setting             | Value           |
| ------------------- | --------------- |
| Install Command     | `npm install`   |
| Build Command       | `npm run build` |
| Start Command       | `npm start`     |
| Development Command | `npm run dev`   |
| Node.js version     | 22.18 or newer  |

- The host has to hand the process a **`PORT`**, which rshono binds; `HOST` is honoured too and defaults
  to `0.0.0.0`. `PORT=0` means any free port rather than the default.
- `npm start` runs `rshono start`, which runs the build that already exists and never makes one. It
  refuses a build made for another target rather than starting a bundle with no listener in it.
- In a Dockerfile the same pair: `RUN npm run build`, then `CMD ["npm", "start"]`.

## Vercel

Import the repository, then set these under **Settings → Build and Deployment → Build & Development
Settings**. Only the first two need changing.

| Setting             | Value                                                     |
| ------------------- | --------------------------------------------------------- |
| Framework Preset    | **Other**                                                 |
| Build Command       | `npm run build` — Override **on**                         |
| Output Directory    | leave Override **off**                                    |
| Install Command     | leave Override **off** (auto-detected from your lockfile) |
| Development Command | leave empty                                               |
| Root Directory      | the app's directory — repo root unless this is a monorepo |
| Node.js Version     | 22.x or newer                                             |

- **Framework Preset has to be Other.** Vercel ships a Hono preset and detects `hono` in your
  dependencies, so the default guess is wrong for a rshono app and will fight the build.
- **Do not override Output Directory to an empty value.** That is Vercel's documented way to say _skip
  the build step_, and it would ship your repository instead of your app. The build writes
  `.vercel/output` — the function, the static assets and the routing table, a complete deployment — and
  that is what gets served.
- **There is no start command.** The platform invokes the function per request; nothing binds a port,
  and `rshono start` refuses this build.
- **Development Command** only affects `vercel dev`, which this target gains nothing from — run
  `npm run dev`. If you want `vercel dev` anyway it needs `npm run dev -- --port $PORT`, because the
  default under the Other preset is empty and `vercel dev` fails without one.
- **Node.js Version** decides the function's runtime, not just the build's: the build records the major
  it ran on so the app runs the runtime it was tested against.

Deploying from your machine or from CI instead of the Git integration:

```sh
npm run deploy
```

That is `rshono build && vercel deploy --prebuilt --prod`. `--prebuilt` uploads what the build
assembled, so the platform runs no build of its own; drop `--prod` for a preview URL. From CI it also
needs `VERCEL_ORG_ID`, `VERCEL_PROJECT_ID` and a CLI token in the environment.

`npm run preview` answers the production build locally, but note what it is: a **Node** build run here,
because the platform is what runs its own prebuilt output and your machine cannot.

`ctx.url` is correct here without [`trustProxy`](/docs/configuration#proxy-headers) — see
[Vercel's request handoff](#vercels-request-handoff).

## Cloudflare

Deploy as a **Worker**, not a Pages project. Create the Worker, connect the repository, then set these
under **Settings → Builds**.

| Setting                              | Value                                                     |
| ------------------------------------ | --------------------------------------------------------- |
| Build command                        | `npm run build`                                           |
| Deploy command                       | `npx wrangler deploy` — the default                       |
| Non-production branch deploy command | `npx wrangler versions upload` — the default              |
| Root directory                       | the app's directory — repo root unless this is a monorepo |

- **There is no install command or output directory field.** Cloudflare installs dependencies from your
  lockfile, and `wrangler.jsonc` is what says where the build went.
- **Commit `wrangler.jsonc`.** The first build scaffolds one if the project has none — including
  `nodejs_compat`, which the request context needs for `AsyncLocalStorage` — and never touches it again,
  so it is yours to edit after that.
- **Bindings** (D1, KV, R2) arrive as `getRequestContext().env`. They are not available under
  `rshono dev`, which is plain Node — `npm run preview` builds and runs the app in workerd via
  `wrangler dev`, which is the only preview that executes the real thing.

`npm run deploy` does the build and the upload in one step from your machine.

## AWS Lambda

There is no settings page here; the upload is yours to script.

| Step        | Value                               |
| ----------- | ----------------------------------- |
| Install     | `npm ci`                            |
| Build       | `npm run build`                     |
| Package     | `dist/` and nothing else            |
| Handler     | `dist/server/main.mjs`              |
| Invoke mode | Function URL, **`RESPONSE_STREAM`** |

A buffered invoke mode deploys fine and then holds every page until its last byte has rendered, so
`RESPONSE_STREAM` is not optional. CloudFront usually sits in front for `/_static` and `public/`.

Your dependencies are compiled into the bundle for this target, so no `node_modules` is uploaded —
which also means a native addon fails the build here rather than the deploy.

`npm run preview` is the local check, and as on Vercel it is a **Node** build run here rather than an
emulation of the Lambda handler.

## Advanced

### How the build works

Two coordinated Rspack compilers, using native RSC support (`rspack.experiments.rsc`):

- **client** (`target: web`) → `dist/static`: hydration runtime, `'use client'` chunks, CSS.
- **server** (`target: node`) → `dist/server/main.mjs`: a Hono app assembled from your routes, rendered
  through two layers — the RSC layer, with the `react-server` condition, produces the flight payload;
  the SSR layer turns it into an HTML stream with the payload inlined for hydration.

Everything in that bundle that depends on _where_ it runs — binding a port, serving `/_static` and
`public/`, reading a prerendered page, loading `.env` — sits behind a single interface the build resolves
per target. The request-handling code has no platform in it.

In development the CLI watches both bundles and runs the server bundle **in a worker thread**, restarted
per rebuild, with requests gated on readiness so nothing drops across a restart. Client edits hot-apply
via react-refresh; server component edits re-fetch the payload in place. Browser state survives both.

### Prerendered pages are never CDN-served

One URL answers with an HTML document or a flight payload depending on the `RSC` request header, and a
path-keyed CDN cannot choose. The app always handles page URLs. Assets under `/_static` and `public/` do go
straight to the CDN where there is one.

### Your dependencies, per target

In production `dist/server/main.mjs` always has React, Hono and the framework bundled in. What happens to
**your** dependencies is a property of the target:

- On **`node`** a server component's dependencies stay external and resolve from the `node_modules` beside the
  build, which is where the process runs.
- On **`cloudflare`, `vercel` and `aws-lambda`** they are bundled in too. A function is an uploaded directory
  rather than an installed one, so there is no `node_modules` at request time and an external
  `import 'some-package'` would be a cold start that dies on `ERR_MODULE_NOT_FOUND`.
- On **every target**, anything a `'use client'` component reaches is bundled. The `PUBLIC_`-only
  `process.env` view those modules are server-rendered against is applied by a loader, and a loader cannot run
  on a module the bundle only imports by name — left external, a third-party client component would be SSR'd
  against the real environment, leaking whatever it reads and disagreeing with hydration. This costs nothing:
  the same module ships in the browser bundle, so it was always required to be bundleable.

The cost on those three: a dependency that cannot be bundled — a native addon, or one that reads its own
files off disk relative to `__dirname` — fails the **build** rather than the deploy. Reach for the `rspack`
hook in `rshono.config.ts` to keep such a package external, or deploy it to `node`.

A Worker has a further constraint: it resolves no `node_modules` at runtime either way, and a dependency
needing a real `node:` API beyond `nodejs_compat` will not work there at all.

### Vercel's request handoff

The function is a Node `(req, res)` listener, because that is what the Build Output API's `Nodejs`
launcher calls — the whole of its Node contract. The `Request`/`Response` handler shape Vercel documents
elsewhere belongs to its `@vercel/node` builder, which compiles a source file and wraps it, and a
prebuilt upload never runs that. So the handoff converts the request itself.

TLS terminates at the edge and the function is reached over plain HTTP, so the socket reports `http` for
a request the browser made to `https`. `X-Forwarded-Proto` is what actually says which scheme was used,
and the request the app sees is built from it — otherwise `ctx.url` would carry a scheme the app then
redirects to and compares origins against. This needs no
[`trustProxy`](/docs/configuration#proxy-headers): on this target the header is not client-supplied,
since the function is only reachable through Vercel's edge.

### Cloudflare's compatibility date

The scaffolded `wrangler.jsonc` carries a fixed date behind the released wranglers, not the day it was
generated: wrangler bundles the workerd it shipped with, and that binary refuses a date newer than its
own, so a config dated today would deploy fine and break `wrangler dev`.

### Why Lambda@Edge is not a target

CloudFront returns the response as a value rather than a stream, caps a generated origin-request response
near 1 MB, and supports no environment variables, so `getRequestContext().env` would be empty there. All
three are deliberate exclusions rather than gaps.

## Limitations

- **No compression.** It belongs in a proxy, a load balancer or a CDN, and every hosted target already
  does it. `hono/compress` in `src/server.ts` if you need it in-process — read its docs on streaming
  first, because a buffering compressor undoes streamed SSR.
- **No base path.** `siteUrl` must be a bare origin.
- **Wildcard, optional and regex params cannot be prerendered.**
- **The dev-mode proxy does not forward WebSocket upgrades** to a custom sub-app. Production is
  unaffected.
- **Dev source maps embed the original source of `'use server'` modules.** Dev binds to 127.0.0.1 only,
  and production ships no client source maps.

---

<!-- source: https://www.rshono.com/docs/api.md -->

---
title: API reference
description: Every export of @rshono/core, @rshono/core/server and @rshono/core/client, in one place.
---

Three entry points, and which one an import comes from tells you where the code runs. That is most of
what there is to know about the surface.

| Import                | Runs                                 | Holds                                                                      |
| --------------------- | ------------------------------------ | -------------------------------------------------------------------------- |
| `@rshono/core`        | build time, server                   | route and config declaration, and the types pages are written against      |
| `@rshono/core/server` | per request, server only             | the request context, `redirect` / `notFound`, error reporting, `publicUrl` |
| `@rshono/core/client` | browser, from `'use client'` modules | the navigation hook and the boundaries                                     |

`@rshono/core` pulls in no runtime machinery — importing it from server code is free. `@rshono/core/server`
from a `'use client'` module is a mistake: those run in the browser, where no request is bound. Read what
you need on the server and pass it down as props.

These three are the whole public surface — the package's `exports` map lists only them, so there is no
deeper path to import. Everything else is framework plumbing.

All three are **ESM only**: the map declares `import` and `types` conditions and no `require` one, so
`require('@rshono/core')` is `ERR_PACKAGE_PATH_NOT_EXPORTED`. Use `import`, or `await import()` from
CommonJS.

## `@rshono/core`

### Functions

| Signature                            | What it does                                                                                                                                           |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `defineRoutes(config): RouteConfig`  | Declares the app's route table in `src/routes.ts`. Also accepts a bare `Route[]` as shorthand. Cross-checks every page's props against its own `path`. |
| `defineConfig(config): RshonoConfig` | Types `rshono.config.ts`. Identity function — it exists for the autocomplete.                                                                          |

See [Routing](/docs/routing) and [Configuration](/docs/configuration).

### Types

| Type                   | What it describes                                                                                               |
| ---------------------- | --------------------------------------------------------------------------------------------------------------- |
| `PageProps<Path, E>`   | What every page receives: `url`, `params`, `ctx`. Pass the route's path to type `params` key-by-key.            |
| `PageComponent<P>`     | A page: a server component returning `ReactNode` or `Promise<ReactNode>`.                                       |
| `PathParams<P>`        | The `params` record a path pattern implies — `'/users/:id'` → `{ id: string }`. `PageProps` applies it for you. |
| `PageRoute`            | A path rendered by a server component: `path`, `component`, and optional `render` / `staticPaths`.              |
| `EndpointRoute`        | A path served by a Hono handler: `type: 'endpoint'`, `path`, `server`, optional `method` (one or a list).       |
| `EndpointServerModule` | What an endpoint's module must export — a single named `handler`.                                               |
| `Route`                | `PageRoute \| EndpointRoute`.                                                                                   |
| `RouteConfig<TRoutes>` | The object `defineRoutes` takes: `routes`, plus optional `notFound` and `error`.                                |
| `FallbackPage`         | The `notFound` / `error` page shape — a `component` with no path of its own.                                    |
| `ErrorPageProps<E>`    | `PageProps` plus `error`, for the page declared as `error`.                                                     |
| `ErrorPageInfo`        | `{ message, stack? }`. Redacted in production: a generic message, and `stack` is `undefined`.                   |
| `HTTPMethod`           | `'get'` \| `'post'` \| `'put'` \| `'patch'` \| `'delete'` \| `'options'` \| `'all'`. A `HEAD` reaches `'get'`.  |
| `RshonoConfig`         | Every field of `rshono.config.ts`. All optional.                                                                |
| `RspackHookContext`    | `{ isServer, isDev }`, handed to the `rspack` config hook.                                                      |
| `DeployTarget`         | `'node'` \| `'cloudflare'` \| `'vercel'` \| `'aws-lambda'`.                                                     |

## `@rshono/core/server`

Server-only, and request-scoped. See [Pages](/docs/pages) and [Usage](/docs/usage).

### Functions

| Signature                                   | What it does                                                                                                                    |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `getRequestContext<E>(): RequestContext<E>` | The current request's context. Memoised per request. Throws at module load, and while prerendering a `render: 'static'` route.  |
| `redirect(location, status?): never`        | Throws a control signal the framework turns into a redirect. `status` defaults to `303`.                                        |
| `notFound(): never`                         | Aborts the render with a 404 and the app's not-found page.                                                                      |
| `onServerError(handler): void`              | Registers one handler for every error the framework catches. Call it once, at the top level of `src/server.ts`.                 |
| `publicUrl(c): URL`                         | The browser-facing URL for a Hono `Context` — proxy-corrected under `trustProxy`. For middleware, which has no request context. |

`publicUrl` is the one export here meant for `src/server.ts` rather than a component: middleware is
handed Hono's `c` and reads `c.req.url`, the address the server was reached on. Give Hono's own
middleware the browser's origin instead — `csrf({ origin: (origin, c) => origin === publicUrl(c).origin })`.
In a server component or an action, `getRequestContext().url` is the same value, cached per request.

`redirect` and `notFound` never return, so TypeScript narrows away the code after them and you don't
need to `return` the call. Don't wrap either in a `try/catch` that swallows the signal.

Both have to be reached **before the page shell is sent**. A page streams, so the status line goes out as
soon as the shell is ready and HTTP has no take-backs after that: called from a `<Suspense>` boundary that
resolves later, neither can still be a 3xx or a 404. The response is committed as `200 text/html`, a browser
with JavaScript follows the signal through the payload, and a visitor without it stays on the fallback.
Decide in middleware or in the page component body, above the boundary — `rshono dev` warns when a signal
arrives too late.

```tsx
import { getRequestContext, redirect } from '@rshono/core/server';

export default async function Dashboard() {
  const session = getRequestContext().cookies.get('session');
  if (!session) redirect('/login');
  return <Layout>Signed in as {session}</Layout>; // session is defined here
}
```

### `RequestContext`

What `getRequestContext()` returns, and the very same object a page gets as its `ctx` prop. Exported as a type
only — one instance exists per request and application code never constructs it.

Reads are safe anywhere. Writes are not — see [Writes happen before the render](#writes-happen-before-the-render).

| Member                               | What it is                                                                                                                                |
| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `url`                                | The browser-facing `URL`, proxy-header aware. Parsed once and cached.                                                                     |
| `req`                                | Hono's `HonoRequest` — method, headers, query, body readers.                                                                              |
| `params`                             | Matched route params. A page gets these typed as its `params` prop; this is for everywhere else.                                          |
| `env`                                | Process env, merged on a bindings platform with its bindings (which win). See [Environment](/docs/configuration#environment-and-secrets). |
| `var`                                | Typed variables a middleware set with `c.set(…)`.                                                                                         |
| `cookies.get(name)`                  | One cookie, or `undefined`.                                                                                                               |
| `cookies.all()`                      | Every cookie as `{ name: value }`.                                                                                                        |
| `cookies.set(name, value, options?)` | Sets a cookie on the response. **Throws in a page.**                                                                                      |
| `cookies.delete(name, options?)`     | Clears one. Pass the `path`/`domain` it was set with. **Throws in a page.**                                                               |
| `setHeader(name, value, options?)`   | Sets a response header. **Throws in a page.**                                                                                             |
| `hono`                               | The underlying Hono `Context` — the escape hatch for everything not above.                                                                |

What this adds over Hono's own `Context` is a proxy-aware cached URL, an env that merges a platform's
runtime bindings over process env, cookies without a second import, and writes that tell you when they
cannot work. The long tail — `executionCtx.waitUntil()` and whatever Hono adds next — is `ctx.hono`.

Hono's response builders (`redirect`, `notFound`, `json`, `text`, `html`, `body`, `status`, `header`)
are present as stubs that throw and name the right API, because a page returns JSX and the framework
builds the response from it — reaching them through `ctx.hono` bypasses the error without making them
work. They are permanent: the strike-through your editor draws over them comes from a `@deprecated` tag
put there for the strike-through, not because they are going away.

`ctx` cannot be handed to a `'use client'` component — it wraps the live request. Reading it on a
[`render: 'static'`](/docs/routing#static-rendering) page throws, because there is no request at build
time.

### Writes happen before the render

A page streams. By the time its component runs the response head is already committed — on a soft
navigation the flight response is built before the page's first line executes. A header set from there
would land on a full page load and vanish on a soft navigation, so `cookies.set`, `cookies.delete` and
`setHeader` throw inside a page render rather than work half the time.

Set them from a `'use server'` action, which runs before the render:

```ts
'use server';
import { getRequestContext, redirect } from '@rshono/core/server';

export async function login(form: FormData) {
  const ctx = getRequestContext();
  ctx.cookies.set('session', await createSession(form), { httpOnly: true, sameSite: 'Lax', path: '/' });
  redirect('/dashboard');
}
```

Or from middleware, for anything belonging to the page rather than to one mutation — `Cache-Control`,
`X-Robots-Tag`. Middleware and `{ type: 'endpoint' }` routes run **outside** the request context, so
`getRequestContext()` is not available in them; they are handed Hono's `c` instead, which is all they
need:

```ts
// src/server.ts
server.use('/blog/*', async (c, next) => {
  await next();
  c.header('cache-control', 'public, max-age=600, s-maxage=3600');
});
```

| Where                           | Reads   | Writes                                       |
| ------------------------------- | ------- | -------------------------------------------- |
| Pages, nested server components | ✅      | ❌ throws                                    |
| `'use server'` actions          | ✅      | ✅ `ctx.cookies.set(…)` / `ctx.setHeader(…)` |
| Middleware in `src/server.ts`   | via `c` | ✅ `c.header(…)` / `setCookie(c, …)`         |
| `{ type: 'endpoint' }` routes   | via `c` | ✅ same, on the `c` the handler is passed    |

### Types

| Type                 | What it describes                                                                         |
| -------------------- | ----------------------------------------------------------------------------------------- |
| `RequestContext<E>`  | The request context above. `E` is the app's Hono `Env`, which types `var` and `env`.      |
| `EnvVars<E>`         | What `ctx.env` resolves to: `Bindings` merged with `Record<string, string \| undefined>`. |
| `RedirectStatus`     | `301 \| 302 \| 303 \| 307 \| 308`.                                                        |
| `ServerErrorHandler` | `(error, context) => void` — what `onServerError` takes.                                  |
| `ServerErrorContext` | `{ source, request, hono, waitUntil }`, the second argument to that handler.              |
| `ServerErrorSource`  | `'action' \| 'render' \| 'ssr' \| 'request'` — which stage produced the error.            |

An `'action'` error is the one worth wiring up: React sends the client an opaque marker with no message
in production, so a handler is the only place the real error is visible.

`hono` is the request's Hono context, for `hono.var` and `hono.env` — handed over because
`getRequestContext()` is not reachable from the handler. `waitUntil` holds a serverless invocation open
until the report has been sent; see [error reporting](/docs/hono#error-reporting) for what it does per
target.

## `@rshono/core/client`

Every export is itself a `'use client'` module, so a server component can render `AsyncBoundary` directly.
The hook needs a client component.

### Hook

| Signature                          | What it returns                                                   |
| ---------------------------------- | ----------------------------------------------------------------- |
| `useNavigation(): NavigationState` | `{ url, params, router }` — the current location, and the router. |

`url` and `params` come from the server payload during SSR and hydration. After hydration, `url`
follows the browser address, including query and fragment changes on static pages, independently of
page fetching. `params` describes the displayed page until its replacement commits. In a server
component, read request data from `getRequestContext()`.

Browser URL changes are reflected through a React transition. If a URL-dependent component suspends,
already revealed content stays visible until its replacement is ready. The address bar can therefore
change before the suspended content commits; newly mounted Suspense boundaries may show their fallback.

```tsx
'use client';
import { useNavigation } from '@rshono/core/client';

export function NextPage() {
  const { url, router } = useNavigation();
  const page = Number(url.searchParams.get('page') ?? '1');
  return (
    <button disabled={router.pending} onClick={() => router.push(`${url.pathname}?page=${page + 1}`)}>
      Next
    </button>
  );
}
```

`router` holds `push(href)`, `replace(href)`, `back()`, `forward()`, `refresh()` and the `pending` flag.
When the browser can intercept an action, it fetches and applies the page's flight payload in place, so
client state outside the changed subtree survives. Off-site hrefs, and a traversal that leaves the app,
fall back to a full load. Each action returns a promise with a `NavigationOutcome`: `rendered` after the
destination commits, `no-op` if there is no history entry to traverse, or `document-navigation` when a
browser load takes over. A failed or superseded intercepted navigation rejects the promise.

### Components

| Component         | Props                                      | What it does                                                                                     |
| ----------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| `<AsyncBoundary>` | `loading`, `error`, `onError`, `resetKeys` | A Suspense fallback and an error fallback in one wrapper — the common case for an async section. |
| `<CatchBoundary>` | `fallback`, `onError`, `resetKeys`         | Error boundary alone. Omit `fallback` to report and re-throw to the next boundary out.           |

`loading` on `AsyncBoundary` is required — a loading state is the reason to reach for it over
`CatchBoundary`, so showing nothing while loading is an explicit `loading={null}`. `error` is optional:
omit it and throws propagate to the next boundary out or the global error page. A `redirect()` is never
absorbed by either boundary — it's navigation, not failure.

`AsyncBoundary` is scoped to the route: a soft navigation to a different pathname mounts the incoming
route's boundary, so its `loading` state shows while the new data streams, and a same-page update
(`refresh()`, a server action, a query-string change) keeps the content it has already revealed. That
scope is a remount — client state and mount effects under the boundary do not survive a route change — so
a section whose state must outlive navigation wants a bare `CatchBoundary` instead. `CatchBoundary` is not
scoped — pass `resetKeys={[url.pathname]}` to clear its error state on navigation.

### Types

| Type                 | What it describes                                                                                         |
| -------------------- | --------------------------------------------------------------------------------------------------------- |
| `NavigationState`    | `{ url, params, router }` — what `useNavigation()` returns.                                               |
| `NavigationRouter`   | The imperative actions plus `pending`.                                                                    |
| `NavigationOutcome`  | The result of an imperative router action.                                                                |
| `AsyncBoundaryProps` | Props of `<AsyncBoundary>`.                                                                               |
| `CatchBoundaryProps` | Props of `<CatchBoundary>`.                                                                               |
| `ErrorFallback`      | `ReactNode`, or `(error, reset) => ReactNode`. The function form only works from a `'use client'` module. |
