API Routes
Expose HTTP handlers from src/app/api and validate input with schemas before handler code runs.
Route handlers
API route modules export HTTP methods. Farm.js discovers them, runs the route pipeline, and can generate typed client callers from the route shape.
Routes in one app source must have distinct URL shapes. For example, /api/users/[id] and
/api/users/[slug] conflict even though their parameter names differ. Parameters must have unique,
non-reserved names, and catch-alls must be the final segment. These checks also run in RSC builds.
If a project overrides a layer's equivalent dynamic shape, the project route replaces it completely,
so handlers do not receive parameters named by the lower-priority route.
import { createEndpoint } from "@farm.js/core/api";
import { z } from "zod";
export const POST = createEndpoint(
{
body: z.object({
name: z.string().min(1),
}),
},
async ({ body }) => {
return Response.json({ message: "Hello " + body.name });
},
);The export name sets the HTTP method, so route files don't pass method. An endpoint without
schemas or other options can take the handler alone:
import { createEndpoint } from "@farm.js/core/api";
export const GET = createEndpoint(async () =>
Response.json(await getStars(), {
headers: { "cache-control": "public, s-maxage=600, stale-while-revalidate=3600" },
}),
);method only matters for endpoints created with an explicit path, such as
createEndpoint("/api/settings", { method: "POST" }, handler), which have no export name to read it
from. There it defaults to GET.
Use createApiClients() in one shared src/lib/api.ts to return { api, apiClient }
from the generated router. Both callers reuse this route definition: api dispatches locally on
the server and apiClient sends HTTP requests. Endpoint middleware runs for both; outer HTTP
middleware is not replayed by direct calls. Never import endpoint modules into the shared caller file.
Experimental Rust, Go, and Python routes
Opt in by adding Polyroute to vite.plugins. Farm.js discovers src/app/api/**/route.rs,
src/app/api/**/route.go, and src/app/api/**/route.py and serves them through the same API
router and middleware as a TypeScript handler. Removing the plugin turns this discovery off. This
early integration has been tested with the Node server target and Polyroute’s default V8
WebAssembly runtime.
Rust, Go, and Python route discovery ships in Farm.js 0.2.0, and these routes join the generated
API client in 0.2.1. To use the versions tested together, install Farm.js core, the CLI, and
Polyroute in your app. Add the Rust target on the machine where you build the app.
pnpm add --save-exact @farm.js/core@0.2.1
pnpm add -D --save-exact @farm.js/cli@0.2.1 @farming-labs/polyroute@0.1.0-beta.5
rustup target add wasm32-wasip2import { defineConfig } from "@farm.js/core";
import { polyroute } from "@farming-labs/polyroute";
export default defineConfig({
vite: { plugins: [polyroute()] },
});For example, put the prime-counting handler
at src/app/api/primes/route.rs. Start farm dev and request /api/primes?limit=10 to get
{"limit":10,"primes":4}. The Rust handler decides which HTTP methods it accepts.
A Go route is a main package with its own go.mod beside route.go, built with Go 1.27.1 or
newer. Other .go files in that directory belong to the route, but only route.go defines the URL.
Copy Polyroute’s slug handler
(route.go, go.mod, and go.sum) into src/app/api/slug/, then request
/api/slug?text=Hello%20Farm to get {"slug":"hello-farm","text":"Hello Farm"}. The first build
downloads the route’s Go modules, so it needs the Go module proxy or a module cache that has them.
A Python route defines a function per HTTP method, such as def POST(request: Request) -> Response,
with Request and Response imported from Polyroute’s polyroute module. It can import the
standard library and modules beside route.py, but only route.py defines the URL. Build it with
componentize-py 0.25 (pip install componentize-py==0.25.1). Copy Polyroute’s
stats handler
to src/app/api/stats/route.py, then POST [1, 2, 3, 4] to /api/stats to get
{"count":4,"mean":2.5,"median":2.5}. componentize-py runs the route’s top-level code once, at
build time, and snapshots the result.
From Farm.js 0.2.1, the generated API client includes these routes. Farm.js can’t read a schema
from Rust, Go, or Python, so by default the route gets every HTTP method, untyped: a call accepts
any query and body, and data is any. A method the handler doesn’t accept returns the
handler’s own response, such as a 405.
To type a route, add a TypeScript declaration file beside it: route.d.rs.ts for route.rs,
route.d.go.ts for route.go, or route.d.py.ts for route.py. Declare each method the handler
accepts with TypedEndpoint<Body, Query, Response>:
import type { TypedEndpoint } from "@farm.js/core/api";
export declare const GET: TypedEndpoint<
never,
{ limit: number },
{ limit: number; primes: number }
>;The client then offers only apiClient.primes.get(), requires a numeric limit, and types data
as { limit: number; primes: number }. farm dev regenerates the client when the file changes, and
farm generate and farm build read it too. Nothing checks the declaration against the handler,
so keep the two in step when you change either one.
Run farm build on a machine with the toolchain for each route language. The deployed server
needs none of them. How a route loads its compiled WebAssembly depends on the target:
- Node server, Vercel, and Netlify read it from files beside the server code, so deploy the
whole output.
farm build --preset node-serverwrites the files next to the server bundle, and the Vercel and Netlify builds put them inside the server function. Called locally, the built Vercel and Netlify functions served Rust, Go, and Python routes; they haven't run on a deployment yet. - Cloudflare can't read those files, and workerd refuses to compile WebAssembly from bytes.
From Farm.js
0.2.5with Polyroute0.1.0-beta.5or newer, a Cloudflare build imports each route's WebAssembly as a Worker module instead, which Cloudflare compiles when the Worker is uploaded. With an older Polyroute, the build fails and names the upgrade. A Worker can't run Polyroute'sexperimental.workersorexperimental.runtime: "wasmtime", so a Cloudflare build with either fails and says to remove it. Farm.js0.2.5isn't released yet, so the Farm.js0.2.1the install command above pins builds these routes for the Node server, Vercel, and Netlify, not Cloudflare. The Worker's size limit, 3 MB compressed on the Free plan and 10 MB on Paid, decides which routes fit. Compressed, the Rust prime-counting route added about 120 KiB, the slug route about 415 KiB built with TinyGo and 1.9 MiB with Go, and the Python stats route about 6.1 MiB. Deployed with Wrangler 4.171.0 and thecloudflare-modulepreset, a Worker with a TypeScript route and the Rust, TinyGo, and Python example routes started in under 10 ms, and every route answered. Measured from one client, including the network, the TypeScript, Rust, and TinyGo routes answered in 72 to 272 ms. The Python route took 1.05 s on its first request, which instantiates its 11 MB uncompressed core module in that isolate, and 0.16 to 0.71 s on the four after it. The test didn't record which isolate served each request.
The Node server starts each route before it listens, so a route's first request doesn't wait for
its WebAssembly to compile and its instance to start. This shipped in Farm.js 0.2.0-beta.2 and needs
Polyroute 0.1.0-beta.2 or newer. With an older Polyroute, each route starts on its first request.
Measured locally, the slug route's first request dropped from 51 ms to 24 ms and the prime-counting
route's from 20 ms to 17 ms, and the server took 29 ms longer to start listening. A route that fails
to start logs the error, and its first request tries again.
Use this for an endpoint whose latency is dominated by computation. In the local Farm.js benchmark at ten connections, Rust lowered warm p95 for the CPU-heavy request from 57.92 ms to 35.00 ms. For a light request on that same route it increased p95 from 3.08 ms to 4.06 ms. Go and Python add more fixed cost per request: Polyroute measured routes that do almost no work at about 4× a TypeScript one. Measure your own endpoint before choosing a language. Benchmark methodology and results.
Worker threads
A route's WebAssembly runs on the server's main thread, so while a Rust route computes, every other
request waits, TypeScript routes included. From Polyroute 0.1.0-beta.3, experimental.workers
moves the routes you list onto worker threads in farm build:
polyroute({
experimental: {
workers: { routes: ["src/app/api/primes/route.rs"], threads: 2 },
},
});List paths from the project root. A path that doesn't match a file fails the build with
INVALID_OPTIONS, so a typo can't leave a route on the main thread. workers: true moves every
route. Each listed route gets its own pool of threads, which defaults to one less than the
server's available parallelism. The Node server starts the threads before it listens. farm dev
still serves every route on the main thread.
List only the routes that compute. Each request to a worker route costs a message to a thread and back, so a route that does little work gets slower. Each thread has its own instance of the route, so global state lasts only across the requests that thread serves, and memory grows with the thread count. In Polyroute's measurement of a Farm.js production server, ten connections counted primes in Rust while a separate TypeScript route took requests. That route's p50 was 24–72 ms with the Rust route on the main thread and 1.4–2.9 ms with it on two worker threads. Method and results.
TinyGo
From Polyroute 0.1.0-beta.3, experimental.tinygo compiles Go routes with TinyGo instead of Go
in farm build. The route's source and go.mod stay the same. The build machine needs TinyGo
0.45 or newer, wasm-tools, and binaryen's wasm-opt.
polyroute({ experimental: { tinygo: { scheduler: "none" } } });For Polyroute's slug route, the compiled route shrank from 6.9 MB to 1.8 MB and its first request
dropped from 137 ms to 65 ms. With scheduler: "none", it shrank to 0.9 MB, its first request
took 40 ms, and its CPU time per request fell from 366 µs to 249 µs. A route that starts a
goroutine, or uses a package that does, fails to build with that setting. tinygo: true keeps
TinyGo's scheduler, which runs goroutines.
TinyGo supports less of Go's standard library and reflection, so some packages don't build. A
TinyGo build is an LLVM compile and takes longer: 25–40 seconds for the slug route. farm dev
still builds Go routes with Go, so a route that only TinyGo rejects fails in farm build, not in
development.
Method and results.
Neither option can be combined with Polyroute's experimental.runtime: "wasmtime"; the build fails
with INVALID_OPTIONS.
MCP tool opt-in
When @farm.js/mcp is installed, a typed endpoint can opt into the authenticated MCP transport
with mcp: true or explicit tool metadata:
export const GET = createEndpoint(
{
mcp: {
name: "list_projects",
description: "List projects visible to the current user.",
readOnlyHint: true,
},
},
async () => ({ projects: await listProjects() }),
);The route still owns validation and endpoint middleware. The top-level mcp config separately owns
transport authentication in farm.config.ts. Alternatively, select explicitly pathed endpoint
instances in mcp.tools and return allowed tool names from mcp.authorize to control discovery
and invocation per caller. The same list can include standalone defineTool() definitions from
@farm.js/mcp for operations without an HTTP route. See the API MCP guide
for mixed composition, generated names, and security boundaries.
Next-style exports
You can also manually export GET, POST, PATCH, and other handlers from the route file. Farm.js keeps this familiar while layering typed helpers around it.
Generated API client types follow runtime value exports. Comments, string examples, and type-only exports named after HTTP methods do not create callable endpoints.
export async function GET() {
return Response.json({ ok: true });
}Validation
Zod and standard schema
Endpoint and integration route inputs can use Zod or compatible standard-schema validators so the handler sees parsed input instead of raw unknown data.
Route file shape
Farm.js follows the familiar route-file convention: each route lives in src/app/api/**/route.ts and exports one or more HTTP methods.
The equivalent route.tsx, route.js, and route.jsx filenames use the same discovery and generated-type behavior.
src/app/api/hello/route.ts -> /api/hello
src/app/api/users/[id]/route.ts -> /api/users/:id
src/app/api/files/[...path]/route.ts -> /api/files/*Static route directory names may contain Unicode. Browsers percent-encode those path segments; Farm.js decodes both the discovered route and request segment before matching them.
Defining the same method and path twice within one app source is an error, including in production RSC builds. The error names both files. Project routes may still override matching methods from a layer; other methods on the layer route remain available.
Use createEndpoint when you want input validation and typed client generation. Use plain GET, POST, PATCH, and friends when you want to handle the raw Request.
Plain handlers always receive that Request; parameter names such as request, context, or ctx
do not change the calling convention. Use createEndpoint for the parsed { body, query, headers }
context.
HEAD follows normal HTTP semantics. A route can export a dedicated HEAD handler, otherwise Farm.js
uses its GET handler and returns the same status and headers without a response body.
This also applies to production RSC builds. They support QUERY exports, prefer an explicit
HEAD handler, and return 405 with an Allow header for unsupported methods.
Body and query input
export const GET = createEndpoint(
{
query: z.object({
q: z.string().optional(),
page: z.coerce.number().int().positive().default(1),
}),
},
async ({ query }) => {
return Response.json({
q: query.q ?? "",
page: query.page,
});
},
);Farm.js parses and validates body, query, and headers before middleware or handler code runs. Header schema keys use the lower-case names exposed by the Fetch Headers API. Invalid input returns a 400 response with structured validation issues. Each issue in details has a path and code. Its message is a generic "Invalid value", because a validator's own message can quote what it expected, such as a literal header token; only refinement messages you write (code: "custom") and type mismatches (code: "invalid_type", which name types, not values) are returned as is.
Generated callers use the schema's input type for body and query values; middleware and
handlers receive its parsed output type. For example, a field declared as
z.string().transform(Number) is sent as a string and received by the handler as a number.
Defaulted fields may be omitted by the caller. The same distinction applies to multipart
toFormData(...) inputs, Standard Schema input/output types, and both api and apiClient
from createApiClients(). Validation still runs on the server; this does not send schemas or
transforms to the browser. Existing endpoints without transforms retain their input types.
Malformed application/json and application/*+json bodies return 400 before endpoint middleware
or handler code executes, including when the endpoint does not declare a body schema. Empty declared
JSON receives the same response for non-QUERY methods. A bodyless QUERY remains valid
because QUERY requires Content-Type and generated clients attach application/json even when the
endpoint declares no body. Malformed multipart/form-data also returns 400 instead of becoming an
absent body; an empty application/x-www-form-urlencoded body is a valid empty form and parses as an
empty object. Callers that omit Content-Type retain the permissive JSON parsing path for
compatibility.
An endpoint whose body schema is JSON (any schema not wrapped in multipart()) answers 415
before middleware or handler code runs when a browser on another origin sends a body declared as
anything other than application/json or application/*+json. text/plain,
application/x-www-form-urlencoded, and multipart/form-data are the types a page on another
site can post with the visitor's cookies and no CORS preflight, so this keeps such a page from
submitting a form that the schema would accept. A request counts as cross-origin when its Origin
(or, without one, its Referer) differs from the app's, or when the browser sends
Sec-Fetch-Site: cross-site; Origin: null is refused too. Unchanged:
- The app's own pages can still post forms to the endpoint, which is how a
<fetcher.Form>submits before hydration. - Callers that send no
OriginorReferer, such as servers and webhooks, keep every content type. - Another origin can still send JSON, which the browser sends only after a CORS preflight that a
routeRulescorsrule allows. Acorsrule does not admit form bodies. - Endpoints without a
bodyschema and plain method exports read the request as before.
To accept form posts from another origin, such as an OAuth response_mode=form_post callback,
wrap the body schema in multipart(). That endpoint then reads urlencoded and multipart bodies
from any origin, and its generated caller takes toFormData(...).
If an upload is aborted while Farm.js is buffering its body, Farm.js rejects it before invoking the endpoint. This does not roll back work in a handler that has already started. On Node, finishing an upload is not an abort: only an interrupted upload or an early response disconnect cancels the request signal.
HTTP QUERY
Use the standardized QUERY HTTP method when a
read operation needs structured request content that is too large or sensitive for a URL. Like
GET, QUERY is safe and idempotent; unlike GET, its request body has defined semantics.
import { QUERY as createQueryEndpoint } from "@farm.js/core/api";
import { z } from "zod";
export const QUERY = createQueryEndpoint(
{
body: z.object({
filters: z.array(z.object({ field: z.string(), value: z.string() })),
limit: z.number().int().min(1).max(100).default(20),
}),
},
async ({ body }) => {
const products = await searchProducts(body.filters, body.limit);
return { products, total: products.length };
},
);The helper infers the validated body inside the handler and exposes the same input and response
types to the generated client. QUERY requests must include a Content-Type header; Farm.js's generated
client sets application/json automatically. A raw handler is also valid:
export async function QUERY(request: Request) {
const search = await request.json();
return Response.json(await searchProducts(search));
}Keep QUERY handlers read-only. Use POST, PATCH, or another unsafe method when the operation
changes server state. A server can advertise accepted query media types with an Accept-Query
response header. Cross-origin browser requests use a CORS preflight, so include QUERY in the
configured cors.methods list when that list is restricted.
Uploads and streaming results
Use multipart() when an endpoint accepts files. Farm.js parses the request as FormData, preserves
Blob/File values and repeated fields, then runs the same body-schema validation used for JSON:
import { createEndpoint, jsonStream, multipart } from "@farm.js/core/api";
import { z } from "zod";
const importBody = multipart(
z.object({
title: z.string().min(1),
file: z.custom<Blob>((value) => value instanceof Blob),
}),
);
type ImportEvent = { phase: "accepted"; bytes: number } | { phase: "complete"; imported: number };
export const POST = createEndpoint(
{
body: importBody,
},
async ({ body }) => {
async function* importEvents(): AsyncGenerator<ImportEvent> {
yield { phase: "accepted", bytes: body.file.size };
const imported = await importRows(body.file);
yield { phase: "complete", imported };
}
return jsonStream(importEvents());
},
);jsonStream() uses newline-delimited JSON (application/x-ndjson). It sends each typed event as
soon as the source yields it, respects response backpressure, cancels the source when the reader
disconnects, and defaults to Cache-Control: no-store. Use ordinary Response objects for binary
downloads or protocols that are not JSON event streams.
The client decoder rejects malformed NDJSON with its original SyntaxError and cancels the
source without waiting for cleanup or an unread response clone. Explicit stream cancellation
and early iterator return still await the producer's cleanup.
When Farm.js bridges a streamed Response to Node, a failed response write also cancels the
upstream body. Put producer cleanup in the stream's cancel() callback. Farm.js preserves the
original write error and does not wait indefinitely for that cleanup to finish.
Disconnects follow the same rule, including when the connection closes under backpressure:
Farm.js releases its reader and response listeners without waiting for app-owned cancellation work.
Endpoint middleware
Put plain async functions in middleware. There is no middleware factory and no next() callback. Functions run in declaration order after endpoint input validation.
import { createEndpoint, type EndpointMiddlewareContext } from "@farm.js/core/api";
import { z } from "zod";
type Session = {
user: { id: string; roles: string[] };
};
async function requireAuth({ request }: EndpointMiddlewareContext) {
const session = await getSession(request);
if (!session?.user) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
return { session: session as Session };
}
const requireRole =
(role: string) =>
async ({ context }: EndpointMiddlewareContext<{ session: Session }>) => {
return context.session.user.roles.includes(role);
};
async function loadProject({
body,
context,
params,
}: EndpointMiddlewareContext<{ session: Session }, { name: string }>) {
const project = await db.project.findUniqueOrThrow({
where: {
id: String(params.id),
ownerId: context.session.user.id,
},
});
return { project };
}
export const PATCH = createEndpoint(
{
body: z.object({ name: z.string().min(1) }),
middleware: [requireAuth, requireRole("admin"), loadProject],
},
async ({ body, context }) => {
// context.session and context.project are inferred from middleware returns.
return db.project.update({
where: { id: context.project.id },
data: { name: body.name },
});
},
);Middleware return values have deliberate control-flow meaning:
| Return value | Result |
|---|---|
| Plain object | Shallow-merges its properties into typed context for later middleware and the handler. |
true | Continues without adding context. |
false | Stops and returns Farm.js's JSON 403 Forbidden response. |
Response | Stops and returns that response unchanged. Use this for custom status, body, or headers. |
Only literal false is the default denial signal. Returning null, undefined, an array, or another value is an error, which catches forgotten returns instead of silently skipping authorization. Context is shallowly frozen, duplicate keys are rejected, and __proto__, constructor, and prototype cannot be provided as context keys.
Endpoint middleware is local to one createEndpoint declaration and can use its validated input. Use src/app/**/middleware.ts for path-level behavior shared by many routes, such as request tracing, common headers, or an early rewrite before endpoint parsing.
Put endpoint guards in middleware. createEndpoint throws if you pass a use option, which Farm.js never ran.
Authorization boundary
Derive users, roles, tenants, and rate-limit identities from the trusted
Requestor server state. Middleware context is created only on the server and is never accepted from client input. Keep resource-specific permission checks close to the resource query even when shared authentication runs in middleware.
Typed expected errors
Declare failures that are part of an endpoint's public contract, then return them through the typed
error function:
export const POST = createEndpoint(
{
body: z.object({
name: z.string().min(1),
}),
errors: {
duplicate: {
status: 409,
message: "A product with this name already exists",
data: z.object({
existingId: z.string(),
}),
},
forbidden: {
status: 403,
data: z.object({
permission: z.string(),
}),
},
},
},
async ({ body, error }) => {
const existing = await findProductByName(body.name);
if (existing) {
return error("duplicate", {
existingId: existing.id,
});
}
return createProduct(body);
},
);Error codes and payloads are checked in the handler and carried into the generated API client:
const result = await api.products.post({
body: { name },
});
if (result.error?.code === "duplicate") {
// existingId is inferred as string.
showExistingProduct(result.error.data.existingId);
}Farm.js validates the failure payload before returning a JSON error response. Declared messages and
payloads are public, so do not include secrets. Undeclared exceptions remain unexpected server
errors and are not converted into a declared failure. Endpoints without an errors declaration
keep the existing Error client type.
The generated client makes this endpoint RPC-like to call, but the transport remains a regular HTTP
request and JSON error response. Existing endpoint definitions using schema and fail continue to
work as deprecated aliases; use data and error in new code for consistency with server functions.
Client inference
Routes become client namespaces from their path:
await api.hello.post({
body: {
name: "Ada",
},
});
await api.users.get({
query: {
limit: 10,
},
});The exact generated shape comes from route generation. Body and query schemas become typed caller input, and path segments become the nested api.users.get style namespace. During farm dev, Farm.js regenerates route/API types when page or API route files are added, changed, or removed. Run farm generate when you want the same refresh outside the dev server.
Declare invalidation with the mutation
When every caller of a mutation makes the same data stale, declare that relationship on the endpoint instead of repeating client-side invalidation:
export const PATCH = createEndpoint(
{
body: z.object({
id: z.string(),
name: z.string().min(1),
}),
invalidates: ({ body }) => [
{ key: ["product", body.id] },
{ key: ["products", "list"] },
{ tag: "products" },
{ path: "/products" },
],
},
async ({ body }) => {
return db.product.update({
where: { id: body.id },
data: { name: body.name },
});
},
);Farm.js applies declared keys, tags, and paths to the server cache after the handler succeeds. Normal
api.products.patch(...) callers also receive the key invalidations through response metadata, so
matching browser queries become stale without repeating an invalidate option. A response with a
status of 400 or higher, or middleware that stops before the handler, does not invalidate.
The resolver receives validated body, query, and headers plus the accumulated typed middleware
context. Invalidation is declarative rather than inferred: database writes do not reliably reveal
every affected query. Existing client-side invalidate options remain supported for
caller-specific cache relationships, and handlers can continue calling invalidate(...) or
revalidatePath(...) directly.
Mount another backend framework
You can mount an existing backend app on a catch-all route and keep its routes, middleware, and validators. Farm.js has two optional helpers, one per calling convention, so any JavaScript backend that exposes either one works. Each returns a handler for every HTTP method, and you export the ones the app handles:
mountFetchHandlerfrom@farm.js/core/apifor any app with a Webfetchhandler, a(request: Request) => Responsefunction or an object with afetchmethod, such as Hono and Elysia.mountNodeHandlerfrom@farm.js/core/api/nodefor any Node.js(req, res)listener, such as Express, Koa, Fastify, and Nest.
The frameworks named on this page are the ones Farm.js's tests mount. Another framework works the same way once you pass its fetch handler or its Node.js listener.
Hono and Elysia
A plain route export receives the Web Request and can return a Response, the same contract as
a Hono or Elysia app's fetch handler. mountFetchHandler accepts an app with a fetch method or
a plain (request: Request) => Response | Promise<Response> function.
import { mountFetchHandler } from "@farm.js/core/api";
import { Hono } from "hono";
const app = new Hono();
app.get("/hello/:name", (c) => c.json({ hello: c.req.param("name") }));
app.post("/echo", async (c) => c.json({ got: await c.req.json() }, 201));
export const { GET, POST } = mountFetchHandler(app, { stripMountPath: true });import { mountFetchHandler } from "@farm.js/core/api";
import { Elysia } from "elysia";
const app = new Elysia()
.get("/hello/:name", ({ params }) => ({ hello: params.name }))
.post("/echo", ({ body, set }) => {
set.status = 201;
return { got: body };
});
export const { GET, POST } = mountFetchHandler(app, { stripMountPath: true });Express, Koa, Fastify, and Nest
mountNodeHandler accepts a Node.js (req, res) listener, or a promise of one for a framework
that starts asynchronously. It runs the listener against an in-memory req and res built from
the request.
import { mountNodeHandler } from "@farm.js/core/api/node";
import express from "express";
const app = express();
app.use(express.json());
app.get("/users/:id", (req, res) => res.json({ id: req.params.id }));
app.post("/users", (req, res) => res.status(201).json(req.body));
export const { GET, POST } = mountNodeHandler(app, { stripMountPath: true });For Koa, pass the app's listener:
export const { GET, POST } = mountNodeHandler(koa.callback(), { stripMountPath: true });For Fastify, wait until the app is ready, then hand each request to its server:
const ready = fastify.ready();
export const { GET, POST } = mountNodeHandler(
async (req, res) => {
await ready;
fastify.server.emit("request", req, res);
},
{ stripMountPath: true },
);For Nest, initialize the app and pass its HTTP adapter's instance. Nest's decorators need
"experimentalDecorators": true in your tsconfig.json.
import "reflect-metadata";
import { mountNodeHandler } from "@farm.js/core/api/node";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "../../../../nest/app.module";
const app = NestFactory.create(AppModule).then(async (nest) => {
await nest.init();
return nest.getHttpAdapter().getInstance();
});
export const { GET, POST } = mountNodeHandler(app, { stripMountPath: true });The app reads the request body as a stream, and its response streams back as soon as it sends headers, so server-sent events work. Some things a Node.js server provides are not available:
- Node.js runtimes only.
mountNodeHandlerimportsnode:http. UsemountFetchHandlerfor edge and worker targets. - No socket.
req.socket.remoteAddressis not set, soreq.ipin Express isundefined. WebSocket upgrades and the framework's ownlisten(), timeouts, and keep-alive settings do not apply; Farm.js's server handles the connection. - Errors go to Farm.js. If the listener throws, rejects, or calls
next(error)before it responds, Farm.js answers as it does for any failed route. A Connect-stylenext()with no response answers404.
Base path
stripMountPath: truehands the app only the part of the path below the catch-all, so its routes don't repeat where Farm.js serves them./api/hono/hello/farmreaches the app as/hello/farm, and the app keeps working if the route moves orapi.basePathchanges. Segments stay encoded as the client sent them. Paths the app builds itself, such as redirect locations, are then relative to the mount rather than to the site.- Without
stripMountPath(the default), the app receives the request unchanged, with the full URL. Give it the route's public path as its base path, such asbasePath("/api/hono")in Hono,prefix: "/api/elysia"in Elysia, orapp.use("/api/express", router)in Express. With any other base path, every request misses its routes and gets the app's own 404.
Without the helper
The helpers only save boilerplate. Exporting a fetch-based app's handler yourself behaves the
same as mountFetchHandler(app) without stripMountPath:
import { Hono } from "hono";
const app = new Hono().basePath("/api/hono");
app.get("/hello/:name", (c) => c.json({ hello: c.req.param("name") }));
const handle = (request: Request) => app.fetch(request);
export { handle as GET, handle as POST };What a mounted app gets from Farm.js
- Only the methods you export. Farm.js answers a method the route file does not export with
405before the app sees it. Leave outHEADto keep Farm.js answering it from yourGETexport, as for any route. Export plain names (export const { GET, POST } = ...): Farm.js reads the route's methods from its export names. - One plain route.
createEndpointfeatures that come from each endpoint's declared shape do not apply to the app's routes: typed client inference, OpenAPI generation, typed errors, MCP tool opt-in, declared invalidation, and endpoint middleware. UsecreateEndpointroutes for those, alongside the mounted app.
These recipes are covered by Farm.js's tests with Hono 4, Elysia 1.4, Express 5, Koa 3, Fastify 5,
and Nest 11 on Node, in development and in a node-server production build.
When to use integrations instead
Use API routes for app-owned endpoints. Use integrations when a provider or feature needs a package-like surface: config validation, lifecycle hooks, database schemas, middleware, providers, and typed callers bundled together.