(null)
const { form, state } = useNavigation()
const sending = state !== 'failed' && form !== null && form === ref.current?.form
return
}
```
A form that could not be sent (offline, the connection lost) stays as it was, and `useForm().failed` says so until the
next navigation starts:
```tsx
{failed && Not sent. Check your connection and try again.
}
```
The progress bar shows for submissions too; `fondu({ progress: { forms: false } })` leaves it to the buttons.
## Files and nested fields
The body is one object whether it comes as JSON (`application/json` or any `application/*+json`, such as
`application/merge-patch+json`) or as form fields. Form fields named like `user[name]` or `tags[]`
become nested objects and arrays, files are `File` objects, and empty file inputs are left out. A body that can't be
one object is a 400: JSON that doesn't parse, a name that is both a value and an object (`a` and `a[b]`), names nested
deeper than 32, and more than 10,000 entries (files and empty file inputs count).
A body of any other type (`text/plain`, or none) is a 415 Unsupported Media Type; a request with no body is `{}`.
`withValidator({ query })` reads the query the same way: `?tag=a&tag=b` and `?tag[]=a` are lists, `?user[name]=Ada` is an
object, and `?a=1&a[b]=2` is a 400. A query carries text, so a schema that wants a number or a boolean parses it
(`z.coerce.number()`), and a list field is written `tag[]=a` (`href()` does), as `?tag=a` is a string. A `useForm` that
sends a GET form reads its fields this way too.
Only a `multipart/form-data` form sends its files (`enctype`, or a submitter's `formenctype`, which comes first). In any
other form (URL-encoded is the default) a file input sends its file name, empty when no file is chosen. `useForm`
checks the form as it is sent: your schema sees a `File`, or that string.
## The body limit
The body is read whole, in memory, files too, and it takes about twice its size while it is parsed. A body over 10 MB
is answered 413 by default, with the error page. The limit is in the chain of each route that takes a body (POST, PUT,
PATCH, DELETE), after the `_middleware.ts` of its directories and before its action or handler. The error page has the
shared props they set, and a request they refuse is never read; for that, a middleware must not read the body. A GET and
a URL that is no route are never read. A client that disconnects mid-upload is not logged as an error. `createApp({ bodyLimit: 25 * 1024 * 1024 })`
in `app/server.ts` changes the limit for the app, and `false` removes it. Raise it for the whole app only a little: every request can use
it. On Cloudflare Workers an isolate has 128 MB of memory, shared by the requests it serves
([limits](https://developers.cloudflare.com/workers/platform/limits/)). Served by Node or Bun directly over HTTP/1.1,
Firefox and Safari may show a failed request rather than the 413 page when a large body is refused unread; behind
Cloudflare, every browser gets the page.
A route that should take less adds Hono's `bodyLimit` in its `_middleware.ts`; a directory's middleware cannot raise
the app's limit.
```ts
// app/routes/avatars/_middleware.ts
import { bodyLimit } from 'hono/body-limit'
export default bodyLimit({ maxSize: 1024 * 1024 }) // 1 MB, then 413
```
A route that should take more has no way to raise the app's limit, so the app has none, and the root middleware sets
one for each path. The 413 must be an `HTTPException` (Hono's default `onError` throws one that carries its own plain-text response), so
that it gets the error page, with the props the root middleware shared above it.
```ts
// app/server.ts
export default createApp({ bodyLimit: false })
```
```ts
// app/routes/_middleware.ts
import { defineMiddleware, share } from 'fondu'
import { bodyLimit } from 'hono/body-limit'
import { HTTPException } from 'hono/http-exception'
const limit = (maxSize: number) =>
bodyLimit({
maxSize,
onError: () => {
throw new HTTPException(413)
},
})
const photos = limit(50 * 1024 * 1024)
const rest = limit(1024 * 1024)
export default [
defineMiddleware(async (c, next) => {
share(c, { site: 'Acme' }) // what every page needs, the error page too
await next()
}),
defineMiddleware((c, next) => (c.req.path.startsWith('/photos') ? photos : rest)(c, next)),
]
```
### Large files
Cloudflare refuses a request over its own limit with a 413 before your app has a say: 100 MB on the Free and Pro plans,
200 MB on Business, more on Enterprise
([limits](https://developers.cloudflare.com/workers/platform/limits/)). Under it, a large file is better
not sent through the app at all. The browser sends it straight to storage, and the form sends only where it went.
With R2, the app gives the browser a presigned URL to `PUT` the file to. The Workers binding can't make one: sign it
with the S3 API ([presigned URLs](https://developers.cloudflare.com/r2/api/s3/presigned-urls/)), in a `.ts` route.
```ts
// app/routes/api/upload-url.ts
import { defineHandler } from 'fondu'
export const POST = defineHandler(async (c) => {
const key = crypto.randomUUID()
const url = await presign(key, 'image/jpeg') // yours, with aws4fetch or the AWS SDK: a signed PUT URL
return c.json({ key, url })
})
```
In the browser, `request()` from `fondu/client` gets the URL (typed), then the file goes to R2 with the platform's
`fetch()`. The form's action receives only the key.
```tsx
import { request } from 'fondu/client'
async function upload(file: File) {
const { key, url } = await request('/api/upload-url', { method: 'POST' })
const res = await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'image/jpeg' }, // the type that was signed
body: file,
})
if (!res.ok) throw new Error('Upload failed')
return key // a hidden input of the form: the action stores the key
}
```
The bucket needs a CORS rule, or the browser refuses the request, valid URL or not
([CORS](https://developers.cloudflare.com/r2/buckets/cors/)): the app's origin, the `PUT` method, and the headers the
browser sends.
```json
[
{
"AllowedOrigins": ["https://example.com"],
"AllowedMethods": ["PUT"],
"AllowedHeaders": ["Content-Type"]
}
]
```
## CSRF
`createApp()` turns on Hono's CSRF protection: a request that changes something (a POST, a form) must come from the
app's own origin. The app's own forms do; nothing else is needed.
# Errors
https://fondu.dev/docs/errors
> How Fondu answers unknown URLs, wrong methods and thrown errors: the error page, plain text for API clients, development reports and your own handler.
## The error page
An unknown URL, a `throw new HTTPException(403)` or an error in a handler: a page request gets `app/routes/_error.tsx`
with the status, inside the root layout, with the shared props. API clients get plain text, or the `HTTPException`'s
own response. A page request is a navigation of Fondu's client or a request that accepts `text/html`, as a browser's
document load does. Any other request (`curl`, a `fetch()` call) is an API client's.
```tsx
// app/routes/_error.tsx
export default function ErrorPage({ status }: { status: number }) {
return {status === 404 ? 'Page not found' : 'Something went wrong'}
}
```
The shared props are what the middleware shared before the error: the root `_middleware.ts`'s, and those of the route's
directories when the error came after them. If a middleware itself fails, the error page has only what was shared before
it failed.
A method the route has no handler for (`DELETE` to a route with `GET` and `POST`, `POST` to a page with only a
`loader`) is a 405 with an `Allow` header listing the route's methods (`HEAD` with `GET`; `OPTIONS` is not added). It
gets the error page too, with `status` 405; a URL that matches no route stays a 404. A directory's `cors()` still
answers a preflight, as its middleware runs first.
A response that `Accept` chooses (the error page or plain text, a redirect back or a 422) has `Vary: Accept`, added to
the `Vary` it has, so a shared cache keeps the forms apart.
A request over the body limit (413) gets the error page too, with the shared props: the limit runs after the
middleware of the route's directories. A CSRF refusal (403) is plain text, "Forbidden": Hono's CSRF protection answers it with its own response,
before any middleware.
Without `app/routes/_error.tsx`, plain text for everyone. An error page that itself fails to render gets plain text
too, with its status and the failure in the log (in the browser: "Something went wrong" and the failure in the
console): a page is never left blank.
A page that throws as it renders in the browser gets the error page with status 500 in its place, inside its layouts
(the error in the console); a layout that throws, the error page alone. The next page is shown as usual.
## In development
A 500 is a report of the error instead: the message, and the stack with your files first; a navigation loads it as a
document. Fix the code and save: the report reloads.
An error before any handler runs, in a route that throws as it is imported, is Vite's: its overlay shows it, as a
whole page, and the next edit reloads the page.
## Answers from outside the app
An answer that isn't a page, such as a proxy's 502 or a CDN's timeout page, comes from what stands in front of the
app: Fondu answers navigations with pages, errors included. The browser shows it as it would without JavaScript: a
link's loads the URL as a document, a form's replaces the page.
## Your own handling
`createApp()` returns a Hono app: its `notFound()` and `onError()` replace Fondu's.
```ts
const app = createApp()
app.onError((error, c) => {
report(error)
return c.text('Something went wrong', 500)
})
export default app
```
# Server and client code
https://fondu.dev/docs/server-and-client
> Where each file of an app runs, on the server, in the browser or both, how server code is kept out of the bundle, and what stops the build.
Every file in `app/` runs on the server, in the browser, or in both. Where a file runs decides what it can do, and
whether it ends up in the JavaScript your visitors download.
## Where each file runs
| Files | Runs | In the browser's bundle |
| ------------------------------------------------------------ | ----------------------------------------------------- | ----------------------- |
| `.ts` files of `app/routes/`, `app/server.ts`, `*.server.ts` | on the server only | never |
| a page's `loader`, `action`, `actions` (in its `.tsx`) | on the server only | never |
| pages, layouts, their components | on the server (the first render), then in the browser | yes |
| anything else they import (a schema, a type) | wherever it is imported | if a page imports it |
The browser's bundle is everything the pages and layouts import, directly or not. Each page is a chunk of its own,
loaded when it is visited.
## A page's route file
A `.tsx` route file is both: its handlers run on the server, its page on both. The browser gets a copy of the file
without its server code: `loader`, `action`, `actions`, `prerender` and `params` are removed, then the imports and
top-level declarations only they used, and so on until none is left.
```tsx
// app/routes/users/[id].tsx
import { defineHandler, render } from 'fondu' // removed: only the loader uses it
import { getUser } from '#/modules/users/users.server.ts' // removed
import { Avatar } from '#/components/avatar.tsx' // kept: the page uses it
const select = (u: User) => ({ name: u.name }) // removed: only the loader uses it
export const loader = defineHandler(async (c) => render(c, Show, select(await getUser(c))))
export default function Show({ name }: { name: string }) {
return
}
```
The copy is made from the source, before TypeScript and JSX are compiled, so what the page uses is read as you wrote it:
a JSX name (``, ``) counts, a type does not (`typeof loader` in a type is fine). The copy does not
follow an `enum`, a `namespace`, `import x = …`, a class with a parameter property or a decorator: a route file that has
one fails the build, and it goes to another module. The tsconfig of a new app has `"erasableSyntaxOnly": true`, so the
editor flags it as you type; add it to an older app's. A type-only import or export (`import type`, `import { type Row }`,
`export type`) is removed too: in a page's route file, either spelling of a type import is fine. Source maps carry the copy, not the file: with `build.sourcemap`, and in development,
`sourcesContent` holds the page without its loader. The server runs the whole file.
What is left is what the page uses, so a server module it still imports (a helper the page calls too) stops the
build, as any other: declare what the server and the browser share in a module of its own. A page imports from
`fondu/client`: `fondu` is the server's. Server code may import `href()` from `fondu/client` too (for a redirect); `request()`, `navigate()`
and the other calls for the browser throw there.
## Server code
The `.ts` files of `app/routes/`, `app/server.ts` and files named `*.server.ts` are server code: they read the database,
the secrets, the session. If a page or a component imports one, even through another file, the build stops and names
the import:
```
fondu: /app/db/index.server.ts is server code (routes/*.ts, server.ts, *.server.ts) and cannot be imported by browser code
```
Name a module `*.server.ts` when it must never reach the browser, and import it from handlers and other server files.
A type is not code: a page can take one from a server file with `import type`, which is removed with the rest of
TypeScript before the build looks at the imports.
```tsx
// app/components/users/card.tsx
import type { UserSummary } from '#/modules/users/users.server.ts'
```
Write the whole import as `import type`. With `verbatimModuleSyntax`, which a new app's `tsconfig.json` has,
`import { type UserSummary } from …` leaves an empty import of the file behind, and the build stops at it.
## Code for both
Pages and their components run twice: on the server for the first render, then in the browser. So they must not touch
`window` or `document` while rendering (do it in an effect), and they can't reach
the server's resources: what they need comes as props.
A module with no secrets, such as a validation schema, can be shared: a route validates with it, a page checks the
same rules before sending.
## Route modules load with the app
Every file of `app/routes/` is imported when the app starts (in development, on the first request), so what a route
imports at the top runs for every page, not only for its own. Keep a heavy dependency out of the start: import the
entry you need (one icon's module, not the whole icon library), or import it in the handler:
```ts
export const GET = defineHandler(async (c) => {
const { renderPdf } = await import('#/lib/pdf.server.ts') // loaded on the first request to this route
return c.body(await renderPdf(), 200, { 'Content-Type': 'application/pdf' })
})
```
## Editing in development
The dev server updates what an edit changes, without reloading the page where it can:
- A page or a component (`.tsx`, `.mdx`): React Fast Refresh, the page's state kept.
- A route's handlers, or code they import: the page asks for its props again (`reload()`), its state and scroll
kept. A page's file is both: its page is refreshed, its props asked for again.
- `app/server.ts`, or code only it imports: the page reloads, as the document around it changed.
- An app that fails to load (a route that throws as it is imported): Vite's overlay shows the error, as a whole page;
the next edit reloads it.
The dev server doesn't watch `node_modules`: after updating a dependency, Fondu included, restart it, or it keeps
running the version it loaded.
## Props are public
Props are the only way data goes from a route to a page, and they are written into the HTML and the JSON of the page:
anyone who can see the page can read them. Send what the page shows, not whole records: `{ name: user.name }`, not a
user row with its password hash.
## Environment variables and secrets
- On Cloudflare: `import { env } from 'cloudflare:workers'` in server code, for variables, secrets and bindings,
typed by `cf-typegen`.
- On Bun and Node: `process.env`, in server code. In development, Fondu loads `.env`, `.env.local`, `.env.development`
and `.env.development.local` into it; a variable already set (by the shell, the host) is not replaced. In production
the server reads them: a Node app's `start` script has `--env-file-if-exists=.env` (`.env` alone; the flag needs
Node 22.9 or later, and a new Node app's `engines` says 22.12), and Bun reads `.env`, `.env.production` and `.env.local`
itself.
- `import.meta.env.VITE_*` is written into the browser's bundle by Vite: only for values that are public anyway.
# Type safety
https://fondu.dev/docs/type-safety
> How Fondu types page props, URLs, handler input and request() calls from your own files, so a renamed prop or a moved route fails at compile time.
Fondu checks the seams between the server and the browser at compile time: what a route sends to a page, the URLs
your pages link to, the input your handlers read, and what the browser sends to a `.ts` route with `request()` and gets
back. Rename a prop, move a route or change a schema, and TypeScript points
at every place that no longer fits, before anything runs.
## Where the types come from
There is nothing to declare twice. Each type has one source, and the rest follows from it:
| Source | Checks |
| ------------------------------------- | --------------------------------------------------------------------- |
| a page component's props | `render(c, Page, props)`: every prop is there and fits |
| the files in `app/routes/` | `href('/users/:id', { id })`: the URL exists, its params, its actions |
| a route's query schema | `href('/search', { query })`: the query the route takes |
| a handler's schemas (`withValidator`) | the `body`, `query` and `params` the handler receives |
| a `.ts` route's handlers | `request()`: the params, `query` and `body` it takes, and its answer |
| declarations next to your middleware | `share()`, `flash()`, `usePage()`, `c.get()` |
The dev server and the build write the routes' types into `app/fondu.gen.d.ts` as your files change; commit it.
## Page props
The component is the source: its parameter's type is what `render()` takes for that page.
```tsx
// app/routes/users/[id].tsx
export const loader = defineHandler(async (c) => {
const user = await getUser(c.req.param('id'))
return render(c, Show, { user }) // error: canEdit is missing
})
export default function Show({ user, canEdit }: { user: User; canEdit: boolean }) { … }
```
## URLs
`href()` from `fondu/client` takes the URL patterns of `app/routes/`, and a route's actions as `?name`:
```tsx
href('/users/:id', { id: 7 }) // '/users/7'
href('/users/:id?rename', { id: 7 }) // '/users/7?rename': actions.rename
href('/users/:id') // error: the param is missing
href('/user/:id', { id: 7 }) // error: no such route
```
`query` and `hash` add a query string and a fragment. When the route checks its query with `withValidator({ query })`
(its loader, a `.ts` file's `GET`, or the action), `query` is typed by that schema; otherwise it takes any values.
```tsx
// app/routes/search.tsx
const query = z.object({ q: z.string(), page: z.optional(z.coerce.number()) })
export const loader = defineHandler.withValidator({ query })(async (c, { query }) => …)
// anywhere
href('/search', { query: { q: 'ada', page: 2 }, hash: 'results' }) // '/search?q=ada&page=2#results'
href('/search') // error: the schema requires q
href('/users/:id', { id: 7, query: { tab: 'posts' } }) // '/users/7?tab=posts': no schema, any query
```
`href()` writes the query as `withValidator({ query })` reads it: a list as `tag[]=a` (one item too), an object as
`user[name]=Ada`, a list of objects or lists with indexes (`rows[0][a]=1`). Numbers and booleans are written as text (`2`,
`true`) and read back as strings, so a schema parses them. An empty list or object is left out and reads back as
absent: give such a field a default in its schema.
A param can't be named `query` or `hash`: they are `href()`'s (and `method`, `body`, `headers` and `signal` are `request()`'s). A value that is `undefined` or `null` is left out, and
`z.coerce.number()` takes any value (a string or a number), as the URL carries it as text.
A redirect takes `href()` too: `return c.redirect(href('/users/:id', { id: user.id }), 303)`.
## Handler input
`defineHandler.withValidator()` types the handler's input from its schemas, as they parse it: with
`z.coerce.number()`, `params.id` is a `number`.
```ts
const idParams = z.object({ id: z.coerce.number() })
export const loader = defineHandler.withValidator({ params: idParams })(async (c, { params }) => {
params.id // number
})
```
Any [Standard Schema](https://standardschema.dev) library works: [Forms and validation](https://fondu.dev/docs/forms.md).
## Calls to a route
`request()` from `fondu/client` is typed by the route file it calls. The path must be a `.ts` route of the app, its
params are the ones `href()` takes, `query` and `body` are typed by the handler's `withValidator` schemas, and the answer
is what the handler returns with `c.json()`, as JSON delivers it. [Routes](https://fondu.dev/docs/routes.md#calling-a-route-from-the-browser)
has the details.
## Shared props, flash data and context values
What a middleware sets is typed where it is set, by declaring Hono's and Fondu's own interfaces:
```ts
// app/routes/_middleware.ts
declare module 'hono' {
interface ContextVariableMap {
user: User | null // c.set('user', …), c.get('user')
}
}
declare module 'fondu' {
interface Register {
shared: { auth: { user: { name: string } | null } } // share(), usePage().props
flash: { message?: string } // flash(), usePage().flash
}
}
```
`share()` and `flash()` then take only those, and `usePage()` returns them. If `render()` overrides a shared prop, its
value must fit both the page and the layout, even when the page accepts arbitrary keys. For a union, don't distinguish
a branch by the absence of a shared key: middleware can add it. For example, if `mode` is shared as `'text' | 'count'`,
use `mode: 'text'` and `mode: 'count'` on the two variants and pass the matching `mode` with their data.
## What crosses as JSON
Props travel to the browser as JSON, so a page's prop types are what it receives: a `Date` arrives as a string, a
`Map` or a `Set` as `{}`, and `undefined` fields are left out. `render()` checks both sides of that:
```tsx
// app/routes/posts/[slug].tsx
export default function Show({ post }: { post: { title: string; publishedAt: string } }) { … }
```
```ts
render(c, Show, { post: { title, publishedAt: new Date() } }) // fine: JSON makes the Date a string
```
A page that types a prop as `Date`, `Map`, `Set` or a function is an error at `render()`, as the page would get
something else. Anything with a `toJSON()` passes for what that returns.
## Props from your data
A page declares its props, and `render()` checks every writer against them. To write that type once, from the type of
the data, use `AsJson` from `fondu`. It is `T` after the JSON round trip, the way a page receives it:
- `Date`, or anything with `toJSON()`, becomes what that returns (a `Date` is a `string`).
- `undefined` properties become optional, and `undefined` in an array becomes `null`.
- Functions and symbols are left out of objects, and are `null` in arrays.
- `Map`, `Set` and other objects with no own data become `{}`.
- A `bigint` is a type error, as `JSON.stringify` throws on it.
- Unions, tuples and readonly arrays keep their shape.
These rules are what `AsJson` guarantees. The exact shape of the error for a `bigint` is not part of it: it may change.
`render()` takes what becomes the page's type, so a page that declares `AsJson` gets a `Row` from the loader, with
its `Date`. Nothing is converted by hand, and the page never types a `Date`.
### A whole row
```tsx
// app/routes/contacts.tsx
type Contact = AsJson
export default function Contacts({ contacts }: { contacts: Contact[] }) { … }
```
Props are public, and a whole row sends every column. Use this for a table the page shows in full, and select columns
for the rest.
### A selected shape
Write the query as a function in the route file, and take the page's type from its result:
```tsx
// app/routes/contacts.tsx
const listContacts = () =>
db.select({ id: contacts.id, name: contacts.name, createdAt: contacts.createdAt }).from(contacts)
export const loader = defineHandler(async (c) =>
render(c, Contacts, { contacts: await listContacts() }),
)
type Props = { contacts: AsJson>> }
export default function Contacts({ contacts }: Props) { … }
```
`typeof listContacts` is in a type position, so the browser's copy of the file does not keep the query (or `db`):
[Server and client](https://fondu.dev/docs/server-and-client.md#a-pages-route-file). When an action or another route needs the query too,
move it to a module named `*.server.ts` and import its type in the page with `import type { listContacts } from …`:
that import is removed with the other types.
### A form's values
For the values a form starts with, take the type from the form's schema. The action's `body` is already typed by
`withValidator`.
```tsx
type Values = z.infer
export default function NewContact({ values }: { values: Values }) { … }
```
### Where it stops
`AsJson` goes by the declared type. It can't tell that a getter of a class, or the `message` of an `Error`, is not own
data: convert such a value before it is a prop. It needs a concrete type, as a `bigint` is found by looking inside it:
for a type parameter `T` that is not resolved yet, TypeScript reports an error.
## Setup
None beyond `tsconfig.json`: a new app has it, and ships `app/fondu.gen.d.ts` for its first route. Keep the file
committed, so a fresh clone or CI has the types before the first build.
Without that file, `href()` and `request()` take no path: the error says `Run vite dev or vite build to generate
app/fondu.gen.d.ts`. An app with no routes gets the same error.
### A library, or a package with no app
A package that uses `fondu/client` without routes of its own opts out: any string is a path.
```ts
// types.d.ts
declare module 'fondu' {
interface Register {
routes: string
}
}
```
# Server-side rendering
https://fondu.dev/docs/ssr
> How pages are rendered on the server and hydrated in the browser, how the document streams with Suspense, and how to turn server rendering off.
## How it works
A document request (a first visit, a reload, a link opened in a new tab) is rendered on the server, in the same
process as the routes: the HTML of the page, the tags it renders for ``, and the page data. The browser shows it
at once, then React hydrates it. The navigations after that are rendered in the browser.
## Streaming
The document is streamed. The first bytes are the start of the document, the tags the page renders for ``
(``, ` `), the page data and the page's shell: everything outside a `` boundary. A boundary whose
data is not there yet shows its fallback, and is sent when it resolves; React puts it in place with a small script.
The loader decides the answer, so the status, the headers, redirects and cookies are sent with the first byte, before
anything renders later. A navigation gets its JSON as before, and a [static page](https://fondu.dev/docs/static-pages.md) waits for every
boundary.
What renders later is the page's to handle. Tags a boundary renders (``, ` `) land in ` `, and the
first `` of the document wins. Without JavaScript the fallback stays. A component that suspends outside any
boundary holds the whole page until it resolves, so wrap what is slow in ``.
There is no separate render server to run, on any target: on Cloudflare the render is part of the Worker.
## Turning it off
With `withoutSsr()`, the pages of some routes are rendered in the browser only. In a `_middleware.ts`, for a
directory:
```ts
// app/routes/admin/_middleware.ts
import { withoutSsr } from 'fondu'
export default withoutSsr()
```
In the root `app/routes/_middleware.ts`, for the whole app. Or in one handler: `defineHandler(withoutSsr(), (c) => render(c, Dashboard))`.
A page rendered in the browser only is empty until its JavaScript runs, on a reload too, so the browser can paint a
blank frame first. Keep the server render for pages whose first paint matters.
## Browser-only parts
A component that needs the browser (`window`, a chart library) can stay on a server-rendered page, rendered once it is
mounted: after an effect, or with `useSyncExternalStore` and a server snapshot of `null`.
## When the server render fails
If a page throws while rendering on the server, Fondu logs the error and sends the page to render in the browser
instead, so the visitor still gets it. Fix it all the same: the page loses what the server render gives it, a fast
first paint and HTML for search engines.
A `` boundary that throws after the shell is sent is rendered in the browser instead, and logged. The status
was sent with the shell, so it stays as it was.
When the visitor leaves (the request is aborted), the render stops, so a boundary that never settles holds nothing. This is
not logged.
# Static pages
https://fondu.dev/docs/static-pages
> How to write pages as static files at build time (SSG): choosing the pages, what a static page can be, and the headers it is served with.
Fondu can write pages as static files at build time: static site generation (SSG). They are served without rendering
them again, and navigations keep working. On Bun, Cloudflare Workers and Node; this site is built that way.
## Choosing the pages
A route opts in with `export const prerender`; a `_middleware.ts` sets it for its directory and below. The nearest
setting wins. The build prerenders when any route or `_middleware.ts` exports `prerender` (even as `false`), and not
otherwise: there is no option in `vite.config.ts`, and `fondu({ prerender: true })` fails with a message saying so.
```ts
// app/routes/(marketing)/_middleware.ts: every page below
export const prerender = true
// app/routes/(marketing)/contact.tsx: not this one
export const prerender = false
// app/routes/blog/[slug].tsx: a dynamic route lists its pages' params
export const prerender = () => posts.map((post) => ({ slug: post.slug }))
```
`app/routes/_middleware.ts` with `export const prerender = true` makes every page static. Only pages are prerendered: a `.ts` route under it is still answered by the server, and one that exports `prerender` itself fails the build.
## How it works
The build starts the server it built (`node` or `bun dist/server/index.js`, or the Worker in wrangler), asks it for the pages
to prerender, and writes each twice in the client build:
- as a document, `docs/intro.html`, for a first visit;
- as its page object, `_fondu/pages/docs/intro.json`, for navigations: Fondu's client reads it instead of asking
the Worker.
It is asked for once the pointer rests on a link to the page, so the click has nothing to wait for.
Fondu keeps one prefix for its own URLs, `/_fondu/`: the page objects (`/_fondu/pages/…`) and, while the build runs, its list
of pages (`/_fondu/prerender`). An app has no route under it: one that a listed `params` value puts there stops the app at
startup. In development, Fondu also serves `/@fondu/dev.css`: the CSS the layouts import, in the document so a server-rendered page
is styled at first paint.
Then:
- On Cloudflare, Workers Static Assets serve the files without running the Worker.
- On Bun and Node, the built server serves the files before the app (Hono's `serveStatic`).
The server still answers every other URL, a page that isn't static or one that doesn't exist. In development, it
answers all of them.
On Cloudflare, the Worker the build starts runs locally, as in development: `.dev.vars` overrides the `vars` of
`wrangler.jsonc`. A static page is written with those values and deployed as it is, so a value meant for your
machine, a `localhost` site URL say, ends up in production. Keep what static pages show out of `.dev.vars`.
## What a static page can be
A static page is the same for everyone. It is rendered once, with every Suspense boundary resolved, for a visitor with no cookies and no query string, shared
props included. So the build stops, naming the route, when a page:
- answers with a status other than 200, such as a redirect;
- takes POSTs at its URL (an `action` or `actions`): Cloudflare answers those with 405 for a static file, so Fondu
refuses them on every target;
- has a URL ending in `index`: see [Limits](#limits);
- lists a param value that is not a file name: one with a `/` or `\` in it, or `.` / `..` (each segment of a catch-all is one name); or two pages that would be the same file.
## Headers
A static page is a file served with the headers the build decided: the security headers of the app's pages, one set
for all of them. The Content Security Policy has no nonce, as a file served to everyone can't have one: the scripts that
had it are allowed by their hashes instead, so an inline script of [the document](https://fondu.dev/docs/document.md) runs on a static
page too. A page object has the same headers, with `X-Fondu`.
The build keeps that set where the target serves the files from:
- On Cloudflare, in `_headers`, which Workers Static Assets apply to static files.
- On Bun and Node, in `dist/server/prerender.json`, next to the built server, which reads it at start.
## A new deploy
Each page records the build it belongs to. After a deploy, a navigation from a tab opened before it loads the page as
a document, with the new assets.
## Limits
A URL whose last segment is `index` (`/index`, `/blog/index`, a param's value, `%69ndex` included) can't be a static
page: its file would be its directory's page, `index.html`. The build stops if one is to be prerendered. Its route
still answers it: Fondu sends such URLs to the server on every target (on Cloudflare, it adds `/index` and
`/*/index` to the built `wrangler.json`'s `run_worker_first`). `routes/blog/index.tsx` at `/blog` is not concerned.
On Cloudflare, one spelling still doesn't reach the Worker: with letters percent-encoded (`/%69ndex`), Static Assets
redirect the request to the directory before the Worker runs, as `run_worker_first` matches the raw path. A link to
it from a page still works.
# MDX pages
https://fondu.dev/docs/mdx
> How to write pages as MDX, Markdown with React components: the Vite setup, layouts, your own components and remark or rehype plugins.
A page can be an `.mdx` file: Markdown, with JSX and imported React components. It suits docs and articles; this site's
docs are MDX pages.
## Setup
Add [`@mdx-js/rollup`](https://mdxjs.com/packages/rollup/) and put it first in `vite.config.ts`:
```sh title="npm"
npm install -D @mdx-js/rollup
```
```sh title="pnpm"
pnpm add -D @mdx-js/rollup
```
```sh title="yarn"
yarn add -D @mdx-js/rollup
```
```sh title="bun"
bun add -d @mdx-js/rollup
```
```ts
// vite.config.ts
import mdx from '@mdx-js/rollup'
export default defineConfig({
plugins: [{ enforce: 'pre', ...mdx() }, fondu({ target: 'node' })],
})
```
## A page
```mdx
{/* app/routes/guide/intro.mdx: /guide/intro */}
import { Counter } from '#/components/counter.tsx'
# Introduction
Some **Markdown**, and a component:
```
An MDX file in `app/routes/` is a page at its URL, rendered on GET. It has no handlers: a `_middleware.ts` around it
can [share](https://fondu.dev/docs/pages.md#shared-props) props, which are in `props` (`{props.title}` in the Markdown), and set
`prerender`.
## Layouts and components
The page renders inside the `_layout.tsx` files above it, as any page does ([Layouts](https://fondu.dev/docs/layouts.md)). To change what
the Markdown becomes (a link that opens another site in a new tab, a styled table), use MDX's
[`providerImportSource`](https://mdxjs.com/packages/mdx/#processoroptions) with `@mdx-js/react`'s `MDXProvider` in
that layout.
In development, an edit to an MDX page updates it in place (React Fast Refresh), as for a `.tsx` page. An MDX page
can't export handlers (`loader`, `action`, `actions`, the HTTP methods), `prerender` or `params`: the app stops, and a
`prerender` goes in a `.tsx` route or a `_middleware.ts`. Any other export is allowed (a table of contents
a rehype plugin adds, say), but Fondu may reserve new export names in a minor release.
Remark and rehype plugins go in `mdx()`'s options: this site uses `remark-gfm` for tables, `rehype-slug` for heading
ids and `@shikijs/rehype` to highlight code at build time.
# The document
https://fondu.dev/docs/document
> The HTML around every page: html attributes, head tags, icons, fonts, and inline scripts under the Content Security Policy.
Every page a browser loads first is an HTML document around the page: ``, ``, ``. Fondu writes a
minimal one; `createApp({ document })` replaces it with yours. Layouts (`_layout.tsx`) are the React around a page; the
document is the HTML around React.
## The default
```html
```
## Your own
`document` is a function of the parts Fondu renders, returning the document as JSX. A component in its own file reads
best:
```tsx
// app/document.tsx
import type { DocumentParts } from 'fondu'
export default function Document({ head, body, c }: DocumentParts) {
return (
{head}
{body}
)
}
```
```ts
// app/server.ts
import { createApp } from 'fondu'
import Document from '#/document.tsx'
export default createApp({ document: Document })
```
- `head`: the page's scripts, then the tags it renders (``, ` `). Put it last in ``. Its
stylesheets go first in ``, right after ` `: the browser asks for them before anything else.
- `body`: the page data (`${head} ${body}`
```
On a [static page](https://fondu.dev/docs/static-pages.md) too, where there is no nonce: the scripts that had it are allowed by their
hashes (a static page waits for every Suspense boundary, so it has none of React's). A script from another origin (`