Interactive Learning Platform Nuxt layer

Isolated learning atmosphere · v4.x

← Back to writing
Step 2 of 9defineHandler + Request/Response

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.

ampyard / preview / 2
Live stage Open app ↗
Ampyard · live stageStage 2 / 9

What it is#

Nitro v3 maps files to routes. With serverDir: "./server", these files become these endpoints:

txt
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:

ts
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:

ts
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/depot returns the eight bays, the queue, today's totals, and the last events.
  • /api/stalls/:id returns one bay plus its recent sessions.
  • /api/tariffs returns the four time-of-use bands.
  • request-id.ts stamps every response with x-ampyard-request-id.

Before#

The h3 v1 version of the same handler reached through Node:

server/api/depot.get.ts — h3 v1
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:

server/api/stalls/[id].get.ts
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:

  1. HTTPError is thrown, not sent. Nitro's error handler turns it into a response. The same throw works in a task or a WebSocket upgrade hook.
  2. The return value is the body. A plain object becomes JSON. A string becomes text/plain unless you set a content type. A Response is sent as-is.
  3. 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:

server/api/depot.get.ts
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:

server/api/tariffs.get.ts
export default defineCachedHandler(async () => currentTariffs(), {
  name: "depot-tariffs",
  maxAge: 60 * 60,
  swr: true,
  staleMaxAge: 60 * 60 * 24,
});

Middleware is a handler that returns nothing:

server/middleware/request-id.ts
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:

server/api/queue.post.ts
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:

bash
pnpm --filter ampyard dev

Read the depot:

bash
curl -s http://localhost:4321/api/depot | jq '.summary'

Read one bay:

bash
curl -s http://localhost:4321/api/stalls/bay-03 | jq '.stall'

Look for the request id:

bash
curl -si http://localhost:4321/api/tariffs | grep -i x-ampyard

Try a missing bay:

bash
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 from nitro or nitro/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?.id is whatever the URL contained. Decode or validate before you use it as a key.
  • String responses are not HTML. Return Response with a content type if you need HTML. A plain string is text/plain.
  • event.res.headers is a Headers object. Use .set(), .append(), .delete(), not setResponseHeader.
  • Errors need a body. new HTTPError({ status: 404, message: "..." }) gives the client a useful message. A bare throw 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.