API routes#
Files under app/api are HTTP endpoints. They are not pages and have no HTML. Each file exports functions named after HTTP methods, and each function returns a Response or a plain value. API routes use the same file-based URL rules as pages, with api/ added to the front.
Your first route#
Create app/api/hello.ts:
export function GET() {
return Response.json({ message: "hello" });
}GET /api/hello returns {"message":"hello"}.
URL mapping#
| File | URL |
|---|---|
app/api/health.ts | /api/health |
app/api/users/index.ts | /api/users |
app/api/users/[id].ts | /api/users/:id |
app/api/files/[...path].ts | /api/files/*path |
Route groups in parentheses are skipped in the URL, as they are for pages. Files whose names begin with an underscore are not routes. Use them for shared helpers inside app/api.
API routes can be .ts, .tsx, .js, or .jsx. Markdown is not allowed.
Methods#
Export a function named for each method you handle:
export function GET() { /* … */ }
export function POST() { /* … */ }
export function PATCH() { /* … */ }
export function DELETE() { /* … */ }The method names are GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
If a request uses a method the file does not export, the response is:
{ "error": "Method PUT not allowed" }with status 405 and an allow header listing the methods the file does export.
HEAD falls back to GET when the file exports no HEAD function, so you rarely need to write one.
Receiving the request#
Each handler receives one object with the route params and the request:
// app/api/users/[id].ts
export async function GET({ params, request }: { params: Record<string, string>; request: Request }) {
const url = new URL(request.url);
const includePosts = url.searchParams.get("posts") === "1";
const user = await findUser(params.id, { includePosts });
if (!user) return Response.json({ error: "Not found" }, { status: 404 });
return Response.json(user);
}Returning values#
What a handler returns decides the response:
| Return value | Response |
|---|---|
A Response | Sent unchanged. Use this when you need headers or a status. |
undefined | 204 No Content. |
| Any other value | 200 with the value as JSON. |
Plain values are serialized with Response.json. A value that cannot be serialized, such as a circular object, causes a server error.
export async function POST({ request }: { request: Request }) {
const body = await request.json();
const created = await createItem(body);
return Response.json(created, { status: 201, headers: { location: `/api/items/${created.id}` } });
}Reading the body#
const json = await request.json(); // JSON bodies
const form = await request.formData(); // form bodies
const text = await request.text(); // raw textFor forms that should be validated, use parseForm from @kiln-js/server. See Forms and validation.
Errors#
Throw HttpError, or use the shortcuts notFound, forbidden, and redirect, from @kiln-js/core. Under /api/, the response is JSON with the error message:
import { notFound } from "@kiln-js/core";
export async function GET({ params }: { params: Record<string, string> }) {
const item = await getItem(params.id);
if (!item) notFound("No item with that id");
return item;
}The response is 404 with { "error": "No item with that id" }.
An unexpected error (anything that is not an HttpError) is not caught by the API layer. It goes to the server log and the visitor gets a server error.
Authentication#
API routes are not signed in by default. Read the session in the handler, or use requireUser from @kiln-js/auth:
import { requireUser } from "../lib/auth";
export async function GET({ request }: { request: Request }) {
const user = await requireUser(request); // throws 401 when not signed in
return Response.json({ id: user.id, name: user.name });
}CORS and CSRF#
Cross-origin access to /api/ is off until you turn CORS on, and CSRF checks are off until you turn them on. See Security.
Calling API routes from the browser#
The same origin is the simplest case, and needs nothing special:
const res = await fetch("/api/health");
const data = await res.json();Testing#
Call handlers as functions with a Request you build yourself:
const res = await GET({ params: {}, request: new Request("http://localhost/api/health") });Or run bunx kiln test /api to render each route and report failures.

