# Server details

The rules, limits and error messages behind the [Server](/server) guide. The signatures are in the [`hamur/server` reference](/api-reference/server).

## The one door

`server/index.ts` exports your handlers by name, and `defineServer` as its default export.

````ts [forms/server/index.ts]
import { defineServer } from "hamur/server"
import { removeGuard } from "./guards/remove.ts"
import { requireLogin } from "./guards/login.ts"
import { timing } from "./guards/timing.ts"
import { timer } from "./timer.ts"

export { listUsers } from "./admin.ts"
export { listBooks } from "./books.ts"
export { getForecast } from "./forecast.ts"
export { addNote } from "./notes.ts"
export { sendContact } from "./contact.ts"
export { getAccount, getDashboard, listOrders } from "./dashboard.ts"
export { getWeather, serverTime } from "./cached.ts"
export { checksum, report } from "./files.ts"
export { getComments, getPost, listPosts, renamePost } from "./posts.ts"
export { hello } from "./hello.ts"
export { getProfile } from "./profile.ts"
export { logIn, logOut, whoami } from "./session.ts"
export { countdown } from "./stream.ts"
export { addTodo, listTodos, removeTodo } from "./todos.ts"
export { upload } from "./upload.ts"

export default defineServer({
  plugins: [timer],
  middleware: [removeGuard, { route: "/admin/**", handler: requireLogin }],
  handlerMiddleware: [timing],
})
````

| `defineServer` key  | Holds                                                                | Runs                                                                                              |
| ------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `plugins`           | `definePlugin(…)` results                                            | once, when the server starts                                                                      |
| `middleware`        | `defineMiddleware(…)`, or `{ route, handler }` to run under one path | before every request that matches, in this order                                                  |
| `handlerMiddleware` | `defineMiddleware(…)`                                                | around every handler of this door, before its own `middleware`                                    |
| `exports`           | `{ Counter }`, imported names                                        | never: `.output/server/index.mjs` exports each by name, beside its default export                 |
| `fetch`             | `pipeline(…)` of `hamur/pipeline`, or `(request, ctx) => Response`   | for every request, in place of the default pipeline                                               |
| `error`             | `defineErrorHandler(…)`                                              | for every error answer, after the `error` hooks ([Errors](/errors#changing-the-error-answer))     |
| `render`            | `defineRenderHandler(…)`                                             | around every page answer, the error page's included ([Errors](/errors#changing-the-error-answer)) |

- Any other key throws at build: `defineServer has no "routes"; it takes plugins, middleware, handlerMiddleware, exports, fetch, error, render`.
- The build reads this file without running your code. It holds imports, re-exports and the default export, nothing else; module code would run on one side of the split, so it fails with `server/index.ts:<line>: this file is split by the build; it holds imports, re-exports and export default defineServer(…); move other code to a file it imports`.
- Each `route` is a string literal in `:param` syntax.
- `handlerMiddleware` and `middleware` must be array literals, and every entry of `handlerMiddleware` an imported name, because the client stub embeds its client part.
- `export { a, b as c } from "./x.ts"` and `export * from "./x/index.ts"` are followed to any depth.
- A handler is `const a = defineHandler({ … })` at the top level of its file, with any name, in any folder; `server/index.ts` itself defines nothing.
- A constant, a class or a factory call in the chain fails: `server/index.ts: export "a" is not defined with defineHandler: the build reads \`const a = defineHandler({ … })\` at its definition and runs nothing`.
- A star over a file with helpers therefore fails; name the handlers instead.
- Two stars that provide one name fail: `server/index.ts: export "same" comes from both ./a.ts and ./b.ts; JavaScript would drop it. Name one: export { same } from "./a.ts"`.
- A package name fails: `a package joins with addServer` (see [Modules](/modules#the-kit)).
- `exports` is for what the host imports from the built entry by name, such as a Durable Object class on Cloudflare (see [Deploy](/deploy/presets/cloudflare#durable-objects)). It is an object literal of names imported in this file: anything else fails with `server/index.ts: exports must be an object literal of imported names; the build reads it`.
- A name the built entry already exports (`default`, `fetch`, `port`, `websocket`, `handler`, `close`, `listen`, `renderPage`, `middleware`, `scheduled`, `queue`, `email`, `tail`, `HamurWebSocket`) fails with `server/index.ts: exports.fetch collides with an entry export of the built server; rename it`.
- A layer or a module adds its own `exports`; one name in two doors fails with `exports "Room" is exported by server/index.ts and by layer "billing"`.
- The server never imports these files itself, so `hamur dev` does not load them.
- Folders under `server/` mean nothing: the tree is yours, and moving a file never changes what is public or what guards it.
- `server/graphql` ([GraphQL](/graphql)) keeps its rules.
- An app with no `server/index.ts` has no server code: pages render, `public/` is served, and `import { x } from "#server"` fails with `#server needs server/index.ts: create it and export the handlers the client may call`.

## A handler with a route

- `route` is a string literal below `app.baseURL`: `:name`, `:name?`, a mixed segment such as `/shop/:category-:id`, and a named last catch-all `/**:rest`.
- An unnamed `/**`, a `*` segment, a missing leading `/` and a pattern that does not parse fail the build with the file and the export in the message.
- `method` is `GET`, `POST` (the default), `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, `CONNECT`, `TRACE`, `QUERY` or, with `raw`, `"*"`; every method but `GET` and `POST` needs a `route`.
- Two handlers on one path with two methods are one route: a `PUT` on a path that has `GET` and `DELETE` answers 405 with `allow: DELETE, GET, HEAD`. The same method and path twice fails the build and names both sides:

```
Server route "/v1/x" (server/p.ts#b) conflicts with "/v1/x" (server/p.ts#a): duplicate GET /v1/x
```

- A server route and a page can share a path.
- The route wins for every method but `GET`, and for a `GET` whose `Accept` does not include `text/html`; otherwise the page wins.

### What a route reads

- The path, the query and the body merge into one object, the `input` of the call.
- `GET`, `HEAD`, `OPTIONS`, `CONNECT` and `TRACE` read the path and the query; the other methods read the body too.
- A name that two places send with two values answers 400 `Input "id" differs between path and body` (`path and query`, `query and body`), so `PUT /v1/users/1` with `{"id": 2}` cannot pass a check on the path and write another row.
- A body that is not an object is the whole input when the route has no parameter and the request no query.
- Nothing is coerced: a parameter is text until the schema says otherwise, so `input` with `z.number()` on a path parameter answers 400 on every call; use `z.coerce.number()`.
- The type checker names a route parameter that `input` lacks, and `hamur dev` answers 500 with `getPost: route "/api/posts/:id" has parameter "id", which input does not declare` for a schema it can read.
- A request with a body must be `application/json`; any other type answers 415 with `accept-post`, `accept-patch` or `accept-query`.
- A route takes no form body.
- The body limit is `server.maxBodySize`.

### What a route answers

- The value is sent as JSON with status 200, or `status` when the definition sets it (200 to 299), or the one `setResponseStatus` set.

| The handler gives                | The route answers                                                                                                                                                                                                                                                                            |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| a value                          | JSON, `JSON.stringify` after a check that refuses what JSON would lose: a `Map`, a `Set`, a `bigint`, a cycle, `NaN`. The error names the handler and the path, such as `posts.ts#getPost returned an instance of Map at output.tags, which JSON cannot carry; return plain data on a route` |
| `undefined`, `null`              | 204, no body                                                                                                                                                                                                                                                                                 |
| a string                         | a JSON string                                                                                                                                                                                                                                                                                |
| a `Response`                     | that response, with the headers set on the event                                                                                                                                                                                                                                             |
| a `Blob`, `File`                 | the bytes                                                                                                                                                                                                                                                                                    |
| a stream                         | `text/event-stream`, each chunk JSON, then `event: end`                                                                                                                                                                                                                                      |
| `redirect()`, returned or thrown | a redirect with `Location`                                                                                                                                                                                                                                                                   |
| a thrown error                   | JSON, or the HTML error page when the request prefers HTML                                                                                                                                                                                                                                   |

A failed `input` answers 400 with every issue, see [The 400 answer](#the-400-answer). A form post from another site is refused before the router with 403, as for every path.

- In `hamur dev` only, a JSON answer to a request with `?pretty` in its query or an `Accept` that names `text/html` is indented with 2 spaces, so a browser shows an API route readably; a build answers compact JSON.
- An `OPTIONS` request to a server route that has no `OPTIONS` handler and no CORS rule answers `204` with the `Allow` header that the `405` of that path carries, such as `GET, HEAD, OPTIONS, POST`; a path with a `cors` rule keeps its preflight.

## `raw`: a plain HTTP endpoint

- `raw: true` hands the request over.
- The shape stays `handler(input, ctx)`, with `input` the path and query only and the body unread on `event.request`: `handler({ id }, { event })`, and `handler(_, { event })` when there is no parameter. There is no 415 rule, no input merge, no JSON check and no `output`; the value goes through the response rules below, so a string is HTML.
- `method: "*"` answers every method.
- A raw handler has no id endpoint and no stub, and importing one from `#server` in client code fails: `app/x.tsx imports stripeHook from "#server", but it is raw: it answers a URL, not a call`.

````ts [server/post-get.ts]
import { createError, defineHandler, getRouterParam } from "hamur/server"

const posts = new Map([["hello", { title: "Hello", body: "First post" }]])

export const getPost = defineHandler({
  route: "/api/posts/:slug",
  method: "GET",
  raw: true,
  handler(_, { event }) {
    const slug = getRouterParam(event, "slug") as string
    const post = posts.get(slug)
    if (!post) throw createError({ status: 404, message: "Post not found" })
    return post
  },
})
````

Return a `Response` to end the request early:

````ts [server/handler-hooks.ts]
import { defineHandler } from "hamur/server"

export const secret = defineHandler({
  route: "/api/secret",
  method: "GET",
  raw: true,
  handler(_, { event }) {
    if (!event.request.headers.has("x-api-key")) return new Response("Missing key", { status: 401 })
    return { ok: true }
  },
})
````

## What a `raw` handler returns

| Returned                            | Response                                                                                                                                         |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| a `Response`                        | sent as it is, with the headers set on the event merged in                                                                                       |
| an object, array, number or boolean | JSON                                                                                                                                             |
| a string                            | `text/html` unless a content type was set                                                                                                        |
| bytes or a `Blob`                   | `application/octet-stream` unless set                                                                                                            |
| a `ReadableStream`                  | streamed                                                                                                                                         |
| `null` or `undefined`               | 204 with no body                                                                                                                                 |
| any value with status 204 or 304    | sent with no body; an answer to `HEAD` keeps its headers and has no body                                                                         |
| a thrown `createError`              | its status, as JSON or the HTML error page                                                                                                       |
| any other throw                     | 500, or the `status`/`statusCode` of the thrown value when it is an HTTP error status (400 to 599); the message is the status text in production |

## Run an Express or Connect handler

````ts [server/node-handler.ts]
import { defineHandler, fromNodeHandler } from "hamur/server"

const legacy = fromNodeHandler((req, res, next) => {
  if (!req.url?.startsWith("/api/legacy/hello")) return next()
  res.statusCode = 200
  res.setHeader("content-type", "application/json")
  res.end(JSON.stringify({ method: req.method, url: req.url }))
})

export const legacyApi = defineHandler({
  route: "/api/legacy/**:path",
  method: "*",
  raw: true,
  handler: (_, { event }) => legacy(event),
})
````

- `req` is an `IncomingMessage`-shaped readable: `method`, `url` (the path and query, whole, not cut at the route), `headers` in lower case, `httpVersion` and `socket.remoteAddress`.
- The body is streamed when the handler reads it, under `server.maxBodySize` (a `bodyLimit` rule raises it); a larger `content-length` is a 413 before the handler runs.
- `res` is a `ServerResponse`-shaped writable with `statusCode`, `statusMessage`, `setHeader`, `getHeader`, `removeHeader`, `hasHeader`, `writeHead`, `write`, `end`, `headersSent`, `flushHeaders` and the `finish` and `close` events. The answer starts at the first `write`, `flushHeaders` or `end`, and later `res.write` chunks stream to the client in order, so a handler can stream.
- A header value with a line break throws, as in node.
- `next()` hands the request to the stages after the route (the page, then the 404), as if the route had not matched.
- `next(error)` fails the request with that error.
- A handler that throws or rejects fails it too.
- Every preset that does not run in a browser-like isolate runs it. On `cloudflare`, `vercel` with the edge runtime and the other isolate presets there is no `node:http`: the build fails with `fromNodeHandler in server/legacy.ts#legacy needs a node or bun preset; the "cloudflare" preset has no node:http`.

## Fall back to another server

- A request that matches no public file, no handler route and no page is forwarded with its method, path, query and streamed body: `/legacy/x?a=1` goes to `https://old.example.com/legacy/x?a=1`, below any path the URL has. It is forwarded as a `proxy` route rule forwards: `host` and the hop-by-hop headers are dropped, a redirect is passed on rather than followed, and an unreachable server is a 502.
- A catch-all page (`[...slug]`, `[[...slug]]`) does not count as a match, so the old server wins over it; a concrete page such as `/about` renders here.
- A path with a handler route for another method answers 405, and a handler that throws a 404 answers it: neither is forwarded.
- The request's `cookie` and `authorization` headers go along, the session cookie included, as with a `proxy` rule, so point `fallbackProxy` only at an origin you trust.
- A rewrite's target, and a browser request that a handler route hands to a page of the same shape, render here.
- With the [`node-middleware`](/deploy) preset and `middleware({ fallthrough: true })`, the proxy is tried before `next()`.
- The prerender never forwards.
- In the browser, a `Link` to a path that no concrete page matches is a plain navigation, a full page load, since that page may live on the old server.
- The client knows only that the option is set, never its URL.
- The URL must be an absolute `http:` or `https:` URL, else the config fails to load: `server.fallbackProxy must be an absolute http: or https: URL (got "legacy.example")`.
- A `static` build has no server to forward from and lists `server.fallbackProxy` among the dropped features.

## Middleware

- The `middleware` list of `defineServer` runs before every request that matches, and before every route, handler call and page.
- `defineMiddleware` takes a function `({ event, input, context, next })`, or an object with a `server` part (and a `client` part for [handler middleware](/handlers#middleware)).
- Returning nothing continues.
- Returning a value ends the request with it.
- `await next()` runs the rest and returns its response, so code after it sees the answer and can set `event.response.headers`; a returned `Response` replaces the answer.
- `next({ context })` merges values into `event.context`.
- A throw is the request's error, and a thrown `redirect()` redirects.
- An entry `{ route: "/admin/**", handler }` runs only under that path; the pattern is a route rule's (`*` one segment, a last `**` zero or more segments), below `app.baseURL`, and `/admin/**` also matches `/admin`.
- A request middleware has no `client` part, because nothing runs it in the browser: list a middleware that has one in `handlerMiddleware`.
- An entry is a step or `{ route, handler }`, and that is the only way to scope one: there is no `matcher`, and a handler has no `use` list.
- To see which rules a pattern covers in a test, call `matchRouteRules({ "/admin/**": {} }, { path: "/admin" }).patterns`.

````ts [rules/server/request-list.ts]
import { defineMiddleware, defineServer, getRequestHeader } from "hamur/server"
import { bucket } from "./bucket.ts"

const audit = defineMiddleware(({ event }) => {
  event.context.userAgent = getRequestHeader(event, "user-agent")
})

export default defineServer({
  middleware: [bucket, { route: "/admin/**", handler: audit }],
})
````

- The `event.context` object carries values on to the handler and to the `load` files of a page. It is what SvelteKit calls `event.locals` and Fresh calls `ctx.state`: Hamur has no `event.locals`, a middleware writes `event.context.user` and the handler reads it.
- To type the keys a middleware sets, augment `HamurEventContext` (and `HamurRuntimeEnv` for the platform bindings on `event.runtime.env`) with `declare module "hamur/server"`; see the API reference.
- A middleware that refuses a request refuses it before the handler, and a route middleware (`app/middleware`) runs only on a navigation in the browser, so only the lists of `defineServer` and the `middleware` of a handler guard anything on the server. The same object can sit in both lists, and a guard that matters is listed in both: the request list protects the document under a path, the handler's list protects the data on every call; see [Sessions and security](/sessions-and-security#protecting-a-page-and-its-data).

### Rewrite from a middleware

- A step can send the request to another page without a redirect: return `rewrite(path)` from `hamur/app`, as a route middleware does.
- The address stays and the answer is the target's.

````ts [rules/server/bucket.ts]
import { rewrite } from "hamur/app"
import { defineMiddleware, getCookie, getRequestURL } from "hamur/server"

export const bucket = defineMiddleware(({ event }) => {
  if (getRequestURL(event).pathname === "/" && getCookie(event, "bucket") === "b") return rewrite("/home-b")
})
````

- The step does not call `next()`.
- The request goes on as a request for the target, which runs its access rules, static files, origin check, `rewrite` and `proxy` rules, the request steps not entered yet, and then its handler route or page. The answer keeps the headers the step set on `event.response`.
- A thrown `rewrite()` does the same.
- A target must be an app path; an external one throws `TypeError: rewrite target must be an app path; use a proxy rule for https://example.com/x`.
- A request that is rewritten to a path it already visited, or a sixth time, answers 508 `Rewrite loop: /a → /b → /a`.
- The browser sees such a rewrite only as the document it got: hydration renders the target and `useRoute().mask` is the address.
- A mapping the browser must apply to its own navigations belongs in a `rewrite` rule or the reroute file, see [Rewrites](/route-rules#rewrites).

## The request, anywhere

- `useEvent()` works in a handler, a handler route, middleware, a `load`, an app plugin on the server and the page render, and it follows the request across `await`, timers and `event.waitUntil`: two requests at the same time never see each other's event.
- `getCookie(name)`, `setCookie(name, value)` and `deleteCookie(name)` without an event use it, and so does a handler called on the server without `{ event }` ([Handlers](/handlers)).
- Every request runs inside the request context, an `AsyncLocalStorage` store of the preset.
- `useEvent()` throws where no request runs: in module code, in a server plugin, or in a timer a plugin started. In a cached computation it returns the cache's own copy of the event, which carries only the headers `varies` names ([Storage and cache](/storage-and-cache)). The error messages are in the [API reference](/api-reference/server#useevent).
- The context has a small price.
- The `bun` preset answering `GET /api/hello` ran at 14,187 requests a second with it on and 14,453 with it off, 1.8 % fewer (medians of 7 alternating runs).
- The off build's own runs ranged over 4,615 requests a second, 32 % of its median, because the machine was shared and loaded. So the run measures a cost smaller than its noise, and the context stays on by default.
- To turn it off, set `server.asyncContext` to `false` in `hamur.config.ts`; `useEvent()` then throws `useEvent() needs the request context; set server.asyncContext: true in hamur.config.ts`, unless tracing is on. On Cloudflare the context needs the `nodejs_compat` compatibility flag.

## Order of a request

1. The `request` server hook.
2. Static files from `public/` and the client assets.
3. The CORS preflight for a `cors` rule, the origin check, then the [redirects file](/route-rules#the-redirects-file), rules that `redirect`, the reroute file, and rules that `rewrite` or `proxy`.
4. The `middleware` list of `defineServer`, outermost entry first: each module's list, each layer's from low priority to high, then the app's.
5. The [OpenAPI document](/server#validated-routes-and-openapi) and the [GraphQL endpoint](/graphql), when they are on.
6. A matching server route, a handler's `route` or a `raw` one.
7. A path with routes but none for the method: 405 with `allow`.
8. `/_hamur/fn/<id>`, the endpoint of a handler a page calls.
9. With `app.trailingSlash: "redirect"`, a 308 to the path without its trailing slash when that path is a page; with `"always"`, a 308 to the path with one.
10. A request that does not prefer `text/html` and matches no page: a JSON 404.
11. A `POST` to a page with `?_fn=<id>` runs that handler and renders the page ([Forms](/forms-and-login#without-javascript)); any other `POST` to a page answers 405.
12. The page, or the HTML 404 error page when no page matches.

- With [`server.fallbackProxy`](#fall-back-to-another-server), a request that steps 10 and 12 would answer with a 404 is forwarded instead.
- `allow` adds `HEAD` when `GET` is there and `OPTIONS` for a path with a `cors` rule.

## Plugins and hooks

- A `definePlugin(fn)` in the `plugins` list runs once, when the server starts, or at the first request on Cloudflare, Vercel and Netlify. It gets `{ hooks, runtimeConfig, log, addLogSink, addSpanExporter, addMetricExporter }`.
- The hooks are `request(event)`, `beforeResponse(event, response)`, `afterResponse(event, response)`, `error(error, event)`, `render:html` and `close`. They return nothing and cannot replace the response; `beforeResponse` may change its headers.
- A hook that throws is logged and the response still goes out, except `request`, whose error answers the request.
- `close` runs when the `bun` or `node` server shuts down: on the first `SIGTERM` or `SIGINT` the server stops accepting connections, lets requests in flight finish for up to 10 seconds, runs `close` and exits with code 0; a second signal exits with code 1.
- See [Deploy](/deploy/presets/bun#shutdown).

## Your own pipeline

- A request runs a pipeline of stages: public files, route rules, the `middleware` list, handler routes, pages, and the 404.
- `fetch` replaces it with your own, composed from the same stages of `hamur/pipeline` and any of your own.
- A stage is `(request, ctx, next) => Promise<Response>`: it answers, or calls `next()` and gets the answer of the stages after it.

````ts [server/health-stage.ts]
import type { Stage } from "hamur/pipeline"

export const health: Stage = async (request, _ctx, next) => {
  if (new URL(request.url).pathname === "/health") return new Response("ok")
  return next()
}
````

````ts [server/pipeline.ts]
import { defineServer } from "hamur/server"
import { pipeline, staticFiles, routeRules, serverRoutes, pages, notFound } from "hamur/pipeline"
import { health } from "./health-stage.ts"

export default defineServer({
  fetch: pipeline(health, staticFiles(), routeRules(), serverRoutes(), pages(), notFound()),
})
````

- A `fetch` written by hand works too; `defaultPipeline` is the pipeline a server without `fetch` runs:

````ts [server/pipeline-by-hand.ts]
import { defineServer } from "hamur/server"
import { defaultPipeline } from "hamur/pipeline"

export default defineServer({
  fetch: (request, ctx) =>
    new URL(request.url).pathname === "/health" ? new Response("ok") : defaultPipeline(request, ctx),
})
````

- The hooks, the request id, tracing, `Server-Timing`, the security headers and the masking of errors run around any `fetch`, and so do the `ipRestriction` and `basicAuth` rules and the origin check.
- A stage you leave out is a feature you turn off: without `routeRules()` the rules' redirects, rewrites, proxies, CORS, rate limits, body limits, timeouts and headers are not applied (caching and `ssr` rules still are), and without `serverRoutes()` no handler or `/_hamur/` endpoint answers.
- Your own stages run once per pass: after a `rewrite`, they run again for the target.
- A stage that wraps `next()` in `try`/`catch` must rethrow anything that is not an `Error`.
- The stages are listed in the [API reference](/api-reference/server).

The server logs a warning for each configured feature whose stage is missing; the [reference](/api-reference/server#pipeline-stage-pipelinecontext) lists them.

## Several instances

- With several instances of the app on the bun preset, `server.pubsub: { driver: "redis" }` carries topics between them through Redis (`Bun.redis`, URL from `REDIS_URL` or `url`).
- `publish` and `peer.publish` also go on the channel `hamur:ws:<topic>` (the prefix is `channelPrefix`), and every other instance delivers the message to its own subscribers of the topic; an instance skips its own messages, so nothing arrives twice.
- `revalidateTag`, `revalidatePath`, `invalidateRouteCache` and a cache's `expire()` go on `hamur:cache:invalidate` when they reached a `memory` mount, and each other instance runs the same call on its own `memory` mounts; a shared driver such as `redis` needs no message.
- An instance handles these messages in the order they arrived, so a client told through a topic after a `revalidateTag` reads the fresh value on any instance.
- When Redis is unreachable, `publish` reaches the local peers only, the server logs `server.pubsub lost redis://cache:6379; retrying` once per outage (without the password) and reconnects after 100 ms, doubling up to 5 s.

## Synced state messages

[Synced state](/realtime#synced-state) sends JSON frames. A page needs none of this; another client speaks them itself.

| Frame                                        | Sent by | Means                                                                                                  |
| -------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------ |
| `{ "t": "sub", room, key }`                  | client  | subscribe to a key                                                                                     |
| `{ "t": "unsub", room, key }`                | client  | end the subscription                                                                                   |
| `{ "t": "set", room, key, value }`           | client  | write a value                                                                                          |
| `{ "t": "val", room, key, value? }`          | server  | the value, without `value` while none is stored                                                        |
| `{ "t": "err", room, key, status, message }` | server  | a refused frame, such as 400 `Synced room and key must be non-empty strings of at most 256 characters` |

## JSON-RPC

- A JSON-RPC route has no client stub: `import { rpc } from "#server"` in client code fails with `<file> imports rpc from "#server", but it is a JSON-RPC route: it answers a URL, not a call`, and the OpenAPI document lists none.
- A method keeps its own stub when `server/index.ts` exports it too.
- `defineHandler` and the build refuse what cannot run: `jsonRpc needs a route`; `jsonRpc cannot be used with handler, input, output, raw, status, events, cache, prerender, batch or live: its methods answer`; `jsonRpc needs method "POST"`; `jsonRpc method "add" must be a handler made with defineHandler`; `jsonRpc method "add" cannot have route, raw, websocket, batch, live or jsonRpc`; `jsonRpc maxBatchSize must be a positive integer (got 0)`; and `websocket message cannot be used with jsonRpc: the methods answer each message`.

## Validated routes

- A handler with a `route` carries its schemas once.
- `input` checks the request, types the handler and describes the parameters; `output` checks the answer and describes the 200; `meta` describes the operation.
- The server builds an OpenAPI 3.2 document from its own route list.
- Hamur has no validator of its own: any library that implements [Standard Schema](https://standardschema.dev) works with no adapter, such as zod, valibot or arktype.

```ts
// server/posts/rename.ts
import { createError, defineHandler } from "hamur/server"
import * as z from "zod"

export const renamePost = defineHandler({
  method: "PATCH",
  route: "/api/posts/:id",
  input: z.object({
    id: z.coerce.number().int(),
    notify: z.enum(["yes", "no"]).default("no"),
    title: z.string().min(1),
  }),
  output: z.object({ id: z.number(), title: z.string() }),
  meta: { summary: "Rename a post", tags: ["posts"] },
  async handler({ id, title }) {
    const post = await db.rename(id, title)
    if (!post) throw createError({ status: 404, message: "Not found" })
    return post
  },
})
```

- `id` is a number and `title` a string, with no annotation.
- `id` comes from the path, `notify` from the query and `title` from the body; the document puts each where it is read.
- A return value that does not fit `output` is a type error, and `output` also runs on the value at run time.
- A key that is not a route parameter, with `GET`, `HEAD` or `DELETE`, is documented as a query parameter; with the other methods, in `requestBody`.
- A route without `input` and `output` costs nothing extra per request.

### The 400 answer

- When `input` fails, the handler does not run and the request answers 400 with every issue.
- `in` names where the key was sent: `"params"` for a key of the route, `"query"` or `"body"` for the rest, and for a key nobody sent `"body"` where the route reads a body and `"query"` where it does not.
- `path` is an array of strings and numbers, and `message` is the library's own text.

```http
PATCH /api/posts/abc?notify=maybe
content-type: application/json

{"title":""}
```

```json
{
  "status": 400,
  "message": "Validation failed",
  "data": {
    "issues": [
      { "in": "params", "path": ["id"], "message": "Invalid input: expected number, received NaN" },
      { "in": "query", "path": ["notify"], "message": "Invalid option: expected one of \"yes\"|\"no\"" },
      { "in": "body", "path": ["title"], "message": "Too small: expected string to have >=1 characters" }
    ]
  }
}
```

- The messages depend on the library.
- A body that is not valid JSON is the usual 400 of `readBody`, and one above `server.maxBodySize` is a 413; both come before validation.
- A schema whose `validate` throws is a 500, not a 400.
- Called by id or from a form, the same failure carries the issues as they came, which `useForm` reads.

## OpenAPI

- `server.openapi` is `false` by default.
- `true` turns it on with defaults; an object sets `path`, `info`, `servers` and any other root field of the document, such as `components`, `security` or `tags`.

````ts [openapi-config.ts]
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "html",
  server: {
    openapi: {
      info: { title: "Shop API", version: "1.4.0" },
      servers: [{ url: "https://shop.example.com" }],
      components: { securitySchemes: { session: { type: "apiKey", in: "cookie", name: "__Host-hamur-session" } } },
      security: [{ session: [] }],
    },
  },
})
````

- The document is served on `GET` and `HEAD` at `/_hamur/openapi.json`, or at `path`, below `app.baseURL`. It is built on the first request and kept.
- When `server.openapi` is off, the path is not answered and the build carries no OpenAPI code.
- `openapi`, `paths` and `jsonSchemaDialect` cannot be set in the config.

### Serve an API reference page

- `server.openapi.ui` is `false` by default.
- `"scalar"` or `"swagger"` serves a page that shows the document, at `/_hamur/api-docs` below `app.baseURL`; `{ provider, path }` moves it.
- `ui` and `prerender` are fields of the `server.openapi` object, so they cannot be set while the document is off.

````ts [server/openapi-ui.ts]
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "html",
  server: {
    openapi: {
      info: { title: "Shop API", version: "1.4.0" },
      ui: "scalar",
      prerender: true,
    },
  },
})
````

- The page loads the viewer from jsDelivr, by exact version and with an `integrity` hash, when a visitor opens it; the server itself makes no request. That page alone answers a `Content-Security-Policy` that allows `https://cdn.jsdelivr.net` for scripts and styles, with the page's own nonce, so the app's policy keeps every other page as it was.
- The page is built for each request and answers `cache-control: no-store`.
- A guard in the `middleware` list covers the page and the document alike.
- `ui` fails at load with `server.openapi.ui must be false, "scalar", "swagger" or { provider, path } (got "redoc")`, and a path that starts without `/`, holds `?` or `#`, or equals `server.openapi.path` fails with `server.openapi.ui.path must differ from server.openapi.path` or the `path` message.

### Write the document at build

- `prerender: true` makes `hamur build` request the document from the built server and write it to `.output/public/_hamur/openapi.json` (below `app.baseURL`).
- The static preset has no server, so this file is how it serves the document; on a server preset the file is answered first and the run-time route stays. The page is not written: it carries a nonce, which is per request.
- `prerender` fails at load with `server.openapi.prerender must be a boolean (got "yes")`.

### The methods of a route

- A route's method is the `method` of its handler, and the document lists exactly that.
- `meta` does not set it.
- A `raw` route with `method: "*"` answers every method, so it has no single method to list: it is documented as `get` and the server logs one line, once per route and process:

```
[hamur] openapi: /api/echo answers every method; documented as get, give it a method
```

- Give the route a `method` to document it and to answer 405 for the others.

### Schemas in the document

- A schema appears in the document only when it has `~standard.jsonSchema`, the Standard JSON Schema side of the interface. Without it the schema still validates, but it is documented as `{}`, and the first request to the document logs one warning per route and part:

```text
[hamur] openapi: PATCH /api/posts/{id} body schema has no ~standard.jsonSchema; documented as {}
```

- zod and arktype schemas carry it.
- A valibot schema does not; wrap it with `toStandardJsonSchema` from `@valibot/to-json-schema`:

```ts
import * as v from "valibot"
import { toStandardJsonSchema } from "@valibot/to-json-schema"

const input = toStandardJsonSchema(v.object({ title: v.pipe(v.string(), v.minLength(1)) }))
```

- `input` is described as what a client sends, `output` as what the handler returns.

### Events in the document

- `events` describes the `data` of each event a route sends with `createEventStream`.
- Like `output` it is never run. It types the `data` that `$fetch.stream` reads from the route, and nothing on the server: the handler returns the stream's `Response`.
- The document lists the success response as `text/event-stream`.
- A route has one success body, so `output` and `events` together throw `events cannot be used with output: a route has one success body`.
- `events` needs a `route`, and a `raw` handler may have it.

```ts
// server/ticks.ts
import { createEventStream, defineHandler } from "hamur/server"
import * as z from "zod"

export const ticks = defineHandler({
  method: "GET",
  route: "/api/ticks",
  raw: true,
  events: z.object({ count: z.number() }),
  meta: { summary: "Count to five" },
  handler(_, { event }) {
    const stream = createEventStream(event)
    let count = 0
    const timer = setInterval(() => {
      stream.push({ count: ++count })
      if (count === 5) {
        clearInterval(timer)
        stream.close()
      }
    }, 1000)
    stream.onClosed(() => clearInterval(timer))
    return stream.send()
  },
})
```

### QUERY routes

- `method: "QUERY"` is a safe method that carries a body, for searches too large for a URL. It needs a `route`. Its input merges as on `POST`, the document lists it under the `query` operation of the path with the input in `requestBody`, and a 415 sets `accept-query`.

```ts
// server/search.ts
import { defineHandler } from "hamur/server"
import * as z from "zod"

export const search = defineHandler({
  method: "QUERY",
  route: "/api/search",
  input: z.object({ terms: z.array(z.string()), limit: z.number().default(20) }),
  output: z.array(z.object({ id: z.number(), title: z.string() })),
  meta: { summary: "Search posts" },
  handler: ({ terms, limit }) => db.search(terms, limit),
})
```

### `meta`

`meta` is plain data that is only read when the document is built.

| Field                                          | Does                                                                                |
| ---------------------------------------------- | ----------------------------------------------------------------------------------- |
| `summary`, `description`, `tags`, `deprecated` | copied to the operation; without `tags` the first static path segment is used       |
| `operationId`                                  | the operation id; the default is the method and route name, as in `patchApiPostsId` |
| `security`, `externalDocs`, `x-*`              | copied to the operation                                                             |
| `requestBody`                                  | replaces the generated request body, for forms or other content types               |
| `responses`                                    | merged over the generated ones by status; an entry replaces that status whole       |
| `hidden`                                       | leaves the route out of the document                                                |

- WebSocket routes, middleware, plugins, pages and handlers without a `route` are never listed.
- Middleware is not read, since its effect cannot be seen from code; describe an auth check with `components.securitySchemes` and `security` in the config, or with `meta.security` and `meta.responses`.

### In tests and scripts

`getOpenAPIDocument({ routes, baseURL, config })` builds the document without a server. Each call builds a new one.

````ts [server/openapi-document.ts]
import { defineHandler, getOpenAPIDocument } from "hamur/server"

const ping = defineHandler({ route: "/api/ping", method: "GET", meta: { summary: "Ping" }, handler: () => "pong" })

const document = await getOpenAPIDocument({
  routes: [
    {
      name: "api-ping",
      path: "/api/ping",
      method: "GET",
      fn: { id: "api-ping", name: "ping", file: "server/ping.ts", export: "ping", raw: false },
      handler: async () => ({ default: ping }),
    },
  ],
  config: { info: { title: "Test API", version: "0.0.1" } },
})

console.log(Object.keys(document.paths))
````

### Protect the document

- The document lists your whole API to anyone who asks. In production put it behind a request middleware, which runs before the document is answered.
- The sample answers 401 when `DOCS_TOKEN` is unset or empty, so a missing variable never opens the document.

````ts [server/openapi-guard.ts]
import { createError, defineMiddleware, getRequestHeader } from "hamur/server"

export const docsGuard = defineMiddleware(({ event }) => {
  if (new URL(event.request.url).pathname !== "/_hamur/openapi.json") return
  const token = process.env.DOCS_TOKEN
  if (!token || getRequestHeader(event, "authorization") !== `Bearer ${token}`) {
    throw createError({ status: 401, message: "Unauthorized" })
  }
})
````

The sample guards the document only. The page of `server.openapi.ui` still opens; give it its own check when it must be closed too.

### Cached routes

- A `GET` handler with `cache` is documented like any other.
- Validation runs inside the handler, so the first request is validated and a 400 is never stored.
- A cache hit does not run the handler.

> **Warning.** On a cache hit the handler does not run, so nothing is validated. A header the answer depends on belongs in `varies`, so it is part of the cache key, and an authorization check belongs in the request middleware: a request without the header can otherwise be answered from the cache.

## Call another Worker

- On the `cloudflare` preset, `createFetch({ binding: "API" })` makes a client whose `/` URLs call `env.API.fetch` of a [service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/), so one Worker calls another without a public request.
- Declare the binding in `services` of the wrangler config.
- Method, headers, body, `query`, JSON handling, `retry` and `FetchError` are those of `$fetch`; the request's host is `http://localhost`, or the origin of `event` when you pass one, and a URL that is absolute still goes to the network.
- A name that is not in the env throws `createFetch binding "API" is not in the env`, and on any other preset the call throws `createFetch binding needs the cloudflare preset`.
- `binding` is a `hamur/server` option only; `createFetch` of `hamur/app` does not take it.
- A binding is another app, so the request's `cookie` and `authorization` are not forwarded to it, and its `set-cookie` does not reach the visitor; pass what it needs in `headers`.
- Only the request id goes along.
- The type argument is the other app's route table: `hamur typegen` writes it as `HamurAppRoutes` in `.hamur/types/fetch-routes.d.ts`, with no augmentation, so a second app names it without merging the two apps' `HamurFetchRoutes`.
- Write `createFetch<import("../api/.hamur/types/fetch-routes").HamurAppRoutes>({ binding: "API" })`; the sample below spells the same table out so it stands alone.
- A literal URL that the table matches has its `body` and `query` checked and its data typed; a URL the table does not list stays untyped, as it does for `$fetch`.

````ts [server/fetch-binding.ts]
import { createFetch } from "hamur/server"

// The other app's table, as its .hamur/types/fetch-routes.d.ts exports it:
// type ApiRoutes = import("../api/.hamur/types/fetch-routes").HamurAppRoutes
interface ApiRoutes {
  static: {
    "/api/users": {
      GET: { data: Array<{ id: number; name: string }>; input: unknown; key: "query"; events: unknown }
      POST: { data: { id: number }; input: { name: string }; key: "body"; events: unknown }
    }
  }
  dynamic: []
}

const api = createFetch<ApiRoutes>({ binding: "API" })

export async function addUser(name: string, token: string) {
  const users = await api("/api/users")
  const created = await api("/api/users", {
    method: "POST",
    body: { name },
    headers: { authorization: `Bearer ${token}` },
  })
  // @ts-expect-error the route's body is { name: string }
  await api("/api/users", { method: "POST", body: { name: 1 } })
  return { count: users.length, id: created.id }
}
````
