This site counts visits with analytics cookies only if you accept. Read the consent

Skip to content

API ReferencecreateHandler

createHandler

Universal adapter factory that creates Web Standard handlers for proxy-mode requests from any framework.

6 min readUpdated proxy mode

Import

ts
import { createHandler } from "@noverax/courier/server"

Signature

createHandler takes an optional configuration and returns handlers that work with Web Standard Request/Response.

ts
declare function createHandler(config?: HandlerConfig): AdapterHandler
ts
import { sources } from "@/api"

const { handle, handleGet, handlePost } = createHandler({ sources })

Parameters

config.sources

A record of API source definitions created with defineApi(). Given, the handler answers for those sources alone, and a later registerSources() in the same process does not change what it serves. Left out, the handler reads the process-wide registry that registerSources() and attachRuntime() fill, at request time — which is how every framework adapter works.

Other options

OptionDefaultDescription
allowedOriginsown origin; local ports in development, for an app served locallyOrigins of other pages that may call the proxy — see Origin Validation
allowedHostsloopback names and IP literals; every name in productionHost names the app is reached by; a request for any other gets 421 — see Host validation
maxBodyBytes1 MBLargest JSON envelope the handler reads; a larger one is refused with 413
maxUploadBytes10 MBLargest multipart/form-data upload the handler reads; a larger one is refused with 413
uploadMode"auto"Where an upload is kept while the call runs: memory up to uploadMemoryBytes, then disk where there is one; "memory" never writes one to disk; "stream" keeps none of it and sends it on as it arrives — see where the proxy keeps an upload
uploadMemoryBytes1 MBHow much of one upload's files stays in memory before the rest goes to disk
totalUploadMemoryBytes64 MBHow much every upload together keeps in memory at once, files and text fields: past it a file goes to disk, or an upload that must stay in memory is refused
totalUploadDiskBytes1 GBHow much every upload together keeps on disk at once: past it an upload is refused
uploadDirectoryos.tmpdir()Where each upload's own folder is made, removed once its call is done
maxUploadParts1000Most parts one upload may hold: its fields and files, and the call's options the client writes first
bodyIdleTimeoutMs30 secondsLongest pause between two pieces of a request body
bodyTimeoutMs5 minutesLongest a request body may take to arrive
sseHeaders—Extra response headers on every SSE stream
sseMaxLifetimeMs30 minutesLongest an SSE stream stays open before the client reconnects with Last-Event-ID
maxSSEConnectionsunlimitedMost SSE streams open at once, each counted from its request on, while its middleware and onSSEConnect run; one more is answered 503
onSSEConnect, onSSEDisconnect, onSSEError—SSE lifecycle hooks

Every option is optional, so createHandler() is a complete call. A body option that could not work as written — a size or a count that is not a whole number, a limit of no bytes or parts, an upload mode it does not have, a wait no timer keeps — is refused where the handler is made, with a ConfigurationError of code BODY_OPTIONS_INVALID.

Request bodies

The handler reads a body as it arrives and refuses it, with the status and code below, as soon as it can tell; what the client still sends is taken off the connection, so a browser reads the answer once its upload is done.

The bodyAnswercode
Declares, or sends, more than its limit413BODY_TOO_LARGE
Ends before the length its Content-Length declares — something in front of the route cut it short, as a Next.js proxy does413BODY_INCOMPLETE
Runs past its Content-Length, or names one that is not a length400BODY_MALFORMED
Is compressed (Content-Encoding)415BODY_ENCODING_UNSUPPORTED
Sends nothing for bodyIdleTimeoutMs, or is still arriving bodyTimeoutMs after it began408BODY_TIMEOUT
An upload of more than maxUploadParts parts, the call's options among them413UPLOAD_TOO_MANY_PARTS
An upload whose text fields together take more than maxBodyBytes413UPLOAD_FIELDS_TOO_LARGE
An upload with a part whose headers take more than 8 KB413UPLOAD_PART_HEADERS_TOO_LARGE
An upload that does not parse as multipart/form-data — see what the proxy takes400BODY_MALFORMED
An upload the disk has no room left for507UPLOAD_STORAGE_FULL
An upload left no room by the others the process keeps, with Retry-After: 5503UPLOAD_CAPACITY_REACHED

A JSON envelope must be UTF-8; one that is not is answered 400.

Return Type

ts
type AdapterHandler = {
  /** Routes GET, POST and SSE; answers any other method with 405 */
  handle: (request: Request) => Promise<Response>
  handleGet: (request: Request) => Promise<Response>
  handlePost: (request: Request) => Promise<Response>
  handleSSE: (request: Request) => Promise<Response>
  /** The SSE streams open right now */
  readonly sseConnections: SSEConnectionRegistry
  /** Tell every SSE client to reconnect later, then close the streams */
  shutdownSSE: (options?: { retryMs?: number; drainMs?: number }) => Promise<void>
}

Framework Adapters

Each framework has a dedicated adapter package that wraps createHandler(). Every adapter is zero-arg — sources are read at request time from the core global registry populated by registerSources() (manual) or attachRuntime() (auto-loads courier.config.ts).

Next.js

instrumentation.ts
import { registerSources } from "@noverax/courier/server"

export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const { sources } = await import("./api")
    registerSources(sources)
  }
}
app/api/request/route.ts
import { apiRoute } from "@noverax/courier-next"

export const { GET, POST } = apiRoute()

Express

server.ts
import { registerSources } from "@noverax/courier/server"
import { courierHandler } from "@noverax/courier-express"
import { sources } from "./api"

registerSources(sources)
app.use("/api/request", courierHandler())

Hono

server.ts
import { registerSources } from "@noverax/courier/server"
import { courierHandler } from "@noverax/courier-hono"
import { sources } from "./api"

registerSources(sources)
app.all("/api/request/*", courierHandler())

Fastify

server.ts
import { registerSources } from "@noverax/courier/server"
import { courierPlugin } from "@noverax/courier-fastify"
import { sources } from "./api"

registerSources(sources)
fastify.register(courierPlugin, { prefix: "/api/request" })

NestJS

courier.middleware.ts
import { registerSources } from "@noverax/courier/server"
import { courierMiddleware } from "@noverax/courier-nestjs"
import { sources } from "./api"

registerSources(sources)

export class CourierMiddleware {
  use = courierMiddleware()
}

Nuxt

server/plugins/courier.ts
import { registerSources } from "@noverax/courier/server"
import { sources } from "~/api"

export default defineNitroPlugin(() => registerSources(sources))
server/api/request/[...].ts
import { courierHandler } from "@noverax/courier-nuxt"

export default courierHandler()

Request Flow

bash
# Every request:
# 1. Refuse a host the app is not reached by (421)
# 2. Answer a preflight; refuse another site's page (403)

# POST request flow:
# 3. Read the endpoint from the URL: _s (source), _g (group), _m (method)
#    — the call is known, and shown in Studio, before its body arrives
# 4. Read the body within its limit (413): { variables, options } as JSON,
#    or the user's form behind an _options field
# 5. Call executeRequest(sources, payload, context) and return its answer

# GET request flow:
# 3. Read the endpoint, _v (variables, JSON) and _o (options) from the URL
# 4. Call executeRequest(sources, payload, context) and return its answer

Security

Marked Endpoints

The handler serves an endpoint only when a mark opens it — .expose() on the endpoint, or expose on its group or its API, the nearest deciding — and answers any other exactly as a name the source does not define, 400, so a caller guessing names learns nothing of what exists. See Exposing Endpoints.

Origin Validation

The handler refuses a request another site's page made with 403 { success: false, message: "Origin not allowed", code: "ORIGIN_NOT_ALLOWED" }. The browser's Sec-Fetch-Site decides where it is sent; otherwise the Origin must be the origin the request was addressed to. Pages on other origins are served when allowedOrigins lists them — see Proxy Mode for the whole rule.

ts
const handler = createHandler({ allowedOrigins: ["https://admin.example.com"] })

Header Whitelisting

Only safe headers are forwarded from the browser to the backend. Extend the whitelist with allowedHeaders in your defineApi() options.

Web Standard

createHandler works with any runtime that supports the Web Standard Request/Response API — Node.js, Deno, Bun, Cloudflare Workers, and more. Framework adapters handle the mapping from framework-specific types.