API handlers
≈ 10 min · you will have an API to create and read orders, with input checks, per-role permissions and Vietnamese error messages.
Each get.ts, post.ts, put.ts, patch.ts or delete.ts file is an endpoint, for example app/bookings/post.ts takes a new booking at a spa. It exports a schema and a handler function, and manh.run sends the function’s return value as JSON.
Handlers run on the server, written with Hono and Zod. The file name is the HTTP method in lower case and the folder is the path.
Files become endpoints
app/orders/get.ts GET /api/orders
app/orders/post.ts POST /api/orders
app/orders/stats/get.ts GET /api/orders/stats
app/orders/[id:int]/get.ts GET /api/orders/:id
app/orders/[id:int]/patch.ts PATCH /api/orders/:id
app/orders/[id:int]/status/post.ts POST /api/orders/:id/statusPaths are on the app’s own domain, for example https://<id>.manh.run/api/orders. A static segment wins over a dynamic one, so /api/orders/stats never lands in [id:int]/get.ts.
A handler
import { z } from "@hono/zod-openapi";
import { createOrder } from "./repository";
export const access = ["staff", "manager"];
export const schema = {
body: z.object({
customerName: z.string().min(1).max(200),
productId: z.number().int().positive(),
quantity: z.number().int().min(1).max(100),
}),
};
export default (c, { user, body }) => {
c.status(201);
return createOrder(user, body);
};schemais a flat object with the keysquery,body,headers. Write only the keys the handler needs. Input that fails the schema never reaches the handler; the client gets400.- The second argument holds the checked input:
param(from[id:int], already a number),query,body,headersanduser(the signed-in user:{ id, name, email, role, avatarUrl }). - Don’t declare
paraminschemaand don’t wrap it inrequest: {…}: manh.run fills those in. Callingc.req.json()orc.req.query()directly skips the check.
Who may call: access
access declares who may call the handler, and manh.run checks it before the handler runs: "public" (anyone), "user" (signed in) or a list of roles such as ["manager", "admin"].
- Not signed in gets
401 UNAUTHENTICATED, the wrong role gets403 FORBIDDEN. Permissions are checked before the schema, so a caller with the wrong role never sees a400that gives the schema away. - Without it, the default is
"user"when the app hasapp/auth.ts. Putaccessin a folder’smiddleware.tsto cover every handler below. - Writes with
access = "public"are limited by default to 30 requests per 10 minutes per sender; over that the app answers429. Change it withexport const rateLimit = { max: 5, windowSec: 600 }, turn it off withexport const rateLimit = false(a webhook from another system). - Row-level limits (only see the orders you created) go in the repository.
Details in Sign-in and permissions.
Return values
- Object, array, number, boolean →
200JSON. String →200text.null/undefined→204. - Return a
Responsefor a file or a stream. For a success status other than 200, callc.status(...)beforereturn. - An unexpected thrown error →
500; its details never show on the live app.
Reporting errors
Throw business errors, don’t return them. Call fail(status, message, code) from manh/errors in a handler, repository or cron job. The client gets { error, message, code }.
import { fail } from "manh/errors";
import { db, eq } from "app/db";
import { orders } from "./orders.table";
export async function getOrder(id: number) {
const [row] = await db.select().from(orders).where(eq(orders.id, id));
if (!row) fail(404, "Không tìm thấy đơn", "NOT_FOUND");
return row;
}failhas typenever, so after that line TypeScript knowsrowhas a value.- A 5xx with a code, such as
fail(503, "Đang bảo trì, vui lòng quay lại sau", "MAINTENANCE"), reaches the client as written. c.json({ error }, 404),c.text("…", 404)orthrow { status: 404 }skip the standard body; don’t use them.
Thin handlers, logic in the repository
A handler checks input, calls one function in app/<resource>/repository.ts and returns the result. Queries, status rules and row-level permissions live in the repository, so cron jobs and other handlers can reuse them. Calling db.* directly in a handler gets the check warning code.no-inline-drizzle-in-handler.
Caching GET
A GET handler that exports cache answers identical GET requests from the cache without running the handler again.
import { dashboardStats } from "./repository";
export const cache = { maxAge: 30, scope: "user" }; // seconds (1–300)
export default () => dashboardStats();scope: "user"(default) caches per token.scope: "public"shares one response with everyone, so use it only for data that is the same for every viewer.- Any non-GET request to the app (writes, cron runs, background jobs, edits in the Data tab) clears the whole cache. Only
200responses up to 256 KB are stored. - Don’t cache a GET with side effects (writing data, sending e-mail):
checkwarnscache.side-effect.
Good to know
- Don’t call
c.json(...); return the value. - A deployed app does not expose
/docsor/openapi.json.schemachecks input and generates theapp/apiclient for your pages. - Each plan caps CPU time per request. Move heavy work (large exports, loops over thousands of rows) to a background job with
manh/jobs. See Plan limits. - Server code runs on a Web API runtime: no
window,documentorlocalStorage. Read secrets withimport { env } from "manh/env".
Next steps
- Database — create tables and write queries in
repository.ts. - Sign-in and permissions —
app/auth.ts, roles and Google sign-in. - get.ts, post.ts… — every export, the argument table and middleware order.