#API Routes
TypeScript and Go API endpoints under /api.
API routes live in src/api/ and can be written in TypeScript/JavaScript
or Go. Both compile into the same /api/* namespace and can be mixed per
route. When a .go and a .ts/.js file map to the same /api path, the
compiled Go route takes precedence.
Route mapping follows the page convention:
| File | Route |
|---|---|
src/api/hello.ts |
/api/hello |
src/api/users/index.go |
/api/users |
src/api/users/[id].go |
/api/users/{id} |
#JS/TS routes
JS/TS routes are compiled and served by the embedded QuickJS runtime by default (no Node.js process) or by a Node/Bun/Deno sidecar when configured.
Each route is compiled twice: a self-contained IIFE bundle for the embedded
runtime and an ESM output for the Node sidecar. Routes that import a Node
built-in or a native module that cannot be bundled are marked Node-only and
transparently forwarded to the sidecar. Packages with a native .node addon
(@napi-rs/canvas, sharp) are detected and stay in node_modules; list other
packages that must not be bundled in
serverExternalPackages.
The embedded runtime cannot load a native addon at all, so such a route always
runs on the Node sidecar; middleware is bundled into one file and cannot import
one (call the addon from an API route).
#Runtime model and performance
- The embedded runtime keeps a pool of long-lived VMs (
ssr.apiWorkers, defaultmin(NumCPU, 8)). Each worker loads a route module once and reuses it, so a request is a single handler call rather than a fresh VM plus a full re-evaluation. Requests run in parallel across workers. - Module state persists per worker across requests (the same semantics as
Node/Next: a module's top-level state survives between requests). Set
ssr.apiIsolation: trueto run every request in a fresh VM instead. - The Node sidecar runs
node:clusteracrossssr.nodeWorkersprocesses, and imports each route once (module cache) in production. - Set
ssr.apiRuntime: "bun"to run the JS/TS routes in a Bun sidecar usingBun.serve(no Nodehttpstack, no cluster shim) - the fastest of the sidecar options.ssr.apiRuntime: "node"(or"deno") uses the Nodehttpsidecar instead. The top-levelruntime: "bun"selects the same Bun server when no explicitapiRuntimeis set. A route is bundled only for the runtime that serves it (plus Node for a Node-only route under the embedded runtime), so rebuild after changingapiRuntime. - Go API routes (
src/api/*.go) remain the fastest option; the sidecar binary is a compiled Go server.
#Web APIs in the embedded runtime
Route handlers receive a standard Web Request and return a Response; the
embedded runtime implements the platform APIs they usually need, and behaves
like the Node sidecar for them (the same route code is compared against both
in the test suite):
Request,Response(json,redirect,error, body streams),Headers(case-insensitive, iterable,getSetCookie()),FormData(urlencoded and multipart bodies),Blob/File,URL/URLSearchParams(spec parsing; an invalid URL throws),AbortController/AbortSignal,ReadableStream.request.json(),.text(),.formData(),.arrayBuffer()and.blob()return promises, soawait req.json().catch(() => null)works.request.cookies(get,getAll,has, read-only) andrequest.nextUrl(aURLwithbasePathandclone()) are available as in Next.js.TextEncoder/TextDecoder(UTF-8),atob/btoa,structuredClone,queueMicrotask,performance.now(), realsetTimeout/setInterval(handlers canawait new Promise((r) => setTimeout(r, 100))),fetch, andcrypto.getRandomValues/randomUUID/subtle.digest/ HMACsubtle.importKey,signandverify.
Anything the embedded runtime does not implement (for example TransformStream,
WritableStream, WebSocket, Buffer, AES in crypto.subtle) throws a
NotSupportedError naming the API and suggesting ssr.apiRuntime: "node", and
the error is logged. The build reports the same APIs ahead of time: when a route
is built for the embedded runtime, each unsupported global it (or a dependency
it bundles) uses is a KR7160 warning
with the file, line, column and an alternative. The full list, with what is
partial and the tests behind each entry, is in the
API runtime compatibility reference,
generated from the ledger the compiler checks against.
A handler that stays pending longer than 30 seconds (KRATE_API_TIMEOUT) is
answered with 504 (see Timeouts). Request and response bodies, binary included, are copied into and out
of the VM as raw bytes, so a megabyte body costs about a millisecond each way.
While a handler holds a body, the VM's memory limit (KRATE_JS_MEMORY_MB,
default 32) grows by twice the body length when it is read as bytes or form
data and five times when it is read as text or JSON; a handler that loops over
a large body byte by byte in JavaScript is still much slower than on Node.
#Methods, errors and streaming
- Exporting only some methods returns
405with anAllowheader for the rest;HEADis served fromGET(headers only), andOPTIONSis answered automatically withAllow. A default export handles every method. - A handler that throws is logged (route, status, message, and the stack in
krate dev). In production the response body is the generic{"error":"Internal Server Error"};krate devincludes the message. /apirequests appear in the access log, and middleware (see Middleware) runs in front of them.- A
Responsewith aReadableStreambody streams to the client as it is produced (Server-Sent Events work on the QuickJS and Node runtimes); streaming responses extend the server write deadline. - Several
Set-Cookieheaders on one response are all delivered.
#Modern pattern (recommended): named method exports
// src/api/users.ts
export async function GET(request: Request) {
const users = await db.getUsers();
return Response.json(users);
}
export async function POST(request: Request) {
const body = await request.json();
const user = await db.createUser(body);
return Response.json(user, { status: 201 });
}A route file also receives the dynamic route segments as a second argument, matching Next.js route handlers:
// src/api/users/[id].ts
export async function GET(request: Request, context: { params: { id: string } }) {
return Response.json({ id: context.params.id });
}[...slug] and optional [[...slug]] segments are passed as slash-joined
strings. A default export with two parameters keeps the Node-style
(req, res) signature.
#Legacy pattern: default export
// src/api/legacy.ts
export default function handler(req, res) {
res.json({ message: 'legacy pattern' });
}#Timeouts
A JS/TS route has 30 seconds to return its Response. A handler that has not
returned by then is answered with 504 Gateway Timeout and the body
{"error":"Gateway Timeout"}, and the work is aborted where it can be:
request.signal aborts at the deadline, so pass it to fetch and other
cancellable calls. Streaming responses are not cut once the headers are sent;
the embedded runtime still applies the budget to each chunk, and a stream that
is silent for that long ends.
Raise the limit for one route with a maxDuration export, in seconds, the same
export Next.js route handlers use:
// src/api/export.ts
export const maxDuration = 120;
export async function GET(request: Request) {
const rows = await buildExport({ signal: request.signal });
return new Response(rows, { headers: { "Content-Type": "text/csv" } });
}Krate reads the value when it builds the route, so it must be a constant
positive whole number of seconds (60 or 5 * 60, at most 3600). Anything else
(a variable, 0, 1.5) is ignored with a KR8601
warning and the route keeps the default. A route without maxDuration uses
KRATE_API_TIMEOUT (a Go duration such as 45s, default 30s), which is also
the default for routes that do not set one.
How each target applies it:
| Target | Behavior |
|---|---|
krate dev, krate start, Docker |
The embedded runtime, the Node/Bun/Deno sidecar and the proxy in front of it all use the route's value, so a long route is not cut at 30 seconds anywhere on the path. |
krate deploy --target node |
The portable server answers 504 and aborts request.signal at the deadline of routes that set maxDuration. Routes without it have no limit. |
vercel |
One function serves every route, so the longest maxDuration in the project becomes the function's maxDuration in .vc-config.json (it also applies to pages rendered by that function). Vercel caps it by plan. |
netlify |
The handler enforces maxDuration, but Netlify limits function run time by plan and the project cannot configure it, so the deploy prints a warning: Netlify may stop the function sooner. |
cloudflare |
The handler enforces maxDuration; Workers set no wall-clock limit while the client stays connected. |
Legacy (req, res) default-export handlers are not time-limited by maxDuration.
#After the response
after(task) from @krate/runtime/server mirrors after() in next/server:
it schedules work, a function or a promise, to run once the response has been
sent, for logging, analytics or warming a cache. Tasks run in registration
order, a task that throws is logged and does not stop the next one, and
revalidatePath/revalidateTag calls made inside a task are applied when the
tasks finish.
import { after } from "@krate/runtime/server";
export async function POST(request: Request) {
const body = await request.json();
after(async () => {
await fetch("https://metrics.example.com/events", { method: "POST", body: JSON.stringify(body) });
});
return Response.json({ ok: true });
}On the Node, Bun and Deno sidecars and in the portable serverless handler the
tasks start after the handler has returned its response (the serverless handler
passes them to the platform's waitUntil; on Cloudflare that is the Worker's
ctx.waitUntil, also for after() called while a page renders or in middleware).
The embedded QuickJS runtime has no
request-scoped store: there after() runs the task on the next microtask turn,
which is right after the handler settles but may be cut short when the response
finishes the request. Use the Node runtime (ssr.apiRuntime: "node") for work
that must complete.
#Go routes
Go routes (src/api/*.go) are compiled into a dedicated Go sidecar binary
(.krate/goapi-server[.exe]) for maximum performance and true concurrency. The
main server reaches it over an AF_UNIX socket (.krate/run/goapi.sock)
rather than a loopback port, so no port is consumed and the hop skips the TCP
stack; it falls back to a loopback port only if the socket cannot be created.
#Quick start (Go routes)
-
Install the Go toolchain (1.21+) and make sure
gois onPATH. Go routes are compiled withgo buildat build time. -
Add a file under
src/api(the defaultgo.apiDirs). No config is required for the default layout; add thegoblock only to change paths or pull in third-party modules. -
Set up editor intellisense (optional but recommended):
krate go:initThis writes a
go.mod+go.work, vendors the helper module under.krate/goext, and adds.krate/typesto yourtsconfig.jsonsogoimports/gopls resolve thegoext/runtimeimport. -
Run
krate devand hit the route.
// src/api/hello.go - GET /api/hello
package api
import (
"net/http"
runtime "github.com/kratejs/krate/packages/compiler/goext/runtime"
)
func GET(w http.ResponseWriter, r *http.Request) {
runtime.WriteJSON(w, 200, map[string]interface{}{"hello": "world"})
}Each file defines a Handler(w, r) function for all methods, and/or named
GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD functions for per-method
dispatch. Dynamic segments use [param] file names and are read with
r.PathValue("param"):
// src/api/users/[id].go - all methods on /api/users/{id}
func Handler(w http.ResponseWriter, r *http.Request) {
runtime.WriteJSON(w, 200, map[string]interface{}{"id": r.PathValue("id")})
}Go routes require the Go toolchain at build time.
The helper packages live at real import paths
(github.com/kratejs/krate/packages/compiler/goext/runtime and
.../goext/krate) so goimports/gopls provide intellisense. Run krate go:init
once to write a project go.mod + go.work and vendor the helper module under
.krate/goext, so the imports also resolve offline at build time. krate doctor
reports whether the setup is complete.
#Packages, helpers, and dependencies
The src/api tree is preserved when it is compiled: a file that defines no
handler is treated as a helper and keeps its package clause, so sibling and
internal packages stay importable at krate-goapi/routes/<dir>:
// src/api/lib/util.go
package lib
func Message() string { return "hi" }
// src/api/hello.go
package api
import (
"net/http"
"krate-goapi/routes/lib"
runtime "github.com/kratejs/krate/packages/compiler/goext/runtime"
)
func GET(w http.ResponseWriter, r *http.Request) {
runtime.WriteJSON(w, 200, map[string]interface{}{"msg": lib.Message()})
}Third-party modules are declared under go (or via a project-root go.mod,
which is merged - its require/replace/exclude directives are copied and
relative replace paths rebased):
// krate.config.ts
go: {
deps: [{ path: "github.com/google/uuid", version: "v1.6.0" }],
replaces: [{ from: "example.com/local", to: "../local" }],
},A src/api/go.mod (with an optional go.sum) is used verbatim for full
control. The compiled sidecar binary is cached by the content of src/api and
the module config, so unchanged routes skip go build. See
Config Reference.
#Custom API sidecar
You can run your own HTTP service (any language) and let Krate forward /api/*
to it. Krate forwards the request first; if your service returns 404, the
request falls through to Krate's built-in Go/TS/QuickJS routes, and finally to a
404 if nothing matches. Because the sidecar sees the full path, it can own
dynamic routes itself (/api/users/123, /api/blog/2024/hello) with no route
declaration:
// krate.config.ts
export default defineConfig({
api: {
sidecar: {
// Supervised: Krate starts/stops the process and restarts it if it exits.
command: "node",
args: ["server.js"],
port: 8080,
// ...or attach to an already-running service:
// target: "http://127.0.0.1:8080",
},
},
});The sidecar process receives PORT and KRATE_API_SIDECAR_PORT in its
environment. Set prefix (default /api) to give the sidecar a different
subtree. See Config Reference.
Last updated: 2026-11-17
Contributors: Noinkin