server-setup
Hono transport for an oRPC router: serviceServerApp mounts the OpenAPI handler (/api), the RPC handler (/rpc), health at healthRoute (default /; move it when / belongs to a UI), /openapi.json and /docs, and createOrpcServer builds the handlers and the OpenAPI document. Also exports the request context, exceptions, graceful-shutdown and free-port (findFreePort({ from, host, attempts?, exclude? }): the first port from from upward that host can listen on; exclude holds ports already picked but not listening yet).
API
createOrpcServer,serviceServerApp: build the HTTP server for a service.serviceServerAppalso takesmounts(see Mounts) andcorsOrigins(see CORS).createOpenApiNormalizer: normalizes the generated OpenAPI document (config:OpenApiNormalizerOptions).findFreePort,gracefulShutdown,handleUncaughtException,handleUnhandledRejection: process helpers.exceptions,./context: error and request-context helpers../client-ip-rate-limit:createClientIpRateLimitMiddleware()applies a procedure'srateLimitmeta per client IP (lastx-forwarded-forentry), withRetry-AfterandRATE_LIMIT_EXCEEDED. Put it before authentication.
Errors
Every error a procedure throws goes through handleError from app-errors: the full classification is logged
with the request's logger, and only the public code, status, message and data reach the client. A request body that is not
JSON fails while oRPC decodes the input, before any procedure runs; a request-level interceptor sends it through the same path as
SYNTAX_ERROR (400), which transportContractErrors declares on every contract.
OpenAPI normalizer
The generated document is post-processed by createOpenApiNormalizer(options). It returns (spec) => spec and is wired through the optional openApiNormalizer option of serviceServerApp and createOrpcServer. With no option you get the stack behaviour; every key below is optional and product-specific, so it lives in the service, not here.
| Option | What it does | Default |
|---|---|---|
arrayObjectIdProperties | Property names whose array items become $ref MongoObjectId | ["_ids"] |
componentSchemaOverrides | Component schemas replaced wholesale when present, e.g. a numeric enum Zod emits without type (the Dart generator needs type: "integer") | MongoObjectId only |
defaultedEnumComponentNames | Shared enum components with a Zod .default(...); required is restored on response schemas (not Create*/Update* inputs) | none |
operationResponseSchemas | { method, path, schema } entries merged into one operation's 200 JSON response, in key order; an undefined value removes a key | none |
scalarObjectIdProperties | Property names that become $ref MongoObjectId | ["_id", "userId"] |
serviceServerApp(router, {
// ...
openApiNormalizer: {
componentSchemaOverrides: { Qos: { default: 0, enum: [0, 1, 2], type: "integer" } },
scalarObjectIdProperties: ["_id", "workspaceId"],
},
});Always on, whatever the config.
- inline objects and enums identical to a component are replaced by a
$ref, and*ErrorMetadataduplicates are collapsed; - oRPC error unions become a
discriminatoroverORPCError_<code>components; withMutationResultSpecandwithResponseSchemaSpecoperations point atMutationResult/ the named component (a list endpoint keeps its array and names onlyitems);- colon/dash-delimited string enums get
x-enum-varnames.
Mounts
serviceServerApp takes an optional mounts list of plain Fetch-API handlers served beside the oRPC routes, for example Better Auth's auth.handler.
serviceServerApp(router, {
// ...
mounts: [
{
handler: auth.handler,
openApi: { document: () => auth.api.generateOpenAPISchema(), namespace: "Auth" },
path: "/api/auth",
},
],
});Type: mounts?: readonly { handler: (request: Request) => Response | Promise<Response>; openApi?: { document: () => unknown | Promise<unknown>; namespace: string }; path: string }[].
- The handler is registered at
pathandpath/*, after evlog and compress and before/api/*.pathis appended to themainRoutesthatserviceServerAppreturns. pathmust start with/; trailing slashes are stripped. A mount withopenApimust sit under/api/.- The
openApidocument is fetched lazily on the first/openapi.jsonrequest. It is cached on success and retried on failure. It is merged after the oRPC spec is normalized.- paths are re-prefixed with the mount path minus
/api(mount/api/authgives/auth/...); - every component section is namespaced with
namespace(UserbecomesAuthUser) and its$refs are rewritten; - the document's top-level
securityis moved onto its own operations; - new tags are appended;
info,serversandopenapiare dropped; - a clash on a path, component or operationId throws, and
/openapi.jsonanswers 500.
- paths are re-prefixed with the mount path minus
- Mounted handlers sit outside oRPC's
CORSPlugin, so a cross-origin UI needscors()on the mount: setcorsOriginson the mount (credentialedcors()for that mount only, exact origins). - Callers that pass no
mountsare unchanged.
CORS
corsOrigins?: readonly string[] (on createOrpcServer and serviceServerApp) lists the browser origins allowed to call /rpc and /api with credentials, for a UI on another origin that sends cookies.
serviceServerApp(router, { ...options, corsOrigins: ["http://localhost:4200"] });- Each listed origin gets
access-control-allow-origin: <origin>andaccess-control-allow-credentials: true, on a preflight and on the real request. Any other origin gets noaccess-control-allow-origin, so the browser blocks it.Vary: Originis set. - A preflight echoes the requested headers, so
AuthorizationandContent-Typepass. - Use exact origins, never
*(browsers reject it with credentials). - Omitted: oRPC's default
CORSPluginapplies unchanged (any origin reflected, no credentials). - It does not reach
mounts; each mount has its owncorsOrigins.
Commands
pnpm nx run server-setup:typecheck # type-check the package
pnpm nx run server-setup:test # run the Vitest suite