Skip to Content

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

Paths 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

app/orders/post.ts
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); };
  • schema is a flat object with the keys query, body, headers. Write only the keys the handler needs. Input that fails the schema never reaches the handler; the client gets 400.
  • The second argument holds the checked input: param (from [id:int], already a number), query, body, headers and user (the signed-in user: { id, name, email, role, avatarUrl }).
  • Don’t declare param in schema and don’t wrap it in request: {…}: manh.run fills those in. Calling c.req.json() or c.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 gets 403 FORBIDDEN. Permissions are checked before the schema, so a caller with the wrong role never sees a 400 that gives the schema away.
  • Without it, the default is "user" when the app has app/auth.ts. Put access in a folder’s middleware.ts to cover every handler below.
  • Writes with access = "public" are limited by default to 30 requests per 10 minutes per sender; over that the app answers 429. Change it with export const rateLimit = { max: 5, windowSec: 600 }, turn it off with export 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 → 200 JSON. String → 200 text. null / undefined → 204.
  • Return a Response for a file or a stream. For a success status other than 200, call c.status(...) before return.
  • 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 }.

app/orders/repository.ts
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; }
  • fail has type never, so after that line TypeScript knows row has 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) or throw { 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.

app/dashboard/stats/get.ts
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 200 responses up to 256 KB are stored.
  • Don’t cache a GET with side effects (writing data, sending e-mail): check warns cache.side-effect.

Good to know

  • Don’t call c.json(...); return the value.
  • A deployed app does not expose /docs or /openapi.json. schema checks input and generates the app/api client 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, document or localStorage. Read secrets with import { env } from "manh/env".

Next steps

Last updated