Skip to Content
gentlemans-stack
ReferenceLibs

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. serviceServerApp also takes mounts (see Mounts) and corsOrigins (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's rateLimit meta per client IP (last x-forwarded-for entry), with Retry-After and RATE_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.

OptionWhat it doesDefault
arrayObjectIdPropertiesProperty names whose array items become $ref MongoObjectId["_ids"]
componentSchemaOverridesComponent schemas replaced wholesale when present, e.g. a numeric enum Zod emits without type (the Dart generator needs type: "integer")MongoObjectId only
defaultedEnumComponentNamesShared 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 keynone
scalarObjectIdPropertiesProperty 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 *ErrorMetadata duplicates are collapsed;
  • oRPC error unions become a discriminator over ORPCError_<code> components;
  • withMutationResultSpec and withResponseSchemaSpec operations point at MutationResult / the named component (a list endpoint keeps its array and names only items);
  • 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 path and path/*, after evlog and compress and before /api/*. path is appended to the mainRoutes that serviceServerApp returns.
  • path must start with /; trailing slashes are stripped. A mount with openApi must sit under /api/.
  • The openApi document is fetched lazily on the first /openapi.json request. 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/auth gives /auth/...);
    • every component section is namespaced with namespace (User becomes AuthUser) and its $refs are rewritten;
    • the document's top-level security is moved onto its own operations;
    • new tags are appended; info, servers and openapi are dropped;
    • a clash on a path, component or operationId throws, and /openapi.json answers 500.
  • Mounted handlers sit outside oRPC's CORSPlugin, so a cross-origin UI needs cors() on the mount: set corsOrigins on the mount (credentialed cors() for that mount only, exact origins).
  • Callers that pass no mounts are 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> and access-control-allow-credentials: true, on a preflight and on the real request. Any other origin gets no access-control-allow-origin, so the browser blocks it. Vary: Origin is set.
  • A preflight echoes the requested headers, so Authorization and Content-Type pass.
  • Use exact origins, never * (browsers reject it with credentials).
  • Omitted: oRPC's default CORSPlugin applies unchanged (any origin reflected, no credentials).
  • It does not reach mounts; each mount has its own corsOrigins.

Commands

pnpm nx run server-setup:typecheck   # type-check the package
pnpm nx run server-setup:test        # run the Vitest suite

On this page