Fondu

Routes

View as Markdown

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:

FileURL
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):

// 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:

// 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 (
    <>
      <h1>{user.name}</h1>
      <form method="post" action="?rename">…</form>
      <form method="post" action="?delete">…</form>
    </>
  )
}
  • 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: <form method="post" action="?rename">. 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, 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/).

FileExports
.tsxthe page (default), loader, action or actions, prerender, params
.tsGET, POST, PUT, PATCH, DELETE, OPTIONS, prerender, params
.mdxits content: an MDX page has no handlers
_middleware.tsits middleware (default), prerender, params
_layout.tsx, _error.tsxthe 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.

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.

RefusedStopsInstead
a .jsx route, layout or error filestartup.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, buildpublic/, or a catch-all
a _error.tsx in a directorystartupone error page, app/routes/_error.tsx: Errors
an export the kind of file does not have (loader in a .ts file, prerender in .mdx)build, startupwhat each file exports
an export of the wrong kind (loader that is not a handler, prerender: 'yes')startupwhat each file exports
params that no route it applies to has as [name] or [[name]]startupthe values of a param
params for a name that a route has as a catch-all ([...name])startupparams lists the values of one segment
two files for the same URLsstartupone file per URL
action and actions in one filestartupone of them: loader and actions
a file name with route syntax ([user-id].tsx, a{b}.ts)startupfiles and URLs
[[...path]], or two [[optional]] segments in one pathstartupfiles and URLs, optional segments
a param named query, hash, method, body, headers or signalstartuprename it: [verb].ts
a route under /_fondu/, by its file or by a value listed in paramsstartup/_fondu/ is Fondu's: move the route
an enum, namespace, import x = …, decorator or parameter property in a pagebuildanother module: Server and client code
a redirect to javascript:, data: or vbscript:the request (a 500)After an action
an unknown or mistyped option of createApp() or fondu()where it is calledAPI

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.

// 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:

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 (Zod, Valibot, ArkType…) and hands the handler the parsed values:

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 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:

// 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 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:

// 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 with that status, API clients the exception's response (plain text by default).

Last updated