Core Concepts

Typed API Runtime Flow

Follow the exact request lifecycle from incoming `/api/*` call to router execution and serialized response.

Updated: 2026-03-04

Entrypoint Discovery

Runtime scans for app/api/typed.ts (and JS/TSX variants). If file is missing, typed API handling is skipped.

Path + Method Resolution

  • Request path candidates include both raw path and /api-stripped path.
  • Router checks matching procedure by normalized method (get/post).
  • No method match with existing route map returns 405.
  • No route match returns not-found and allows fallback.

Body Parsing Rules

  • application/json and +json parse into objects.
  • application/x-www-form-urlencoded parses via URLSearchParams.
  • text/* returns UTF-8 string.
  • Other content types return Buffer payload.

Context and Environment Factories

typed entrypoint optional exports

ts
export async function createContext({ req, res }) {
  return { userId: req.headers['x-user-id'] ?? null };
}

export function createEnv() {
  return { mode: process.env.NODE_ENV ?? 'development' };
}

Procedure req.cookies is a read-only cookie store. Procedures may use .output(schema) to validate handler results, and Server Components can call the same router without HTTP:

ts

ts
const caller = v.createCaller(router, { ctx, env });
const health = await caller.health();

Middleware that returns a Response without calling next() short-circuits the procedure.

Error Mapping

  • Validation and method errors map to 4xx responses with message.
  • Body size violations map to 413.
  • Unhandled runtime errors map to 500.
  • Router-level error handler can return custom Response for central handling.