Route handlers
Handle a request with Hono’s context, then either return a response directly or render this route’s page with data.
Load data and render the page
Export a handlers object keyed by HTTP method. Import page from @humjs/core to render the same file’s default component. The handler receives the unmodified Hono context.
// The code behind the form at the bottom of this page.
import { define, page } from "@humjs/core";
import { Partial } from "@humjs/core/client";
export const handlers = define.handlers({
GET: () => page({ notice: "" }),
POST: async (c) => {
const form = await c.req.formData();
const name = String(form.get("name") ?? "").trim();
return page({
notice: name ? `Welcome, ${name}!` : "Please enter a name.",
});
},
});
export default define.page<{ notice: string }>(({ data }) => (
<form method="post" action="/docs/handlers" data-hum-client-nav>
<input name="name" required />
<Partial name="welcome">
{data.notice && <p>{data.notice}</p>}
</Partial>
</form>
));- The first argument becomes the view’s
dataprop. A synchronousdefine.head<Data>(({ data }) => ...)export can reuse that same payload for SEO tags after the handler has loaded it. - Pass
{ status: 201 }as the second argument to set the HTML response status. - A
HEADrequest uses theHEADhandler, or falls back toGETwhen one is not defined.
Return a response directly
Handlers can use Hono helpers such as c.json(), c.text(), and c.redirect(). If a handler returns a Response, Hum sends it without rendering the page.
// app.ts of this site, reachable at /api/health
app.get("/api/health", (c) => c.json({ status: "ok" }));That endpoint is live on this site: /api/health →
If the selected handler returns nothing, Hum falls through to the default page render. If a route declares handlers but does not handle a non-GET/HEAD method, Hum responds with 405 Method Not Allowed.
Try it
A form handled on the server
This form submits to the page’s POST handler. The handler reads the form data and renders the page again with a message.
Next: Partial page updates →