Routes on Web Standards: Bays, Tariffs, and Honest Errors
Add the depot's read routes with defineHandler, dynamic params, request middleware, zod validation, and HTTPError. The handler API is Request, Response, URL, and Headers, not event.node.
Stage 1 could render a shell, but it could not answer a question. Stage 2 gives Ampyard its first read routes: the depot snapshot, a single bay, the tariff table, and a request id on every response.
What it is#
Nitro v3 maps files to routes. With serverDir: "./server", these files become these endpoints:
server/api/depot.get.ts → GET /api/depot
server/api/stalls/[id].get.ts → GET /api/stalls/:id
server/api/tariffs.get.ts → GET /api/tariffs
server/middleware/request-id.ts → every request
A handler is a function that receives an h3 v2 event and returns a value or a Response. The event is built on web standards:
event.req; // Request
event.url; // URL
event.res; // { status, statusText, headers: Headers }
event.context; // per-request context
event.context.params; // route params
There is no event.node.req on the portable surface. If you need Node's request or response, event.node still exists on Node runtimes, but it is the escape hatch, not the front door.
Why you'd care#
Every previous Nitro version taught a different event shape. Nitro v3 settles on the platform. If you know fetch, you know how to read a body, a header, or a query string:
const body = await event.req.json();
const token = event.req.headers.get("authorization");
const page = event.url.searchParams.get("page");
event.res.headers.set("x-cache", "MISS");
That portability is the point. The same handler runs on Node, Bun, Deno, Cloudflare Workers, and the Vite dev server.
What we're building#
Three reads and one piece of middleware:
/api/depotreturns the eight bays, the queue, today's totals, and the last events./api/stalls/:idreturns one bay plus its recent sessions./api/tariffsreturns the four time-of-use bands.request-id.tsstamps every response withx-ampyard-request-id.
Before#
The h3 v1 version of the same handler reached through Node:
import { defineEventHandler } from "h3";
export default defineEventHandler((event) => {
const id = event.context.params.id;
const page = getQuery(event).page;
setResponseHeader(event, "x-ampyard", "v1");
return { id, page };
});
The event is a wrapper around IncomingMessage, and every helper is specific to that wrapper.
After#
The Nitro v3 version reads the request directly:
import { HTTPError } from "nitro";
import { defineCachedHandler } from "nitro/cache";
import { buildStalls } from "../../utils/depot";
import { listSessionsForStall } from "../../utils/db";
export default defineCachedHandler(async (event) => {
const id = event.context.params?.id;
if (!id) {
throw new HTTPError({ status: 400, message: "Missing stall id." });
}
const stalls = await buildStalls();
const stall = stalls.find((candidate) => candidate.id === id);
if (!stall) {
throw new HTTPError({ status: 404, message: "Stall not found." });
}
return { stall, sessions: await listSessionsForStall(id) };
}, {
name: "stall-detail",
maxAge: 3,
swr: true,
staleMaxAge: 15,
});
Three things are worth noticing:
HTTPErroris thrown, not sent. Nitro's error handler turns it into a response. The samethrowworks in a task or a WebSocket upgrade hook.- The return value is the body. A plain object becomes JSON. A string becomes
text/plainunless you set a content type. AResponseis sent as-is. - The cache wrapper is explicit. Stage 2 does not need the cache yet, but the bay detail already uses a three-second SWR window because a bay page is read far more often than it changes. Stage 3 goes deeper.
The depot snapshot is a plain handler:
import { defineCachedHandler } from "nitro/cache";
import { buildSnapshot } from "../utils/depot";
export default defineCachedHandler(async () => buildSnapshot(), {
name: "depot-snapshot",
maxAge: 2,
swr: true,
staleMaxAge: 10,
});
The tariff route is the same shape with a one-hour window:
export default defineCachedHandler(async () => currentTariffs(), {
name: "depot-tariffs",
maxAge: 60 * 60,
swr: true,
staleMaxAge: 60 * 60 * 24,
});
Middleware is a handler that returns nothing:
import { defineHandler } from "nitro";
export default defineHandler((event) => {
event.res.headers.set("x-ampyard-request-id", crypto.randomUUID().slice(0, 8));
});
Validation is explicit. The queue and reservation routes read JSON with the platform, then run a standard schema:
const bodySchema = z.object({
driver: z.string().trim().min(1).max(60).optional(),
});
export default defineHandler(async (event) => {
const body = await event.req.json().catch(() => ({}));
const parsed = bodySchema.safeParse(body ?? {});
if (!parsed.success) {
throw new HTTPError({ status: 400, message: "Send { driver?: string }." });
}
return Response.json({ queue: await joinQueue(parsed.data.driver ?? "") }, { status: 201 });
});
No readBody, no sendError, no getQuery. The web platform already has the verbs.
Do it yourself#
Start the dev server:
pnpm --filter ampyard dev
Read the depot:
curl -s http://localhost:4321/api/depot | jq '.summary'
Read one bay:
curl -s http://localhost:4321/api/stalls/bay-03 | jq '.stall'
Look for the request id:
curl -si http://localhost:4321/api/tariffs | grep -i x-ampyard
Try a missing bay:
curl -si http://localhost:4321/api/stalls/bay-99
# HTTP/1.1 404
The live stage#
The preview above is /preview/2. It shows the bay board for the first time: eight connectors, live statuses, and a summary row. There are no hold buttons yet, because holds are stage 4. That is the stage boundary doing its job.
Gotchas#
- Explicit imports. Nitro v3 server code should import
defineHandler,HTTPError, and friends fromnitroornitro/h3. Do not rely on a global auto-import layer if you want the file to run unchanged in tests and on other runtimes. - Route params are strings.
event.context.params?.idis whatever the URL contained. Decode or validate before you use it as a key. - String responses are not HTML. Return
Responsewith a content type if you need HTML. A plain string istext/plain. event.res.headersis aHeadersobject. Use.set(),.append(),.delete(), notsetResponseHeader.- Errors need a body.
new HTTPError({ status: 404, message: "..." })gives the client a useful message. A barethrow new Error()is a 500. - Middleware runs for WebSocket upgrades too. If you add auth middleware later, decide whether upgrades should pass through it. Stage 7 covers the exception.
Recap#
Ampyard can now answer questions with portable handlers: Request, URL, Headers, Response, explicit validation, and thrown HTTP errors. Stage 3 puts a cache in front of the board so a spike in readers does not become a spike in D1 queries.
Next: Cache the Board.