# Fondu > A small meta-framework for full-stack React apps, built on Hono and Vite. It runs on Bun, Cloudflare Workers and Node. # Introduction https://fondu.dev/docs > Fondu is a small meta-framework for full-stack React apps, built on Hono and Vite: how its routes, pages and client fit together. Fondu is a small meta-framework for full-stack React apps, built on [Hono](https://hono.dev) and [Vite](https://vite.dev). It runs on Bun, Cloudflare Workers and Node. ## Routes and pages The files in `app/routes/` are the app's URLs: the file path is the URL. A page's file has its Hono handlers, which run on the server, and the page, a React component: the loader renders it with its props. ```tsx // app/routes/users/[id].tsx: GET /users/7 export const loader = defineHandler.withValidator({ params })(async (c, { params }) => render(c, Show, { user: await getUser(params.id) }), ) // the component's props are the page's props; the browser gets this part of the file alone export default function Show({ user }: { user: User }) { return

{user.name}

} ``` The first request gets the page rendered on the server. From then on, links and forms are plain `` and `
`: Fondu's client asks the same route for the next page and its props as JSON, and React swaps the page in place. There is no API to write for your pages and no client-side router to keep in sync with the server: the routes are the only router. ## Who does what | Part | Done by | | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | HTTP, middleware, CSRF protection, security headers | Hono and its middleware | | Dev server and production build | Vite, with `@hono/vite-dev-server` or `@cloudflare/vite-plugin` | | `routes/`, pages and layouts, the client, forms' errors and flash data, typed pages and URLs, the document, error and static pages | Fondu | So most of what you write on the server is Hono's API, and its docs apply as they are. The pages here cover what Fondu adds. ## Next - [Quick start](https://fondu.dev/docs/quick-start.md): create an app and run it. - [The demo](https://demo.fondu.dev) shows Fondu's features, one page each, on Cloudflare Workers. # Quick start https://fondu.dev/docs/quick-start > Create a Fondu app with create-fondu for Bun, Cloudflare Workers or Node, run it, add a page and build it for production. ## Automatic installation Copy this prompt and paste it into your coding agent. It will guide you through setting up a Fondu app, in a new project or an existing one, and answer your questions along the way. ```text wrap Read https://fondu.dev/docs/quick-start.md, then help me create a Fondu app (or add Fondu to this project). Ask me where it will run (Bun, Cloudflare Workers or Node), set it up as the guide says, and explain each file you create. ``` ## Create an app ```sh title="npm" npm create fondu@latest my-app ``` ```sh title="pnpm" pnpm create fondu@latest my-app ``` ```sh title="yarn" yarn create fondu my-app ``` ```sh title="bun" bun create fondu@latest my-app ``` It asks where the app runs: Bun, Cloudflare Workers or Node (or pass `--target bun`, `--target cloudflare` or `--target node`), and whether to add code checks (or pass `--checks`): oxfmt and oxlint, and VS Code settings that format on save; and whether to make a git repository (`--git`), unless the folder is in one. Then it writes a small app: one page, a layout, the error page, Tailwind CSS, editor snippets and an `AGENTS.md` for coding agents, and installs the dependencies with the package manager you ran it with (`--no-install` leaves that to you). `--yes` takes the defaults for what the options don't say, without asking, except for the target, which has none and must be given: ```sh bun create fondu@latest my-app --target cloudflare --checks --yes ``` ## Run it ```sh title="npm" cd my-app npm run dev ``` ```sh title="pnpm" cd my-app pnpm dev ``` ```sh title="yarn" cd my-app yarn dev ``` ```sh title="bun" cd my-app bun dev ``` The app is at `http://localhost:5173`. Edit the page in `app/routes/index.tsx` and it updates in place; edit its loader and the page gets the new props, without a reload. ## Add a page A page is a route file: its loader, and the page component. Add `app/routes/about.tsx`: ```tsx import { defineHandler, render } from 'fondu' // GET /about: runs on the server export const loader = defineHandler((c) => render(c, About, { team: ['Ada', 'Grace'] })) // the page: the part of the file the browser gets export default function About({ team }: { team: string[] }) { return ( <> About

About

) } ``` `render(c, About, …)` is checked against the page: a missing prop or one of the wrong type is a type error. Link to it with a plain `
` and a URL from `href()`, typed after your routes: ```tsx import { href } from 'fondu/client' export const AboutLink = () => About ``` ## Build ```sh title="npm" npm run build ``` ```sh title="pnpm" pnpm build ``` ```sh title="yarn" yarn build ``` ```sh title="bun" bun run build ``` Then `start` on Bun or Node, or `deploy` on Cloudflare: [Deploying](https://fondu.dev/docs/deploying.md) has the details. ## Next - [Agent skills](https://fondu.dev/docs/skills.md): give your coding agent Fondu's rules and keep your app's own conventions in `AGENTS.md`. - [Project structure](https://fondu.dev/docs/project-structure.md): the files of the app you just created. - [Routes](https://fondu.dev/docs/routes.md), [Pages and props](https://fondu.dev/docs/pages.md) and [Navigation](https://fondu.dev/docs/navigation.md): what you will write most. - Every page of these docs is also Markdown: add `.md` to its URL. [llms.txt](/llms.txt) lists them all. # Agent skills https://fondu.dev/docs/skills > How to install Fondu's agent skill, use it in a task, keep app rules in AGENTS.md, and give agents the docs as Markdown. Fondu's agent skill gives a coding agent the framework's rules before it changes your app. It covers routes, pages, forms, navigation, data loading, rendering, server code and types, with topic references for the details. The [skill source](https://github.com/fondujs/fondu/tree/main/skills/fondu) is kept in the same repository as Fondu and these docs. The skill is instructions for your agent, not a package your app imports. It adds no code to the server or browser. ## Install the skill From your app's root directory, run the [skills CLI](https://github.com/vercel-labs/skills): ```sh npx skills add fondujs/fondu ``` Select the `fondu` skill and the coding agents you use. The CLI installs to the current project by default and handles each agent's skill directory. See its documentation for prerequisites and supported agents. ## Use it in a task Ask your agent to use the `fondu` skill when building or changing a Fondu app. For example: ```text wrap Use the fondu skill and this app's AGENTS.md. Add a contacts page with a server loader and a plain HTML form. Validate the form with one schema on the server and in the browser, preserve entered values when validation fails, and run the app's checks. ``` The skill starts with the framework's model and links to the relevant topic references. The agent should read those references for its task rather than load every topic or invent another way to write a route, form or navigation. Review the resulting code and run your app's checks as usual. Installing a skill does not validate the changes for you. ## Keep app rules in AGENTS.md Use the skill for Fondu's framework rules. Keep your app's own commands, directory conventions, data layer, authentication and UI constraints in `AGENTS.md`. A new app created with `create-fondu` includes that file. For example, an app can specify where domain modules live, which test command to run and which shared UI components must stay unchanged. It does not need to copy all of Fondu's routing and form rules into the same file. [Project structure](https://fondu.dev/docs/project-structure.md) shows one way to organize an app. ## Use it without installing You can give the instructions to an agent for one task without registering a persistent skill. The CLI can print a prompt without installing it: ```sh npx skills use fondujs/fondu@fondu ``` Or ask the agent to read [SKILL.md](https://github.com/fondujs/fondu/blob/main/skills/fondu/SKILL.md) and the topic references it links to. If the agent cannot fetch them, provide those files directly. This supplies the same instructions for the task, but does not make the skill automatically discoverable in later sessions. ## Keep it up to date Check for skill updates when you update Fondu, then review the changes before using them: ```sh npx skills update ``` This command updates installed skills, not your app's `fondu` dependency. ## Give agents the docs Every documentation page also has a Markdown copy: add `.md` to its URL, or use **Copy as Markdown** at the top of the page. For example, [Quick start as Markdown](https://fondu.dev/docs/quick-start.md) contains the setup instructions without page navigation. - [llms.txt](/llms.txt) lists the documentation pages and their Markdown URLs. - [llms-full.txt](/llms-full.txt) contains all of the docs in one file. - The topic references in the skill point back to the docs, which remain the source of truth for Fondu's API. # Project structure https://fondu.dev/docs/project-structure > The files of a Fondu app: vite.config.ts, app/server.ts, the routes directory, the generated types, and one way to organize the rest. ## The files ``` my-app/ ├─ app/ │ ├─ server.ts # the server: export default createApp() │ ├─ routes/ # the file path is the URL │ │ ├─ _middleware.ts # runs for its directory and below │ │ ├─ _layout.tsx # around every page (a directory's _layout.tsx: around its pages) │ │ ├─ _error.tsx # the error page (404, 403, 500…) │ │ ├─ index.tsx # /: its loader and actions, and the page │ │ ├─ users/[id].tsx # /users/:id │ │ └─ api/health.ts # /api/health: server code only │ └─ fondu.gen.d.ts # the generated types (commit it) ├─ package.json # fondu, hono, react, react-dom └─ vite.config.ts # plugins: [fondu({ target: 'node' })] ``` ## `vite.config.ts` `fondu()` is the Vite plugin. It takes the target, `bun`, `cloudflare` or `node`, and a few options more (`progress`, `viewTransitions`, `react`: [API](https://fondu.dev/docs/api.md#fonduvite)): ```ts import fondu from 'fondu/vite' import { defineConfig } from 'vite' export default defineConfig({ plugins: [fondu({ target: 'node' })], }) ``` On Cloudflare, the Cloudflare plugin comes first and runs the Worker in workerd, in development too: ```ts plugins: [cloudflare({ viteEnvironment: { name: 'ssr' } }), fondu({ target: 'cloudflare' })] ``` ## `app/server.ts` The server: `createApp()` returns a Hono app made of `app/routes/`, with CSRF protection, security headers (a Content Security Policy included), one URL per page (`/users/` redirects to `/users`: 301 for GET and HEAD, 308 for other methods, with no option for it) and error pages built in. ```ts import { createApp } from 'fondu' export default createApp() ``` Its options: `document` (the HTML around pages, as in [The document](https://fondu.dev/docs/document.md)), `csrf` and `secureHeaders` (Hono's options, or `false`), and `bodyLimit` (bytes, or `false`). The [API](https://fondu.dev/docs/api.md#createapp) lists them. ## Server code The `.ts` files of `app/routes/`, `app/server.ts`, files named `*.server.ts` and `fondu` itself are server code: browser code must not import them, and the build stops if it does. A page's loader and actions are server code too, in the page's own file: the browser's copy of it is the page alone. [Server and client code](https://fondu.dev/docs/server-and-client.md) explains where each file runs. `package.json` maps `#/*` to `./app/*`, so `import { db } from '#/db/index.server.ts'` works from anywhere in `app/`. ## `app/fondu.gen.d.ts` The dev server and the build write the types of your routes here: they make `href()` typed. A new app ships it. Commit it, so the types are there before the first build (in CI, say); don't edit it. ## Editor snippets A new app has `.vscode/fondu.code-snippets`: type `/route` or `/page` in a new `.tsx` route file, `/loader`, `/action`, `/actions`, `/validated`, `/layout` or `/form` in one, `/api`, `/get` … `/delete` or `/middleware` in a `.ts` file. Edit them freely. ## One way to organize an app Fondu reads `routes/` and the files above; the rest of `app/` is yours, and Fondu only checks that browser code doesn't import server code. Here is one way to arrange it, which [the demo](https://fondu.dev/docs/demo.md) follows. It is an example, not a rule. ``` app/ ├─ routes/ # URLs: their handlers and pages, the layouts ├─ components/ # all UI that isn't a page │ ├─ ui/ # the primitives: buttons, fields, dialogs │ └─ users/ # the parts of the pages in routes/users/ ├─ modules/ # what the app does, a directory per domain, no UI │ ├─ auth/ # auth.server.ts, guards.server.ts │ └─ users/ # users.server.ts, schemas.ts ├─ lib/ # helpers that know no domain: dates, class names └─ db/ # the tables and the client ``` - A route file is short: its handlers call a module, its page puts components together. - A page's own parts are in `components/`, in a directory named like the page's route. - A domain keeps its code together: `modules/users/` has the server code, the schemas its routes validate with and its forms use, and the types of the data it gives pages. - A new file goes where the first answer is yes: a URL, `routes/`; UI, `components/`; about one domain, `modules//`; anything else, `lib/`. # Demo application https://fondu.dev/docs/demo > A tour of the Fondu demo app at demo.fondu.dev: one page per feature, each with the code that makes it work. [demo.fondu.dev](https://demo.fondu.dev) is a Fondu app that shows Fondu's features, one page each, with the code that makes it work. Its source is [apps/demo](https://github.com/fondujs/fondu/tree/main/apps/demo) in the Fondu repository. ## What it shows Its menu is grouped by what you would be doing: - **Routing**: routes and actions, redirects, a page in three languages, the error pages. - **Forms & requests**: forms with validation, file uploads, flash data, HTTP routes for API clients. - **Data loading**: props, shared props. - **Navigation**: links and forms in place, Back, pending state, view transitions, a gallery whose dialog has its own URL (shallow navigation), asset versioning. - **Rendering**: server-side rendering, and pages rendered in the browser only. - **Auth**: an account, with a settings dialog that calls a route with `request()`, and an admin area. Each page says what it demonstrates, which part is Fondu's or Hono's, and which API it uses, so the demo doubles as a set of working examples. ## What it is built with - Cloudflare Workers, with a D1 database through Drizzle ORM - Better Auth for accounts: sign-in, sessions, an admin role - coss ui (Base UI and Tailwind CSS) for the interface - Paraglide JS for the languages The data goes back to its first state every six hours. # Routes https://fondu.dev/docs/routes > How files in app/routes/ become URLs: params, optional segments, loaders, actions, middleware, HTTP routes and calling a route from the browser. ## Files and URLs Every file in `app/routes/` is a route: a page (`.tsx`, `.mdx`) or server code only (`.ts`). Files and directories starting with `_` are not routes (`_middleware.ts`, `_layout.tsx` and `_error.tsx` are what their names say, with those extensions: `_middleware.tsx` stops the app at startup and fails the build), nor are declarations (`*.d.ts`) and tests (`*.test.*`, `*.spec.*`, any extension). A route's path is its URL: | File | URL | | ------------------------- | --------------------------------------- | | `index.tsx` | `/` | | `about.tsx` | `/about` | | `users/index.tsx` | `/users` | | `users/[id].tsx` | `/users/:id` | | `files/[...path].ts` | `/files/:path*`: one or more segments | | `[[lang]]/about.tsx` | `/about` and `/:lang/about` | | `(marketing)/pricing.tsx` | `/pricing`: a `(group)` adds no segment | Where two routes could take a URL, a static segment comes first, then a param with listed values, then any param, then a catch-all: `/users/new` is `users/new.tsx`, not `users/[id].tsx`. A name with any of `[ ] : * { } ?` must be one of the forms above (a param is letters, digits and `_`). `[user-id].tsx`, `[id]x.ts`, `:id.ts` and `a{b}.ts` stop the app at startup, rather than become a literal URL or a wildcard. A param can't be named `query`, `hash`, `method`, `body`, `headers` or `signal`: the first two are `href()`'s options, the other four `request()`'s. A file such as `api/[method].ts` stops the app at startup; rename it (`api/[verb].ts`). The URLs don't change. A catch-all's key is `/files/:path*`, in `href()`, `request()` and the generated types: `href('/files/:path*', { path: 'a/b' })` is `/files/a/b`, its slashes kept. There is no optional catch-all: `[[...path]].ts` stops the app at startup; `index.ts` and `[...path].ts` are its two files. A path starting with `.` is not a route: `routes/.well-known/ping.ts` stops the app at startup and fails the build. Put a file of `/.well-known/` in `public/` (`public/.well-known/security.txt`), or answer it in a catch-all route: `[...rest].ts` matches `/.well-known/ping`, and `href('/:rest*', { rest: '.well-known/ping' })` is its URL. ## Optional segments `[[lang]]` is a segment the URL may leave out: `routes/[[lang]]/about.tsx` answers `/about` and `/de/about`, and the `_middleware.ts` files of its directories run for both. A route has one at most. The types have both URLs: `href('/about')`, `href('/:lang/about', { lang: 'de' })`. ## The values of a param `export const params` lists the values a param takes; any other isn't the route's URL. In a route, or in a `_middleware.ts` for its directory and below (the nearest one counts): ```ts // app/routes/[[lang]]/_middleware.ts export const params = { lang: ['de', 'fr'] } ``` `/de/about` and `/fr/about` answer, `/xx/about` is a 404. The values are URL segments: letters, digits, `-`, `.`, `_`, `~`. A dynamic route beside it keeps the other URLs: with `[slug].tsx` next to `[[lang]]/index.tsx`, `/de` is the language and `/my-post` the slug. ## One file per URL Two files that answer the same URLs stop the app at startup: `index.tsx` and `[[lang]]/index.tsx`, `users/[id].tsx` and `users/[slug].tsx`, `about.tsx` and `(site)/about.tsx`, `about.tsx` and `about.ts`. Only one of them could answer, and maybe without the other's middleware. Routes whose URLs differ by the values of a param list them with `params`. ## Loader and actions A page's route file has its handlers and its page, the default export: ```tsx // app/routes/users/[id].tsx import { back, defineHandler, render } from 'fondu' // GET /users/7 export const loader = defineHandler(async (c) => render(c, Show, { user: await getUser(c.req.param('id')) }), ) export const actions = { // POST /users/7?rename rename: defineHandler(async (c) => back(c)), // POST /users/7?delete delete: defineHandler(async (c) => c.redirect('/users', 303)), } export default function Show({ user }: { user: User }) { return ( <>

{user.name}

…
…
) } ``` - `loader` answers GET and renders the page with its props. Without a loader, the page is rendered on GET with none of its own. - `action` answers POST: the page's one form. - `actions.name` answers `POST ?name`, a form each: `
`. A file has `action` or `actions`, not both; with `actions`, a POST without one of their names is a 404. - A method the route has no handler for is a 405 with `Allow` (`DELETE` to a `.ts` file with `GET`, `POST` and `PUT`: `Allow: GET, HEAD, POST, PUT`), after the directories' middleware, so a `cors()` there answers a preflight. With `action`, a `?name` is ignored. - After an action, answer with a redirect: `back(c)` to the page the request came from, or `c.redirect(url, 303)`. The browser then shows that page. `defineHandler(...middleware, handler)` is Hono's `createHandlers`: `c` is Hono's [Context](https://hono.dev/docs/api/context), so `c.req.param()`, `c.req.query()`, `c.json()` and the rest are there. ## What a route file exports Each kind of file exports what it is for, and nothing else: the app stops at startup with what to do instead. Code they share goes in a file of its own (`app/lib/`, `app/components/`). | File | Exports | | --------------------------- | -------------------------------------------------------------------------- | | `.tsx` | the page (default), `loader`, `action` or `actions`, `prerender`, `params` | | `.ts` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`, `prerender`, `params` | | `.mdx` | its content: an [MDX page](https://fondu.dev/docs/mdx.md) has no handlers | | `_middleware.ts` | its middleware (default), `prerender`, `params` | | `_layout.tsx`, `_error.tsx` | the component (default) | `vite build` checks the names, and the app checks the values at startup: `loader`, `action`, the values of `actions` and the HTTP methods are handlers (`defineHandler(...)`, a function or a list of them), a `_middleware.ts`'s default is a middleware (a function or a list of them), and `prerender` is `true`, `false` or a function. An export that is `undefined` is no export, but for a key of `actions`, which names a form. The browser gets a page's file without its server code: [Server and client code](https://fondu.dev/docs/server-and-client.md). ## What the app refuses What would answer the wrong way stops the app, with a message that says what to write instead. Nothing is ignored. | Refused | Stops | Instead | | ------------------------------------------------------------------------------------------ | ------------------- | -------------------------------------------------------------------------- | | a `.jsx` route, layout or error file | startup | `.tsx`: route files are TypeScript | | `_middleware`, `_layout` or `_error` with another extension (`_middleware.tsx`) | startup, build | `_middleware.ts`, `_layout.tsx`, `_error.tsx` | | a path starting with `.` (`routes/.well-known/ping.ts`) | startup, build | [`public/`, or a catch-all](#files-and-urls) | | a `_error.tsx` in a directory | startup | one error page, `app/routes/_error.tsx`: [Errors](https://fondu.dev/docs/errors.md) | | an export the kind of file does not have (`loader` in a `.ts` file, `prerender` in `.mdx`) | build, startup | [what each file exports](#what-a-route-file-exports) | | an export of the wrong kind (`loader` that is not a handler, `prerender: 'yes'`) | startup | [what each file exports](#what-a-route-file-exports) | | `params` that no route it applies to has as `[name]` or `[[name]]` | startup | [the values of a param](#the-values-of-a-param) | | `params` for a name that a route has as a catch-all (`[...name]`) | startup | `params` lists the values of one segment | | two files for the same URLs | startup | [one file per URL](#one-file-per-url) | | `action` and `actions` in one file | startup | one of them: [loader and actions](#loader-and-actions) | | a file name with route syntax (`[user-id].tsx`, `a{b}.ts`) | startup | [files and URLs](#files-and-urls) | | `[[...path]]`, or two `[[optional]]` segments in one path | startup | [files and URLs](#files-and-urls), [optional segments](#optional-segments) | | a param named `query`, `hash`, `method`, `body`, `headers` or `signal` | startup | rename it: `[verb].ts` | | a route under `/_fondu/`, by its file or by a value listed in `params` | startup | [`/_fondu/` is Fondu's](https://fondu.dev/docs/static-pages.md#how-it-works): move the route | | an `enum`, `namespace`, `import x = …`, decorator or parameter property in a page | build | another module: [Server and client code](https://fondu.dev/docs/server-and-client.md) | | a redirect to `javascript:`, `data:` or `vbscript:` | the request (a 500) | [After an action](https://fondu.dev/docs/forms.md#after-an-action) | | an unknown or mistyped option of `createApp()` or `fondu()` | where it is called | [API](https://fondu.dev/docs/api.md) | ## HTTP routes A route for API clients is a `.ts` file exporting handlers named after the methods: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`. A `.ts` file has no `loader`, `action` or `actions`: those are a page's, and its `GET` and `POST` are the same requests. ```ts // app/routes/api/health.ts import { defineHandler } from 'fondu' export const GET = defineHandler((c) => c.json({ ok: true })) ``` ## Calling a route from the browser For an effect or an event (a dialog's tab, a toggle without a form), `request()` from `fondu/client` calls a `.ts` route, typed by its file: ```tsx import { request, RequestError } from 'fondu/client' const usage = await request('/api/usage') // the GET's c.json() type, as JSON delivers it: a Date is a string const user = await request('/api/users/:id', { id: 42, query: { full: 'yes' } }) await request('/api/settings', { method: 'POST', body: { emails: false } }) try { await request('/api/settings', { method: 'POST', body: { emails: 'no' } }) } catch (error) { if (error instanceof RequestError && error.status === 422) { const data = error.data if (typeof data === 'object' && data !== null && 'errors' in data) showErrors(data.errors) } } ``` What is checked: - the path is a `.ts` route of the app (a page's pattern is not one: a page's data is its props), with its params as `href()` takes them; - `method` is one the file exports, and GET when left out. It is required for any other method, and when the file has no `GET`: a call that names `POST` in its type arguments without `method: 'POST'` is an error, as it would send a GET; - the options are `method`, `query`, `body`, `headers` and `signal`, next to the params: that set is fixed, which is why no param can be named `method`, `body`, `headers` or `signal` (nor `query`); - `query` and `body` are typed by the handler's `withValidator` schemas (a body only for a method other than GET, sent as JSON); `headers` and `signal` pass through; - the answer is what the handler returns with `c.json()`, as JSON delivers it. A handler that answers otherwise (text, a redirect) gives `unknown`. A non-2xx answer throws a `RequestError`, with `status`, `data` (the parsed body, typed `unknown`: narrow it before you read it; a 422's is `{ errors }`) and `response`. A network error is thrown as it is. There is no retry and no cache: use `use()`, an effect or a library of your own, and `AbortSignal.timeout()` for a timeout. `request()` is for the browser: during the server render it throws, as a page's data comes from its loader. ## Validated input `defineHandler.withValidator({ body, query, params })` checks the input with any [Standard Schema](https://standardschema.dev) (Zod, Valibot, ArkType…) and hands the handler the parsed values: ```ts import * as z from 'zod/mini' const params = z.object({ id: z.coerce.number() }) const rename = z.object({ name: z.string().check(z.minLength(1)) }) export const actions = { rename: defineHandler.withValidator({ params, body: rename })(requireUser, async (c, { params, body }) => { await renameUser(params.id, body.name) return back(c) }), } ``` The middleware comes first (up to three; more with `every()` from `hono/combine`), so a guard runs before the body is read. Invalid input goes back to the page with the errors: [Forms and validation](https://fondu.dev/docs/forms.md) has the details. ## Middleware A `_middleware.ts` file runs for every route in its directory and below, outermost first. Its default export is a Hono middleware: ```ts // app/routes/admin/_middleware.ts import { defineMiddleware } from 'fondu' import { HTTPException } from 'hono/http-exception' export default defineMiddleware(async (c, next) => { if (c.get('user')?.role !== 'admin') throw new HTTPException(403) await next() }) ``` `app/routes/_middleware.ts` runs for every request, unknown URLs included: the place to read the session and [share](https://fondu.dev/docs/pages.md#shared-props) what every page needs. A middleware for some handlers only goes in `defineHandler()`, before the handler: `defineHandler(requireUser, (c) => …)`. ## Logging every request in development Hono's `logger()` in `app/routes/_middleware.ts` runs after Fondu's own middleware. It does not see a cross-site POST that the CSRF check refuses with a 403, and for `/users/` (a redirect to `/users`) it logs the 404 from before the redirect. To log every request with its final status, wrap the app `createApp()` returns in an outer Hono app, `logger()` first: ```ts // app/server.ts import { createApp } from 'fondu' import { Hono } from 'hono' import type { Context } from 'hono' import { logger } from 'hono/logger' const app = createApp() // a Worker has an execution context (for `waitUntil`); the other targets throw when it is read const executionCtx = (c: Context) => { try { return c.executionCtx } catch {} } const outer = new Hono() outer.use(logger()) outer.all('*', (c) => app.fetch(c.req.raw, c.env, executionCtx(c))) export default import.meta.env.DEV ? outer : app ``` In development each request and its status go to the terminal; a build exports `app`, as before. ``` <-- GET / --> GET / 200 107ms <-- POST /echo --> POST /echo 303 15ms <-- GET /echo/ --> GET /echo/ 301 1ms <-- GET /nope --> GET /nope 404 1ms <-- POST /echo --> POST /echo 403 2ms ``` - On Bun, if the app sets a `websocket`, export it too: `export default import.meta.env.DEV ? { fetch: outer.fetch, websocket: app.websocket } : app`. - Don't use `outer.route('/', app)`: it drops Fondu's not-found page. Don't use `mount()`: Hono deprecates it. - Keep `app.notFound()` and `app.onError()` on the inner `app`. - The logger prints the query string as it is: leave it out of production, or redact it, if URLs carry secrets. ## Errors Throw Hono's `HTTPException` with a status, or return `c.notFound()`: pages get the [error page](https://fondu.dev/docs/errors.md) with that status, API clients the exception's response (plain text by default). # Pages and props https://fondu.dev/docs/pages > How a page is a React component fed by its loader: props, title and meta tags, shared props and reading the page in a component. A page is a React component: the default export of a route file. `app/routes/users/[id].tsx` is the page at `/users/:id`, and its loader, in the same file, renders it with its props. ```tsx // app/routes/users/[id].tsx import { defineHandler, render } from 'fondu' // GET /users/7, on the server export const loader = defineHandler(async (c) => { const user = await getUser(c.req.param('id')) return render(c, Show, { user: { name: user.name } }) }) // the page: the part of the file the browser gets export default function Show({ user }: { user: { name: string } }) { return ( <> {`${user.name} · My app`}

{user.name}

) } ``` A page can also be an [MDX](https://fondu.dev/docs/mdx.md) file. The parts around pages are [layouts](https://fondu.dev/docs/layouts.md). How the app moves from one page to the next is in [Navigation](https://fondu.dev/docs/navigation.md). ## Props The props are what the loader gives `render()`. They are the page's only data from the server. ```ts render(c, Show, { user }) render(c, Show, { user }, { status: 201 }) // another status ``` - `render()` is type-checked against the component: a missing prop, or one of the wrong type, is an error. - The props travel as JSON. A `Date` arrives as a string, so the page types it `string`. A `Map`, a `Set` or a function can't be sent: typing a prop that way is an error. [Type safety](https://fondu.dev/docs/type-safety.md) has the details, and `AsJson` to type a page's props from the data's own type ([Props from your data](https://fondu.dev/docs/type-safety.md#props-from-your-data)). - The props are written into the page's HTML and JSON: anyone who can see the page can read them. Send what the page shows (`{ name: user.name }`), not whole records. - A route file renders its own page only. To use another route's page, make it this file's default export too: `export { default } from './index.tsx'`. A page without a loader is rendered on GET with no props of its own. ## Title and meta tags A page renders its own ``, `<meta>` and `<link>` tags where it likes; React moves them into `<head>`, on the server too (a tag in a Suspense boundary that resolves later is sent in `<body>`). A title is one string, hence the template literal above. ```tsx <> <title>{`${post.title} · Blog`} ``` What every page shares (the charset, icons, fonts) goes in [the document](https://fondu.dev/docs/document.md). ## Shared props Props every page gets, such as the signed-in user, are set once in a middleware with `share()`: ```ts // app/routes/_middleware.ts import { defineMiddleware, share } from 'fondu' export default defineMiddleware(async (c, next) => { const user = await currentUser(c) share(c, { auth: { user: user && { name: user.name } } }) await next() }) ``` A shared value can be a function: it runs only when a page renders, not for API requests. Pages and layouts read shared props with `usePage().props`. [Type safety](https://fondu.dev/docs/type-safety.md) shows how to type them. ## A slow prop A page is sent with all its props, so a slow one holds it. To leave it out, render the page without it and ask for it from the browser: a `.ts` route gives the data, and the page calls it with `request()`. Put the `.ts` route next to the page, in the same directory, so the same `_middleware.ts` guards both: ``` app/routes/dashboard/ ├─ _middleware.ts # the sign-in check: guards index.tsx and stats.ts ├─ index.tsx # /dashboard └─ stats.ts # /dashboard/stats ``` A `.ts` route is guarded only by the `_middleware.ts` files above it. Nothing in the page protects it: a `.ts` route outside the directory is open to anyone who asks for its URL. ```ts // app/routes/dashboard/stats.ts import { defineHandler } from 'fondu' export const GET = defineHandler(async (c) => c.json(await loadStats())) ``` ```tsx // app/routes/dashboard/index.tsx import { defineHandler, render } from 'fondu' import { request } from 'fondu/client' import { useEffect, useState } from 'react' export const loader = defineHandler((c) => render(c, Dashboard, { user: currentUser(c) })) export default function Dashboard({ user }: { user: User }) { const [stats, setStats] = useState() useEffect(() => { const ask = new AbortController() // an error shows as "not available"; leaving the page aborts the request request('/dashboard/stats', { signal: ask.signal }).then(setStats, () => setStats(null)) return () => ask.abort() }, []) return ( <>

{user.name}

{stats === undefined ?

Loading…

: stats === null ?

The stats are not available.

: } ) } ``` The document has the loading state (`undefined`) and so has a page without JavaScript. The error state (`null`) is for a failed request, and the abort is for a page left before the answer. What decides the status or a redirect is awaited in the loader, as before. A promise as a prop of `render()` (`{ stats: loadStats() }`) throws, as JSON would send it as `{}`: `await` it. A promise inside a prop is not checked. ## Reading the page in a component `usePage()` from `fondu/client` returns the page on the screen, in any component: | Field | Is | | ----------- | ------------------------------------------------------------------------------------------- | | `component` | the page's id: its route file's path in `app/routes/`, without the extension (`users/[id]`) | | `props` | the page's props, with the shared props and `errors` | | `url` | the page's URL (path and query) | | `flash` | the data an action left for this page with `flash()`, shown once | Its type is `Page` (`Page` for the props you give it: `usePage()`). ```tsx import { usePage } from 'fondu/client' export function Greeting() { const { props } = usePage() return props.auth.user ?

Hello, {props.auth.user.name}

: null } ``` # Navigation https://fondu.dev/docs/navigation > How links and forms change pages in place with no router: navigate(), shallow navigation, view transitions, pending state and full page loads. The first request for a page gets HTML, rendered on the server. After that, Fondu's client takes over the app's links and forms: it asks the server for the next page's props as JSON and swaps the page in place. The layouts stay mounted, with their state, and the browser doesn't reload. There is no router to set up and no special link component: links are ``, forms are ``. Without JavaScript, they work the same way, as plain links and forms. ## Links Link to a page with a plain ``, and build its URL with [`href()`](https://fondu.dev/docs/type-safety.md), which is typed after your routes: ```tsx import { href } from 'fondu/client' export function UserLink({ user }: { user: { id: number; name: string } }) { return {user.name} } ``` When the link is clicked, the client loads `/users/7` in place. The new page starts at the top, or at its `#fragment` (`/docs#setup`). A query and a fragment are `href()`'s too: `href('/search', { query: { q }, hash: 'results' })`. The page's code is loaded before the click, once the pointer rests on the link or a touch starts on it, so the click has less to wait for. The data of a static page is asked for then too (its file, which runs nothing, used by the clicks of the next 30 seconds); another page's data is asked for at the click, and its loader runs for a visit only. Nothing is loaded ahead when the browser's data saver is on. A link to the page on the screen can say so with `aria-current`, which CSS can style (`a[aria-current='page']`): ```tsx const { url } = usePage() const to = href('/users') return Users ``` The client takes a click only when it is a link to one of the app's pages, as the files in `app/routes/` define them. The browser handles every other link, as it would without Fondu: | Link | Handled by | | --------------------------------------------------------------- | --------------------------- | | a page of the app: `/users/7` | the client, in place | | a `#fragment` of the current page: `#setup` | the browser, scrolls to it | | a file of the site: `/llms.txt`, `/report.pdf` | the browser, loads the file | | an HTTP route (a `.ts` file): `/api/health` | the browser | | a URL no route answers: `/nope` | the browser, shows the 404 | | another site | the browser | | with `target` (`_blank`…), `download`, or Ctrl, ⌘, Shift or Alt | the browser | | without `target`, in a page whose `` isn't `_self` | the browser | | an SVG ``, or an `` | the browser | ### A full page load A link without its own `target` has the document's ``, as in the browser: `_blank` there opens every such link in a new tab, and the client leaves the click alone. A `target="_self"` on the link itself overrides it. Links in an SVG (``) and image maps (``) are always the browser's. A form is the same: with no `target` of its own, and a submitter with no `formtarget`, it has the ``, and one that isn't `_self` is submitted by the browser. To make a link to a page load as a whole document, without the client, add `target="_top"`. In a page that isn't in a frame, it opens in the same tab, as any link, but the browser loads it: ```tsx Admin ``` Use it when the next page needs a fresh document, such as a page of another ``, or one whose scripts must run again. In code, `loadDocument(url)` does the same. A catch-all page route (`docs/[...slug].tsx`) covers every URL below it, files included. A link to a file there, `/docs/manual.pdf`, takes `download` or `target="_top"`, so the browser loads the file. ## Navigating in code `navigate()` from `fondu/client` goes to a URL as a link to it would: ```tsx import { href, navigate } from 'fondu/client' navigate(href('/orders', { query: { page: 2 } })) ``` - A page of the app loads in place, in a new history entry. - `{ replace: true }` replaces the current history entry instead, so Back skips it. - `{ keep: true }` shows the answer as `reload()` does: the page keeps its state (a focused input, what was typed) and the scroll position, and nothing is announced. The loader still runs for `url`. If another page answers, it is shown as any navigation's, from the top. - `{ transition: true }`, or `{ transition: ['zoom'] }` to add types, animates the navigation ([View transitions](#view-transitions)). `false` opts out where `viewTransitions` is on. With `keep`, the page stays and does not transition unless it opts in like this. - Any other URL loads as a document: `mailto:` and other sites too. A `javascript:` URL throws an `Error`, in `navigate()` and in `loadDocument()`. ### Search as you type An input whose value goes into the URL, and a loader that answers the results. Without `keep`, each new query would mount the page anew: the input would lose its focus and what was typed meanwhile. ```tsx import { defineHandler, render } from 'fondu' import { href, navigate } from 'fondu/client' import { useRef, useState } from 'react' export const loader = defineHandler((c) => { const q = new URL(c.req.url).searchParams.get('q') ?? '' return render(c, Search, { q, results: findProducts(q) }) }) export default function Search({ q, results }: { q: string; results: string[] }) { const [value, setValue] = useState(q) const timer = useRef>(undefined) const change = (next: string) => { setValue(next) clearTimeout(timer.current) timer.current = setTimeout( () => navigate(href('/search', { query: { q: next } }), { replace: true, keep: true }), 250, ) } return ( <> change(event.target.value)} />
    {results.map((name) => (
  • {name}
  • ))}
) } ``` `replace` makes one history entry for the search, not one per letter. A navigation in flight is aborted by the next, so a fast typist sees only the last answer. Why not `request()` from an effect: the URL holds the search, so Back, a reload and a shared link all work, and the loader is the one place the results are computed. | Export | Does | | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `navigate(href, { replace?, keep?, transition? })` | goes to `href` as a link would; `keep`: the page keeps its state and scroll, as `reload()` does; `transition`: a [view transition](#view-transitions) | | `navigate(href, { shallow: true, ... })` | changes this page's URL to a page URL of the app, with no request; `replace?`, no `keep`, no `transition` ([below](#shallow-navigation)) | | `closeShallow(to)` | closes what a shallow navigation opened, one step: Back, or `to` in place of this entry | | `loadDocument(url)` | loads `url` as a document (a full page load) | | `reload()` | asks for the current page's props again; state and scroll stay | ## Forms A `` is sent by the client too, and its answer is shown in place. When the answer is the same page (back with validation errors, or `back(c)`), the page is updated where it is: the scroll position and what was typed stay. When it is another page, it is a new entry in the history. A GET form to a page of the app is the client's too: its fields become the query. A GET form to a `.ts` route is the browser's, as a link to one is. [Forms and validation](https://fondu.dev/docs/forms.md) covers actions, errors and pending states. ## Scroll positions | After | The page is | | ------------------------------------------------------------------------ | --------------------------------------- | | a link, or `navigate()` | at the top, or at the URL's `#fragment` | | Back or Forward | where it was when you left it | | a reload | where it was when you left it | | a form's answer at the same URL, `reload()`, or `navigate()` with `keep` | where it is | | a shallow navigation, and Back or Forward between the entries it shares | where it is | The positions of the last 50 history entries are kept, in `sessionStorage` too, so a reload puts the page back where it was. Back and Forward show the page at once, as it was left, then put the server's fresh page in its place. The pages kept for this are in memory only, and they are all forgotten once a form is sent, as the form may have changed them (or signed the user out). ## Shallow navigation Some state belongs in the URL without loading another page: an open dialog or drawer, a selected item, a tab. A shallow navigation changes the URL of the page on the screen to any page URL of this app, and asks for nothing. The pathname, query and `#fragment` may change. The loader does not run; the page keeps its component, props, state and scroll. ```tsx import { navigate } from 'fondu/client' navigate('?item=7', { shallow: true }) // a new history entry navigate('?item=8', { shallow: true, replace: true }) // this entry's URL changes navigate('#settings/profile', { shallow: true }) ``` In markup, mark the link with `data-shallow`: ```tsx Order 7 ``` A plain left click on it is a shallow navigation. A click with Ctrl, Cmd, Shift or Alt, or a link with `target` or `download`, is the browser's, as for any link. The URL must be a page of this app, using the same route check as an ordinary link. Shallow links are not prefetched: nothing will be asked for. Without JavaScript every link is a plain link, so its own route loads. A document load at `/orders?item=7` has the drawer open, and the click only skips the request. - `navigate(url, { shallow: true })` throws for another origin or a URL that is not a page of this app; the error names the URL. A `data-shallow` link to such a URL is an ordinary browser link. - `shallow` and `keep` do not go together: a shallow navigation keeps the page anyway. TypeScript and the runtime both refuse it. - Before the app has started, `navigate(…, { shallow: true })` is a document load. - While a visit is being put on the screen (its URL is in the address bar, its page is not shown yet), a shallow navigation is an ordinary one: it supersedes that visit, as any navigation does. ### What the page has `usePage().url` follows the address bar: its path and query. The component and props do not. They are the loader's answer for the URL that got the page, so read what the path or query holds from `url`. A shallow navigation also drops the page's `flash` and `errors`: they belonged to the answer before it. ```tsx import { usePage } from 'fondu/client' const { url } = usePage() const item = new URL(url, 'http://localhost').searchParams.get('item') ``` A `#fragment` is not in `url`. Read it with `useSyncExternalStore` on `hashchange`. A shallow navigation to a new `#fragment` dispatches a `hashchange`, as the browser's own does: ```tsx import { useSyncExternalStore } from 'react' const subscribe = (notify: () => void) => { addEventListener('hashchange', notify) return () => removeEventListener('hashchange', notify) } const useHash = () => useSyncExternalStore(subscribe, () => location.hash, () => '') // '' on the server ``` Back and Forward between two shallow entries that differ in both the query and the `#fragment` may not fire `hashchange` (browsers fire it only when the rest of the URL is the same). Read `location.hash` on `popstate` too if that matters. A shallow `#fragment` is not a fragment navigation of the browser. The page does not scroll to the element it names, and `:target` does not follow it. For that, use a link without `data-shallow`: a link to a `#fragment` of the page on the screen is the browser's. ### A dialog or a drawer The URL holds the open state. `closeShallow()` closes it: ```tsx import { closeShallow, navigate, usePage } from 'fondu/client' export default function Orders({ orders }: { orders: Order[] }) { const { url } = usePage() const id = new URL(url, 'http://localhost').searchParams.get('order') const index = orders.findIndex((order) => String(order.id) === id) const next = orders[(index + 1) % orders.length] return ( <> {index >= 0 && ( closeShallow(url)}>

{orders[index].name}

)} ) } ``` - `closeShallow(to)` closes one level, and never leaves the page. When the current entry was pushed by a shallow navigation, it goes Back, to the entry below. Otherwise (a document loaded at this URL, a reload, an entry that was replaced) it replaces the current entry with `to`, a URL of this page, with no request and no new entry. Pass the URL without the state, as `usePage().url` has it. - Switching between items inside an open drawer uses `replace`, so the drawer is one history entry: one close, or one Back, returns to the page under it. - Overlays nest, one level per close: a tab opened over a drawer is closed first, then the drawer. - A second `closeShallow()` before the first one's Back has landed does nothing, so a double click closes one level. - The browser's own `#fragment` entries are not shallow entries. A native `#fragment` link clicked over an open drawer adds an entry that `closeShallow()` replaces, as it replaces any other. If the drawer needs data the list does not have, ask for it with `request()` from a `.ts` route. A form in the dialog is posted as any form. Its answer at the same page (back with errors, or `back(c)`) keeps the `#fragment` on the screen, so the dialog stays open, with its errors or its result. The entries that shared the page keep sharing it with the answer's props: closing the dialog asks for nothing more. ### A gallery at an item's own URL The list can open a photo in a dialog at `/photos/7`, while that URL's route renders the photo's own page: ```tsx import { closeShallow, href, usePage } from 'fondu/client' export default function Gallery({ photos }: { photos: Photo[] }) { const { url } = usePage() const path = new URL(url, 'http://localhost').pathname const photo = photos.find((photo) => href('/photos/:id', { id: photo.id }) === path) return ( <> {photos.map((photo) => ( {photo.title} ))} {photo && closeShallow(href('/photos'))} />} ) } ``` One URL serves both: a dialog opened from the gallery, the photo's page on a reload, a shared link or a new tab. The gallery has the photo's data already; the photo's own route serves direct loads. No special layout or history handling is needed. ### Back and Forward The entries that show the same page share it: the one that got the page, those added by shallow navigations, and the browser's own `#fragment` entries. Back and Forward between them change `url` and nothing else. No request is made, and the state stays. A visit still on its way is given up, as with any Back. Once another page is shown, the group is left: Back or Forward into one of its entries is an ordinary visit to that URL. For `/photos/7`, it loads the photo's own page, not the gallery's dialog. A form's answer for the page on the screen keeps the group: the same component at the same pathname, even if the query or fragment differs. All the entries that shared the page now share the answer's props; Back and Forward between them still change `url` without a request. Flash is not shown again. An answer from another component, or a redirect to another pathname, starts a new group instead. Other answers from the server on a shallow entry belong to that entry alone. They end the sharing, and the other entries become normal ones: Back to them asks, as it does for any page. This is the case for: - `reload()`, asked at the entry's URL, so the loader sees its path and query; `reload()` at another page's URL shows that page, rather than keeping the gallery or dialog. A browser reload of a shallow URL is a document load, and the entries before it are documents of their own. A close that goes Back to one of them loads it. ### A prerendered page A [prerendered page](https://fondu.dev/docs/static-pages.md) is a file made without a query. Once it has hydrated, its `usePage().url` has the query of the address bar, so a state in the query works on a direct load, as it does after a click. The loader did not see that query: it ran at build time. Whatever a page must have for a query, a prerendered page cannot get from its loader. ## View transitions A navigation can animate between two pages, with the browser's View Transition API. Each navigation opts in on its own. A link, with `data-transition`: ```tsx Photo 7 ``` - A value adds types of your own, separated by spaces: `data-transition="zoom fade"`. A bare attribute adds none. (React writes `` as `data-transition="true"`, which means the same.) - A form takes the same attribute: ``. - In code, `navigate()` takes `transition`: `true`, or the types to add. ```ts navigate('/photos/7', { transition: true }) navigate('/photos/7', { transition: ['zoom'] }) ``` A navigation that opted in runs its commit inside `document.startViewTransition()`: the old page is captured, the new page is put on the screen and scrolled where it belongs, and the browser animates between the two. It is the browser's API around Fondu's own commit. The animation is CSS (`::view-transition-*`), and there is nothing to add to a page. Without `document.startViewTransition`, a navigation is as it was. ### Every navigation by default An app where most navigations animate sets the default in `vite.config.ts`: ```ts fondu({ target: 'node', viewTransitions: true }) ``` A navigation that shows another page then transitions: a link, a form, `navigate()`, and Back and Forward. One opts out with `data-transition="false"` or `transition: false`. A page that stays does not transition: `navigate()` with `keep` (search as you type), `reload()`, and a form's answer at its own URL. `navigate(url, { keep: true, transition: true })` opts in. A shallow navigation never transitions. The option sets the default and nothing else: the code is in the client either way, and a link can opt in without it. ### Types Each transition has types, for CSS to pick the animation: the direction first, then the navigation's own. | Type | For | | -------------------- | ---------------------------------------------------------------------------------- | | `navigation-forward` | a new history entry (a link, a form, `navigate()`), and Forward | | `navigation-back` | Back | | `navigation-replace` | an entry replaced (`navigate(…, { replace: true })`, a link to the page's own URL) | | your own | those of `data-transition="zoom fade"` or `transition: ['zoom']` | In a browser that has no `:active-view-transition-type()`, the transition is untyped. ```css @media (prefers-reduced-motion: no-preference) { /* the photo in the list and the photo on its page are one element to the browser */ .photo { view-transition-name: photo; } /* the new page comes in from the right, and from the left for Back */ :root:active-view-transition-type(navigation-forward)::view-transition-new(root) { animation: slide-in-right 250ms ease-out; } :root:active-view-transition-type(navigation-back)::view-transition-new(root) { animation: slide-in-left 250ms ease-out; } /* a link with data-transition="zoom": the photo takes its time */ :root:active-view-transition-type(zoom)::view-transition-group(photo) { animation-duration: 500ms; } @keyframes slide-in-right { from { transform: translateX(2rem); opacity: 0; } } @keyframes slide-in-left { from { transform: translateX(-2rem); opacity: 0; } } } ``` ### Back and Forward An entry that a navigation reached with a transition remembers it, with the types it added, in `history.state` (so it survives a reload). Back from that page and Forward to it run the transition again, with the types and the direction: a link with `data-transition="zoom"` is `navigation-forward zoom`, and Back from the page it opened is `navigation-back zoom`. Of the two entries a traversal goes between, the one that was reached later is the one that matters: Back from it, and Forward to it. When Back or Forward skips several entries, it is the later of the two it goes between. - Back from a page reached without a transition does not animate. - With `viewTransitions: true`, every Back and Forward to another page animates: with the remembered types if the entry has them, with the direction alone if it does not (a page reached by a navigation that opted out). - A navigation that replaces an entry (`replace: true`, a link to the page's own URL) with a transition stores its types in that entry, and one without a transition clears what the entry had. No transition is made for a page that stays: `reload()`, `navigate()` with `keep` (unless it has `transition`), a form's answer at its own URL. A swipe back that the browser animates itself has none either. A shallow navigation (`data-shallow`, `shallow: true`) never transitions, whatever else is on it. ### What to know - The scroll position is restored inside the transition, so the new snapshot is of the page where it is scrolled, and the page's title is announced when it is on the screen. - While the browser captures the old page, and while a page's modules load, the old page is still on the screen under the new URL. A newer navigation in that time wins: the older one commits nothing. - React's `` component does not animate Fondu's navigations: Fondu's commit is not a React transition, and the component sets nothing for it (not even its `name`). It works as it does anywhere for your own `startTransition` updates. A shared element between two pages is a `view-transition-name` in CSS, on the same element in each page. - The document runs one view transition at a time. A navigation and a transition of your own (a React `` in a `startTransition`, or your own `document.startViewTransition()`) cut each other short: the newer one skips the older. Two elements with the same `view-transition-name` skip the transition too. - Reduced motion is your CSS: put the animations in `@media (prefers-reduced-motion: no-preference)`, as above. ## While a page loads `useNavigation()` from `fondu/client` says what is on its way, from a click or a submit until the next page is on the screen: | Field | Is | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `state` | `'idle'`; `'submitting'`, a form's POST; `'loading'`, any other (a link, `navigate()`…); `'failed'`, a form's POST that could not be sent (offline…) | | `to` | where to: a path with its query and fragment (`/users/7?tab=posts`), or `null` when idle | | `form` | the form being sent (a GET form's too), or `null` | ```tsx import { useNavigation } from 'fondu/client' export function Spinner() { const { state } = useNavigation() return state === 'loading' || state === 'submitting' ? … : null } ``` `failed` lasts until the next navigation starts; the form stays as it was, to send again. A GET that fails is loaded as a document instead, where the browser says what is wrong. Code that read "not `idle`" as "pending" compares with `loading` and `submitting`. A navigation that takes longer than 350 ms also shows a thin progress bar at the top of the page. Configure it in `vite.config.ts`: ```ts fondu({ target: 'node', progress: { color: 'var(--brand)', // default: the page's text color delay: 500, // ms before it shows (default 350) forms: false, // not for forms' submissions: their buttons show it }, }) ``` `progress: false` removes it, when your own indicator uses `useNavigation()`. ## Other answers - Screen readers announce the new page's title after each navigation. - An answer that isn't a page, such as a file or a proxy's error page, is shown as the browser would show it. - A redirect to another site (`c.redirect('https://…')`) loads that site. - After a deploy, the next navigation from a tab opened before it loads the page as a document, so the browser runs the new version. Protocol notes: `X-Fondu-Location` (with status 409) means "load this URL as a document". `X-Fondu-Redirect` means "follow this path in place", as a navigation. # Layouts https://fondu.dev/docs/layouts > How a _layout.tsx wraps the pages below it and stays mounted: nesting, route groups, choosing the layouts of a page, code splitting and non-route files. A layout is the part of the page that stays the same from one page to the next: a header, a sidebar, a footer. It stays mounted while navigations move between the pages it wraps, so its state (a scroll position, an open menu) is kept. ## `_layout.tsx` A `_layout.tsx` in a directory of `app/routes/` wraps every page below it. Its default export is a component that renders the page as `children`: ```tsx // app/routes/_layout.tsx: around every page import type { ReactNode } from 'react' import '../styles/app.css' export default function Layout({ children }: { children: ReactNode }) { return ( <>
…
{children}
) } ``` The root layout is around every page, the [error page](https://fondu.dev/docs/errors.md) too: the place to import the app's CSS. Layouts nest with the directories, outermost first: ``` app/routes/ ├─ _layout.tsx # around every page ├─ index.tsx └─ docs/ ├─ _layout.tsx # around the docs pages, inside the one above ├─ intro.mdx └─ routes.mdx ``` `/docs/intro` is rendered inside `_layout.tsx`, then `docs/_layout.tsx`. Pages written in [MDX](https://fondu.dev/docs/mdx.md) get their layouts the same way. Read the page and its props in a layout with `usePage()` (`fondu/client`). ## Different layouts for different parts A `(group)` directory adds no segment to the URLs: its pages share a layout without sharing a path. ``` app/routes/ ├─ _layout.tsx # the styles, around everything ├─ (marketing)/ │ ├─ _layout.tsx # the site's header and footer │ ├─ index.tsx # / │ └─ legal/ │ ├─ _layout.tsx # a narrow column, inside the marketing layout │ ├─ terms.tsx # /legal/terms │ └─ privacy.tsx └─ admin/ ├─ _layout.tsx # the dashboard's sidebar, not the site's header └─ users.tsx # /admin/users ``` A part that should not sit inside a layout goes in a directory beside it: `admin/` is not in `(marketing)/`. The pattern for most apps: the root `_layout.tsx` is the shell (the CSS, providers), and the site's chrome (header, footer) is in `(site)/_layout.tsx`. A page that should render alone, such as a sign-in or a print view, sits outside `(site)/`: ``` app/routes/ ├─ _layout.tsx # the shell: CSS, providers ├─ (site)/ │ ├─ _layout.tsx # the header and footer │ ├─ index.tsx # / │ └─ about.tsx # /about └─ sign-in.tsx # /sign-in, without the header and footer ``` ## Code-split with their pages A layout is in the JavaScript of its pages only: a visitor of the home page doesn't download the docs' sidebar. The client loads a page's `_layout.tsx` files with it, found by the page's route file. ## Files that are not routes A file in `app/routes/` whose name starts with `_`, or that is in a directory whose name does, is not a route: it has no URL, and it is not in the generated types. Besides `_layout.tsx`, a component used by the pages of one directory can live there too, as `_toc.tsx` or `_parts/toc.tsx`. Tests (`*.test.*`, `*.spec.*`) are not routes either. # Forms and validation https://fondu.dev/docs/forms > How a plain HTML form posts to an action: validation with one schema on the server and in the browser, errors, flash data, files and the body limit. ## A form A form is a plain ``. It posts to an action, which validates the input and answers, usually with a redirect back: ```tsx // app/routes/contacts/new.tsx import { back, defineHandler, flash } from 'fondu' import type { Errors } from 'fondu/client' import { contactSchema } from '#/modules/contacts/schemas.ts' // POST /contacts/new export const action = defineHandler.withValidator({ body: contactSchema })(async (c, { body }) => { await addContact(body) flash(c, { message: 'Contact added' }) return back(c) }) export default function NewContact({ errors }: { errors: Errors }) { return ( {errors.email &&

{errors.email}

} ) } ``` A form without an `action` posts to its page's URL. A page with several forms gives each its own: `actions = { add, remove }` in the route file, `
` in the page. With JavaScript, Fondu's client sends it without a page load: back at the same URL, the page is updated where it is. Without, it is an ordinary form post, with the same result. ## After an action An action answers with a redirect, so that a reload doesn't send the form again: - `back(c)`: back to the page the form was on. With JavaScript, that page is updated in place. - `c.redirect(url, 303)`: to another page, a file or another site. A URL with the scheme `javascript:`, `data:` or `vbscript:` is refused: the request gets a 500, `fondu: a redirect to "javascript:" is refused`, and the error is logged. - `flash(c, { message: 'Saved' })` before either: data for the next page only, in `usePage().flash`, for a "Saved" message say. Flash data and errors travel in a short cookie. The cookie comes back from the client, so what a page reads from `usePage().flash` is not trusted: anyone can write it. Fondu ignores a cookie whose `flash` is not an object or whose errors are not strings, and shows the flash once. Keep the values short: a cookie over about 4 KB is dropped by the browser, so Fondu leaves out the flash data first, then the errors that don't fit, and logs a warning. ## Invalid input When the body or the query doesn't fit its schema, the handler doesn't run: - a page's form (a POST, PUT, PATCH or DELETE) gets a redirect back to the page it came from, and that page gets the errors in its `errors` prop, one message per field (`{ email: 'Invalid email' }`). What was typed stays in the form. - a GET (or HEAD) with an invalid query has no form to go back to, and a redirect could loop: a visitor gets the error page with status 422. - an API client gets 422 and `{ errors }`. Params that don't fit are a 404: the URL names nothing. A check the schema can't make, such as an address already taken, throws `ValidationError` from the handler, with the same result: ```ts import { ValidationError } from 'fondu' if (await emailTaken(body.email)) throw new ValidationError({ email: 'This address is taken' }) ``` The errors are one object for the page: two forms on a page keep theirs apart by their fields' names. ## The same schema in the browser A schema is plain code: a page can import it, from any module that isn't [server code](https://fondu.dev/docs/server-and-client.md), and check the form before it is sent. It is still a plain form: when the check passes, Fondu's client sends it; when it doesn't, the submit is stopped and the errors shown. The server checks again, and what only it can (an address already taken). `useForm(schema)` from `fondu/client` does it. It reads the fields as the server does (`tags[]`, `user[name]`), so the browser's check and the server's agree: ```tsx import { useForm } from 'fondu/client' import { contactSchema } from '#/modules/contacts/schemas.ts' export default function NewContact() { const { form, field, errors, submitting } = useForm(contactSchema) return ( {errors.email &&

{errors.email}

}
) } ``` | Field | Is | | ------------- | ------------------------------------------------------------------------------------------------- | | `form` | for the `
`: checks it on submit; an invalid one isn't sent, its first field to fix focused | | `field(name)` | for a field: its `name`, `aria-invalid`, and its checks as it is left and changed | | `errors` | the server's (the page's `errors` prop), and the browser's: `errors.email`, `errors['user.name']` | | `submitting` | this form is being sent | | `failed` | this form could not be sent (offline…): it stays, to send again | - A field is checked as it is left for another with something typed, and again as it changes while it is wrong, so a fixed field loses its message. Not as it is left for the submit button: the message would move the button from under the pointer. - A server's error stays until its field is checked again. Back with the server's errors, the first field to fix gets the focus. - Any [Standard Schema](https://standardschema.dev) works in the browser if it checks synchronously. Without a schema, `useForm()` gives the server's errors, `submitting` and `failed` only. - A schema that returns a promise (an async rule, such as a taken email) gives no verdict in the browser: the form is sent as it is, and the server's errors come back as any other. In development, one warning per schema says so (`fondu: this schema has an async rule, so useForm leaves it to the server`). The server keeps async schemas: put that rule in the action's schema, and the browser still checks the rest. - `errors` has the server's keys: a field's path, joined with dots (`user[name]` is `user.name`). - With a schema, `form` sets `noValidate` on the ``: the schema's messages replace the browser's own (`required`, `type="email"`). Without JavaScript the browser's checks stay. - Your own handlers go next to it: `onChange={(e) => { field('email').onChange(e); … }}`. - Without JavaScript, the form is sent as it is, and the server's check answers. ## While it is sent The form being sent has `aria-busy="true"` until the answer is on the screen, however it was sent (a click, Enter, `requestSubmit()`): its buttons can show it with CSS alone, and assistive technology says it. ```css form[aria-busy='true'] button[type='submit'] { opacity: 0.6; cursor: progress; } ``` In a component, `useForm().submitting` says it, or `useNavigation().form`, the form being sent: ```tsx import { useNavigation } from 'fondu/client' export function SubmitButton(props: ComponentProps<'button'>) { const ref = useRef(null) const { form, state } = useNavigation() const sending = state !== 'failed' && form !== null && form === ref.current?.form return