@jakobm/route-forge
v0.3.1
Published
Typed Express routes with shared HTML and JSON handlers, authentication and OpenAPI
Readme
route-forge
A TypeScript library for Express 4 and Zod 3. A route can share typed
input validation, resource loading and response validation between JSON and HTML,
and contribute its JSON contract to an instance-specific OpenAPI document.
Published as @jakobm/route-forge, with an ESM entrypoint and TypeScript declarations. Requires Node.js 20 or later.
Explicit registration
Install with npm install @jakobm/route-forge express@4 zod@3.
Consumers import from @jakobm/route-forge; internal module paths are not exported.
import express from "express";
import { createRouteForge } from "@jakobm/route-forge";
import { z } from "zod";
const app = express();
app.use(express.json());
const routes = createRouteForge({ app });
routes.registerRoute({
method: "get",
path: "/greeting/:name",
authRequired: false,
schemas: {
params: z.object({ name: z.string().min(1) }),
response: z.object({ greeting: z.string() })
},
handler: ({ params }) => ({ greeting: `Hello ${params.name}` })
});
routes.initialize().then(() => app.listen(3000));Each factory owns its registration queue, renderer and OpenAPI registry. Register
routes before initialize() to apply registrationPriority (highest first).
Initialization is idempotent. Registration after initialization mounts immediately.
Route modules can be reused across independent Express apps.
Standalone route definitions
Use defineRoute to build a definition separately from registration. The helper
infers handler inputs and results from the Zod schemas and returns the same object.
It does not register routes, execute callbacks or require an Express app.
defineRoute(config) uses the default identity type (never); for an app with
authentication, bind its identity once with defineRoute<AppAuth>():
// app-route.ts
import { defineRoute } from "@jakobm/route-forge";
export type AppAuth = { userId: number };
export const defineAppRoute = defineRoute<AppAuth>();Each route module can then return a definition from a dependency-injected factory:
// create-job.ts
import { z } from "zod";
import { defineAppRoute } from "./app-route.js";
export default function createJobRoute({ jobs }: {
jobs: { create(title: string, owner: number): Promise<{ id: number }> };
}) {
return defineAppRoute({
method: "post",
path: "/jobs",
authRequired: true,
schemas: {
body: z.object({ title: z.string().min(1) }),
response: z.object({ id: z.number() })
},
handler: ({ body, auth }) => jobs.create(body.title, auth.userId)
});
}Discovery and dependency injection belong to the consumer. Once all factories have returned, collect and register their definitions centrally before initializing:
import type { RouteDefinition, RouteForge } from "@jakobm/route-forge";
import type { AppAuth } from "./app-route.js";
export async function mountRoutes(
routes: RouteForge<AppAuth>,
definitions: readonly RouteDefinition<AppAuth>[]
) {
for (const definition of definitions) routes.registerRoute(definition);
await routes.initialize();
}RouteDefinition<AppAuth> lets a list contain definitions with different schemas
while preserving the app's identity requirement. Schema-specific callback types
are hidden in this collection type; individual helper results retain them.
The helper checks types at definition time, so construct each complete definition
through it instead of changing its schemas or callbacks afterward. Bind the same
app identity for both public and protected definitions; authRequired determines
whether callbacks receive AppAuth | null or AppAuth.
Definitions can be reused across factories. With external discovery, omit
routesDir; Route-forge's directory loader expects registration functions.
Factory options
Only app is required. The consumer installs Express body parsing and, when using
cookie authentication, cookie parsing before initializing the routes.
| Option | Behavior |
| --- | --- |
| htmlRenderer | Synchronous (input) => ({ html, status }) renderer for pages and errors. Required when registering an HTML handler. |
| auth | Request-specific authenticate(req) resolver returning an application-defined identity or null, synchronously or asynchronously. May provide onAccessDenied to customize access-denial responses. |
| backgroundJobs | Enables in-process jobs with required onError(error), optional run(job) executor and awaitCompletion. |
| routesDir | Opts into recursively loading modules that default-export a registration function. |
| openApi | Document metadata with independently optional jsonPath and uiPath endpoints; may also supply servers, securitySchemes and security. |
html receives the validated handler result as data when both are
present. Express content negotiation chooses HTML or JSON using media ranges and
quality weights. Equally preferred explicit ranges follow header order; an empty
or wildcard Accept header selects HTML.
A shared route returns 406 when neither representation is acceptable. JSON-only
routes always return JSON. Without a response schema the JSON handler must return
undefined; otherwise its result must pass the response schema. The default JSON
status is 204 without a schema and 200 with one; responseStatus overrides it.
Use HttpError(status, message) for an expected HTTP failure.
Typed authentication and authorization
The app defines the identity and resolves credentials. Route-forge passes that
identity to handler, html, raw handlers and route-local authorize:
import { createRouteForge, type RouteForge } from "@jakobm/route-forge";
import { z } from "zod";
import { authenticateSession } from "./sessions.js"; // App-owned credential validation.
type UserAuth = { userId: number; email: string };
export type AppRoutes = RouteForge<UserAuth>;
const routes = createRouteForge<UserAuth>({
app,
auth: {
authenticate: (req) => authenticateSession(req) // UserAuth | null, or a promise.
}
});
routes.registerRoute({
method: "get",
path: "/users/:id",
authRequired: true,
schemas: {
params: z.object({ id: z.number() }),
response: z.object({ email: z.string() })
},
authorize: ({ auth, req }) => auth.userId === Number(req.params.id),
handler: ({ auth }) => ({ email: auth.email }) // auth is UserAuth.
});The generic can also be inferred from the resolver's return type. Separate route
modules should accept AppRoutes (or RouteForge<UserAuth>) to retain it.
Every typed and raw route must specify authRequired. With true, handler and
policy auth types are non-nullable UserAuth, and anonymous callers are denied.
With false, anonymous callers are allowed and the type is UserAuth | null;
the resolver still supplies an identity when available. Without an auth resolver,
public routes receive null and protected routes deny access. Omitting the flag
is a type error.
The resolver runs once per request per factory, before route validation and
multipart parsing. Its result, including null, is reused across handlers and
route fallthrough. Rejected resolutions go to Express error handling without
running the route. Use null for anonymous callers. The package imposes no user,
role, token or session structure.
An optional authorize({ auth, req }) policy returns a boolean or promise; it
runs after authentication and before route validation. A required route's policy
runs only for authenticated callers. Policies use the raw Express request, so
validate any input they use; resource ownership checks can also live in handlers
where parsed inputs and loaded resources are available.
Denials return 401 for anonymous callers and 403 for authenticated callers.
Without a callback, HTML denials use the configured error renderer; JSON denials
use { error: "unauthorized" } or { error: "forbidden" }. JSON-only routes
always select JSON, even for requests accepting HTML.
Override denial handling with
auth.onAccessDenied({ req, res, auth, status, format }); this callback owns the
entire response and may be async. For example, an app can redirect HTML 401
responses to its login page, render a custom HTML 403, and send its own JSON
errors. There is no loginPath option: redirects belong in this callback. It
handles only access denials (401/403), not validation errors or server errors.
OpenAPI and Swagger UI
Route-forge owns Zod/OpenAPI integration, document generation and optional document and Swagger UI serving. Its Swagger dependencies stay inside the package. Configure the factory to expose either endpoint or both:
const routes = createRouteForge({
app,
openApi: {
title: "My API",
version: "1.0.0",
description: "My application API",
jsonPath: "/openapi.json",
uiPath: "/openapi",
securitySchemes: {
ApiKeyHeaderAuth: { type: "apiKey", in: "header", name: "x-api-key" }
},
security: [{ ApiKeyHeaderAuth: [] }]
}
});title and version are required metadata directly under openApi; optional
description, contact, license and other OpenAPI info fields also go there.
Route-forge places these fields under info in the generated OpenAPI document.
Optional servers supplies server URLs. The
served document uses OpenAPI 3.0.0. Each path opts into that endpoint independently:
JSON-only serving needs no uiPath, and UI-only serving embeds the document without
requiring a JSON endpoint. With no paths, including when openApi is omitted,
neither endpoint is exposed. Paths are registered when the factory is created,
before middleware the consumer subsequently installs. Documents and UI initialization
scripts reflect the current instance's routes and schemas, including later
registrations, without sharing documents between instances.
openApi.securitySchemes defines OpenAPI authentication methods;
openApi.security lists the requirements automatically attached to typed routes
with authRequired: true. Public routes omit them, and the document has no global
security requirement. An array of separate objects means alternatives (OR), while
multiple methods in one object mean all are required (AND). Scopes apply to OAuth
schemes. These fields describe the API and configure Swagger clients; enforcement
still comes from auth.authenticate, authRequired and optional authorize.
Neither field is inferred from the other or from the resolver. Security metadata
also works for programmatic generation when no documentation endpoints are enabled.
Programmatic generation remains available regardless of endpoint configuration:
routes.generateOpenApiDocument({ openapi: "3.0.0", info: ... }). Multipart fields
and files are included, and multipartFileFieldSchema describes a binary file.
Import z directly from the zod peer dependency. Ordinary Zod schemas need no
special initialization. Importing route-forge extends the shared Zod prototype
with .openapi() for optional metadata. A module that calls .openapi() while
defining schemas must import route-forge at runtime before those calls; a
type-only import does not initialize the extension:
import "@jakobm/route-forge";
import { z } from "zod";
export const Greeting = z.object({ greeting: z.string() }).openapi("Greeting");The package initializes this extension internally for its own schemas as well.
Middleware composition
Install consumer middleware explicitly with app.use(...) before initializing
routes. Credential policies, form method overrides and JSON suffix rewriting
belong to the consumer. Route-forge selects HTML or JSON from the Accept header;
it does not rewrite URLs.
Create the factory before any middleware that rewrites documentation URLs so the configured OpenAPI endpoints take precedence. Initialize routes after installing application middleware. Route-forge retains authorization, per-route validation, representation negotiation and upload lifetime management.
Directory loading
Explicit registration needs no filesystem conventions. To opt into loading, set
routesDir and export this entrypoint from each route module:
import type { RouteForge } from "@jakobm/route-forge";
export default function registerRoutes(routes: RouteForge): void {
routes.registerExpressRoute({
method: "get",
path: "/example",
authRequired: false,
handler: ({ res }) => { res.send("Example"); }
});
}The loader supports .js, .cjs and .mjs. Source .ts modules require a runtime
loader such as tsx; declaration files are ignored. Files are loaded in sorted
order, and their entrypoints are invoked for each factory even when the module
itself is cached. registerExpressRoute passes { req, res, next, auth } to its
handler and supports the same typed identity, required authRequired flag,
authorize policy and registration priority as typed routes. Thrown/rejected errors go to Express error handling;
the consumer owns raw responses and OpenAPI documentation.
Uploads and background jobs
A route's multipart configuration enables Formidable parsing for its exact path
and HTTP method. Parsed fields/files are validated against its schemas. Temporary
uploads are deleted when the response finishes or closes. Starting a background
job retains uploads until the job settles unless retainMultipartFiles: false is
passed to runBackgroundJob.
runBackgroundJob can be called once per request and requires the factory's
backgroundJobs configuration. Jobs start in the current process; route-forge
provides no durable queue, retries or restart recovery. onError reports failed
jobs. The optional executor can wrap execution in application-specific tracing.
awaitCompletion: true waits in both JSON and HTML flows, which is useful for
controlled callers. The default allows the HTTP response to finish first.
Development
Use the Node.js and npm versions pinned in package.json via Volta. Run npm ci
to install dependencies and build the package, then npm test for the canonical
checks: library and test typechecking, compilation, HTTP behavior tests and an
isolated consumer test of the packed npm artifact. For focused changes, run
npm run build followed by npm run test:unit -- test/<file>.test.ts.
Tests use temporary files and in-memory Express apps; no database, personal
configuration or external service is needed.
PR checks and npm publishing call Peacekeeper's central workflows at approved
commit SHAs. Local workflow files only declare triggers, caller permissions and
the explicit RELEASE_POLICY_TOKEN mapping. test:package remains in tests.all,
so it runs through the shared PR job. Require test / test in GitHub's branch
protection to match peacekeeper.config.yaml; npm trusted publishing keeps the
local publish.yml entrypoint. The shared PR job can install optional prerequisites
from tests.aptPackages and tests.playwrightBrowsers; both lists are empty for
Route-forge. Other workflow behavior belongs in repository-defined workflows.
The Peacekeeper development dependency is pinned to npm version 0.29.0.
Workflow pins must match the approved revisions bundled with that version.
Repository-local Codex configuration is no longer used; configure setup and hooks
outside the repo.
The implementation and authentication/OpenAPI tests were extracted from
absolute-strava-sync, commit 480ba14
on codex/route-forge-factory.
dist/ is generated and is not committed. Each build removes old output before
compiling src/ into JavaScript (.js) and TypeScript declarations (.d.ts).
TypeScript source stays in src/. The existing prepare hook builds the package
on npm ci, npm pack and npm publish, so the npm artifact contains ready-to-use
JavaScript and declarations. Consumers do not need to build it. The isolated
package test lives in test/package.cjs and runs via npm run test:package.
