Server details
The rules, limits and error messages behind the Server guide. The signatures are in the hamur/server reference.
The one door
server/index.ts exports your handlers by name, and defineServer as its default export.
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) |
render | defineRenderHandler(…) | around every page answer, the error page's included (Errors) |
- 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
routeis a string literal in:paramsyntax. handlerMiddlewareandmiddlewaremust be array literals, and every entry ofhandlerMiddlewarean imported name, because the client stub embeds its client part.export { a, b as c } from "./x.ts"andexport * 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.tsitself 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). exportsis for what the host imports from the built entry by name, such as a Durable Object class on Cloudflare (see Deploy). It is an object literal of names imported in this file: anything else fails withserver/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 withserver/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 withexports "Room" is exported by server/index.ts and by layer "billing". - The server never imports these files itself, so
hamur devdoes 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) keeps its rules.- An app with no
server/index.tshas no server code: pages render,public/is served, andimport { 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
routeis a string literal belowapp.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. methodisGET,POST(the default),PUT,PATCH,DELETE,HEAD,OPTIONS,CONNECT,TRACE,QUERYor, withraw,"*"; every method butGETandPOSTneeds aroute.- Two handlers on one path with two methods are one route: a
PUTon a path that hasGETandDELETEanswers 405 withallow: 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 aGETwhoseAcceptdoes not includetext/html; otherwise the page wins.
What a route reads
- The path, the query and the body merge into one object, the
inputof the call. GET,HEAD,OPTIONS,CONNECTandTRACEread 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), soPUT /v1/users/1with{"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
inputwithz.number()on a path parameter answers 400 on every call; usez.coerce.number(). - The type checker names a route parameter that
inputlacks, andhamur devanswers 500 withgetPost: route "/api/posts/:id" has parameter "id", which input does not declarefor a schema it can read. - A request with a body must be
application/json; any other type answers 415 withaccept-post,accept-patchoraccept-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
statuswhen the definition sets it (200 to 299), or the onesetResponseStatusset.
| 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. A form post from another site is refused before the router with 403, as for every path.
- In
hamur devonly, a JSON answer to a request with?prettyin its query or anAcceptthat namestext/htmlis indented with 2 spaces, so a browser shows an API route readably; a build answers compact JSON. - An
OPTIONSrequest to a server route that has noOPTIONShandler and no CORS rule answers204with theAllowheader that the405of that path carries, such asGET, HEAD, OPTIONS, POST; a path with acorsrule keeps its preflight.
raw: a plain HTTP endpoint
raw: truehands the request over.- The shape stays
handler(input, ctx), withinputthe path and query only and the body unread onevent.request:handler({ id }, { event }), andhandler(_, { event })when there is no parameter. There is no 415 rule, no input merge, no JSON check and nooutput; 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
#serverin client code fails:app/x.tsx imports stripeHook from "#server", but it is raw: it answers a URL, not a call.
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:
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
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),
})
reqis anIncomingMessage-shaped readable:method,url(the path and query, whole, not cut at the route),headersin lower case,httpVersionandsocket.remoteAddress.- The body is streamed when the handler reads it, under
server.maxBodySize(abodyLimitrule raises it); a largercontent-lengthis a 413 before the handler runs. resis aServerResponse-shaped writable withstatusCode,statusMessage,setHeader,getHeader,removeHeader,hasHeader,writeHead,write,end,headersSent,flushHeadersand thefinishandcloseevents. The answer starts at the firstwrite,flushHeadersorend, and laterres.writechunks 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,vercelwith the edge runtime and the other isolate presets there is nonode:http: the build fails withfromNodeHandler 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=1goes tohttps://old.example.com/legacy/x?a=1, below any path the URL has. It is forwarded as aproxyroute rule forwards:hostand 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/aboutrenders 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
cookieandauthorizationheaders go along, the session cookie included, as with aproxyrule, so pointfallbackProxyonly 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-middlewarepreset andmiddleware({ fallthrough: true }), the proxy is tried beforenext(). - The prerender never forwards.
- In the browser, a
Linkto 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:orhttps:URL, else the config fails to load:server.fallbackProxy must be an absolute http: or https: URL (got "legacy.example"). - A
staticbuild has no server to forward from and listsserver.fallbackProxyamong the dropped features.
Middleware
- The
middlewarelist ofdefineServerruns before every request that matches, and before every route, handler call and page. defineMiddlewaretakes a function({ event, input, context, next }), or an object with aserverpart (and aclientpart for handler 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 setevent.response.headers; a returnedResponsereplaces the answer.next({ context })merges values intoevent.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), belowapp.baseURL, and/admin/**also matches/admin. - A request middleware has no
clientpart, because nothing runs it in the browser: list a middleware that has one inhandlerMiddleware. - An entry is a step or
{ route, handler }, and that is the only way to scope one: there is nomatcher, and a handler has nouselist. - To see which rules a pattern covers in a test, call
matchRouteRules({ "/admin/**": {} }, { path: "/admin" }).patterns.
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.contextobject carries values on to the handler and to theloadfiles of a page. It is what SvelteKit callsevent.localsand Fresh callsctx.state: Hamur has noevent.locals, a middleware writesevent.context.userand the handler reads it. - To type the keys a middleware sets, augment
HamurEventContext(andHamurRuntimeEnvfor the platform bindings onevent.runtime.env) withdeclare 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 ofdefineServerand themiddlewareof 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.
Rewrite from a middleware
- A step can send the request to another page without a redirect: return
rewrite(path)fromhamur/app, as a route middleware does. - The address stays and the answer is the target's.
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,
rewriteandproxyrules, the request steps not entered yet, and then its handler route or page. The answer keeps the headers the step set onevent.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().maskis the address. - A mapping the browser must apply to its own navigations belongs in a
rewriterule or the reroute file, see Rewrites.
The request, anywhere
useEvent()works in a handler, a handler route, middleware, aload, an app plugin on the server and the page render, and it follows the request acrossawait, timers andevent.waitUntil: two requests at the same time never see each other's event.getCookie(name),setCookie(name, value)anddeleteCookie(name)without an event use it, and so does a handler called on the server without{ event }(Handlers).- Every request runs inside the request context, an
AsyncLocalStoragestore 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 headersvariesnames (Storage and cache). The error messages are in the API reference.- The context has a small price.
- The
bunpreset answeringGET /api/helloran 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.asyncContexttofalseinhamur.config.ts;useEvent()then throwsuseEvent() needs the request context; set server.asyncContext: true in hamur.config.ts, unless tracing is on. On Cloudflare the context needs thenodejs_compatcompatibility flag.
Order of a request
- The
requestserver hook. - Static files from
public/and the client assets. - The CORS preflight for a
corsrule, the origin check, then the redirects file, rules thatredirect, the reroute file, and rules thatrewriteorproxy. - The
middlewarelist ofdefineServer, outermost entry first: each module's list, each layer's from low priority to high, then the app's. - The OpenAPI document and the GraphQL endpoint, when they are on.
- A matching server route, a handler's
routeor arawone. - A path with routes but none for the method: 405 with
allow. /_hamur/fn/<id>, the endpoint of a handler a page calls.- 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. - A request that does not prefer
text/htmland matches no page: a JSON 404. - A
POSTto a page with?_fn=<id>runs that handler and renders the page (Forms); any otherPOSTto a page answers 405. - The page, or the HTML 404 error page when no page matches.
- With
server.fallbackProxy, a request that steps 10 and 12 would answer with a 404 is forwarded instead. allowaddsHEADwhenGETis there andOPTIONSfor a path with acorsrule.
Plugins and hooks
- A
definePlugin(fn)in thepluginslist 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:htmlandclose. They return nothing and cannot replace the response;beforeResponsemay change its headers. - A hook that throws is logged and the response still goes out, except
request, whose error answers the request. closeruns when thebunornodeserver shuts down: on the firstSIGTERMorSIGINTthe server stops accepting connections, lets requests in flight finish for up to 10 seconds, runscloseand exits with code 0; a second signal exits with code 1.- See Deploy.
Your own pipeline
- A request runs a pipeline of stages: public files, route rules, the
middlewarelist, handler routes, pages, and the 404. fetchreplaces it with your own, composed from the same stages ofhamur/pipelineand any of your own.- A stage is
(request, ctx, next) => Promise<Response>: it answers, or callsnext()and gets the answer of the stages after it.
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()
}
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
fetchwritten by hand works too;defaultPipelineis the pipeline a server withoutfetchruns:
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 anyfetch, and so do theipRestrictionandbasicAuthrules 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 andssrrules still are), and withoutserverRoutes()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()intry/catchmust rethrow anything that is not anError. - The stages are listed in the API reference.
The server logs a warning for each configured feature whose stage is missing; the reference 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 fromREDIS_URLorurl). publishandpeer.publishalso go on the channelhamur:ws:<topic>(the prefix ischannelPrefix), 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,invalidateRouteCacheand a cache'sexpire()go onhamur:cache:invalidatewhen they reached amemorymount, and each other instance runs the same call on its ownmemorymounts; a shared driver such asredisneeds no message.- An instance handles these messages in the order they arrived, so a client told through a topic after a
revalidateTagreads the fresh value on any instance. - When Redis is unreachable,
publishreaches the local peers only, the server logsserver.pubsub lost redis://cache:6379; retryingonce per outage (without the password) and reconnects after 100 ms, doubling up to 5 s.
Synced state messages
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.tsexports it too. defineHandlerand 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); andwebsocket message cannot be used with jsonRpc: the methods answer each message.
Validated routes
- A handler with a
routecarries its schemas once. inputchecks the request, types the handler and describes the parameters;outputchecks the answer and describes the 200;metadescribes 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 works with no adapter, such as zod, valibot or arktype.
// 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
},
})
idis a number andtitlea string, with no annotation.idcomes from the path,notifyfrom the query andtitlefrom the body; the document puts each where it is read.- A return value that does not fit
outputis a type error, andoutputalso runs on the value at run time. - A key that is not a route parameter, with
GET,HEADorDELETE, is documented as a query parameter; with the other methods, inrequestBody. - A route without
inputandoutputcosts nothing extra per request.
The 400 answer
- When
inputfails, the handler does not run and the request answers 400 with every issue. innames 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.pathis an array of strings and numbers, andmessageis the library's own text.
PATCH /api/posts/abc?notify=maybe
content-type: application/json
{"title":""}
{
"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 aboveserver.maxBodySizeis a 413; both come before validation. - A schema whose
validatethrows is a 500, not a 400. - Called by id or from a form, the same failure carries the issues as they came, which
useFormreads.
OpenAPI
server.openapiisfalseby default.trueturns it on with defaults; an object setspath,info,serversand any other root field of the document, such ascomponents,securityortags.
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
GETandHEADat/_hamur/openapi.json, or atpath, belowapp.baseURL. It is built on the first request and kept. - When
server.openapiis off, the path is not answered and the build carries no OpenAPI code. openapi,pathsandjsonSchemaDialectcannot be set in the config.
Serve an API reference page
server.openapi.uiisfalseby default."scalar"or"swagger"serves a page that shows the document, at/_hamur/api-docsbelowapp.baseURL;{ provider, path }moves it.uiandprerenderare fields of theserver.openapiobject, so they cannot be set while the document is off.
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
integrityhash, when a visitor opens it; the server itself makes no request. That page alone answers aContent-Security-Policythat allowshttps://cdn.jsdelivr.netfor 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
middlewarelist covers the page and the document alike. uifails at load withserver.openapi.ui must be false, "scalar", "swagger" or { provider, path } (got "redoc"), and a path that starts without/, holds?or#, or equalsserver.openapi.pathfails withserver.openapi.ui.path must differ from server.openapi.pathor thepathmessage.
Write the document at build
prerender: truemakeshamur buildrequest the document from the built server and write it to.output/public/_hamur/openapi.json(belowapp.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.
prerenderfails at load withserver.openapi.prerender must be a boolean (got "yes").
The methods of a route
- A route's method is the
methodof its handler, and the document lists exactly that. metadoes not set it.- A
rawroute withmethod: "*"answers every method, so it has no single method to list: it is documented asgetand 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
methodto 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:
[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
toStandardJsonSchemafrom@valibot/to-json-schema:
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)) }))
inputis described as what a client sends,outputas what the handler returns.
Events in the document
eventsdescribes thedataof each event a route sends withcreateEventStream.- Like
outputit is never run. It types thedatathat$fetch.streamreads from the route, and nothing on the server: the handler returns the stream'sResponse. - The document lists the success response as
text/event-stream. - A route has one success body, so
outputandeventstogether throwevents cannot be used with output: a route has one success body. eventsneeds aroute, and arawhandler may have it.
// 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 aroute. Its input merges as onPOST, the document lists it under thequeryoperation of the path with the input inrequestBody, and a 415 setsaccept-query.
// 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
routeare never listed. - Middleware is not read, since its effect cannot be seen from code; describe an auth check with
components.securitySchemesandsecurityin the config, or withmeta.securityandmeta.responses.
In tests and scripts
getOpenAPIDocument({ routes, baseURL, config }) builds the document without a server. Each call builds a new one.
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_TOKENis unset or empty, so a missing variable never opens the document.
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
GEThandler withcacheis 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
cloudflarepreset,createFetch({ binding: "API" })makes a client whose/URLs callenv.API.fetchof a service binding, so one Worker calls another without a public request. - Declare the binding in
servicesof the wrangler config. - Method, headers, body,
query, JSON handling,retryandFetchErrorare those of$fetch; the request's host ishttp://localhost, or the origin ofeventwhen 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 throwscreateFetch binding needs the cloudflare preset. bindingis ahamur/serveroption only;createFetchofhamur/appdoes not take it.- A binding is another app, so the request's
cookieandauthorizationare not forwarded to it, and itsset-cookiedoes not reach the visitor; pass what it needs inheaders. - Only the request id goes along.
- The type argument is the other app's route table:
hamur typegenwrites it asHamurAppRoutesin.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
bodyandquerychecked and its data typed; a URL the table does not list stays untyped, as it does for$fetch.
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 }
}