Use tRPC for your app's own data. Use REST route handlers for webhooks, file uploads, streaming responses, OAuth callbacks and a public API.
Every route has a policy
apps/web/lib/route-policy.ts has one row per API route:
{ path: "/api/settings/modifyAvatar", match: "exact", auth: "session", rateLimit: "default", maxBodyBytes: 6 * MB, input: "image-upload" },
| Field | Values |
|---|---|
path, match | The route path ([param] matches one segment), exact or prefix |
auth | public, auth-page, auth-handler, session, api-key, webhook, procedure |
roles | Required user roles, for example ["admin"] |
allowGuest | Let the read-only guest call a session route |
rateLimit | default, chat, api-key or none |
maxBodyBytes | Larger requests get 413 from the middleware before your handler runs |
input | Where input is validated: zod, image-upload, form-data, provider, forwarded, manual, trpc, none |
cors | self-managed when the handler sets its own CORS headers |
tests/integration/routePolicy.test.ts fails when a route under app/api has no row, when a session route does not call guardRoute, or when a route does not use the validation its row declares.
A session route
// apps/web/app/api/reports/export/route.ts
import { NextResponse } from "next/server";
import { z } from "zod";
import { guardRoute } from "@/server/routeGuard";
export const runtime = "nodejs";
const body = z.object({ reportId: z.string().min(1), format: z.enum(["csv", "pdf"]) });
export async function POST(req: Request) {
const guard = await guardRoute(req, "/api/reports/export");
if (!guard.ok) return NextResponse.json({ error: guard.error }, { status: guard.status });
const parsed = body.safeParse(await req.json());
if (!parsed.success) return NextResponse.json({ error: "Invalid input" }, { status: 400 });
// guard.session.user.id is the signed-in user
return NextResponse.json({ ok: true });
}
// route-policy.ts
{ path: "/api/reports/export", match: "exact", auth: "session", rateLimit: "default", maxBodyBytes: 16 * KB, input: "zod" },
guardRoute returns 401 (no session), 403 (wrong role, or a guest without allowGuest) or 429 (rate limited) as data, so each route keeps its own response shape.
A webhook
{ path: "/api/webhooks/acme", match: "exact", auth: "webhook", rateLimit: "none", maxBodyBytes: 1 * MB, input: "provider" },
- Read the raw body (
await req.text()) and verify the provider's signature before parsing. - Use the provider's event or object ID as an idempotency key: return
200early if it was already processed. - Check again inside
db.$transactionbefore writing. - Give the key a unique constraint and treat Prisma
P2002as "already processed".
The payment webhooks are the reference: apps/web/app/api/payments/stripe/webhook/route.ts.
A public API route
With the API Keys module, authenticate with authenticateApiKey(req, { scopes: [...] }) and use auth: "api-key" with rateLimit: "api-key". See API Keys & REST API.
Streaming
Route handlers can stream. The AI chat route returns a UI message stream from the AI SDK, and the agent route proxies Server-Sent Events from the Python backend. Set export const maxDuration = 60 (or what your host allows) for long responses.
Existing routes
| Route | Auth | Purpose |
|---|---|---|
/api/auth/* | Better Auth | Sign-in, OAuth callbacks, sessions, desktop callback |
/api/trpc/* | Per procedure | tRPC |
/api/healthcheck | Public | Uptime checks |
/api/demo-login | Public | Signs into the demo guest account |
/api/settings/modifyAvatar | Session | Avatar upload |
/api/cms/upload | Session, admin | CMS image upload |
/api/payments/stripe/webhook, /api/payments/dodo/webhook | Webhook | Billing module |
/api/ai/chat, /api/ai/speech/tts, /api/ai/speech/stt | Session | AI Platform module |
/api/ai/agents/[agentId]/stream | Session | AI Agents module |
/api/v1/me | API key | API Keys module |
Good habits
- Set
export const runtime = "nodejs"for routes that use Prisma,sharpor Node APIs. - Validate every input, and answer
400with a short message. - Log with
loggerfrom@workspace/observability/winston-logger; never log request bodies that may contain secrets. - Keep the policy row and the handler in the same commit.
