Skip to content

Services

Services are dependencies your application owns, such as a database client, a clock, or a repository, that Routa constructs and passes to handlers as ctx.services. Application services are built once per application instance. A route file or a single method can add request services, built once for each request it handles. Handlers depend on interfaces you declare, so you can change an implementation without touching a route. Services are optional: plain imports keep working, and a project without services has no ctx.services at all.

src/services.ts
import { defineServices } from "@routa-ts/core";
export interface Clock {
now(): Date;
}
export interface UserStore {
find(id: string): Promise<{ id: string; name: string } | undefined>;
}
export interface AppServices {
clock: Clock;
users: UserStore;
}
export const defineAppServices = defineServices<AppServices>();
src/routa.ts
import { createRouta } from "@routa-ts/core";
import { defineAppServices } from "./services.js";
import { connectUserStore } from "./users.js";
export default createRouta({
services: defineAppServices(async ({ logger, onCleanup }) => {
const clock = { now: () => new Date() };
const users = await connectUserStore(process.env.DATABASE_URL);
onCleanup(() => users.close());
logger.info("services.ready", "Application services are ready.");
return { clock, users };
}),
});
src/routes/users/$userId/route.ts
import { createRoute, createRouteRoot } from "@routa-ts/core";
import { z } from "zod";
export default createRouteRoot("/users/:userId")({
get: createRoute({
input: { params: z.object({ userId: z.string() }) },
responses: {
success: { status: 200, schema: z.object({ id: z.string(), name: z.string() }) },
notFound: { status: 404 },
},
run: async ({ ctx, input, response }) => {
const user = await ctx.services.users.find(input.params.userId);
return user ? response.success(user) : response.notFound();
},
}),
});

defineServices<AppServices>() fixes the service contract and returns a helper. Name the helper once, as defineAppServices above, and pass every factory for that contract through it. TypeScript checks that the factory returns each declared service with a compatible type. The inline form services: defineServices<AppServices>()(factory) is equivalent.

routa check and routa generate read the contract from source. They never import your modules or run the factory. The generated .routa/routes.gen.ts records the service names and a type-only reference to the contract:

.routa/routes.gen.ts
export const routaApplicationServices = ["clock", "users"] as const;
export type RoutaApplicationServices = import("../src/services.js").AppServices;

That reference is what types ctx.services in every handler. Handlers see AppServices, never the factory’s concrete classes, so members the interface does not declare are a type error.

When routa dev or routa start boots, Routa awaits the factory once, before the server listens. The factory receives the configured logger and onCleanup. It gets no request data, and it reads configuration through ordinary closures and imports. Routa then checks that the returned object has exactly the declared names. A missing or extra name fails startup. Routa does not check the services’ methods at runtime.

ctx.services is frozen and cannot be reassigned, so no handler or middleware can replace a service. The services themselves are not frozen, and their own state stays mutable.

One factory may build several services that depend on each other. Wire them through local variables, and every handler receives the same instances:

src/routa.ts
import { createRouta } from "@routa-ts/core";
import { defineAppServices } from "./services.js";
import { MemoryUserStore } from "./users.js";
export default createRouta({
services: defineAppServices(() => {
const clock = { now: () => new Date() };
return { clock, users: new MemoryUserStore(clock) };
}),
});

Routes depend on the contract, so you can swap an implementation in the factory alone. This factory replaces MemoryUserStore with a SQL-backed store. The route file above does not change, and handlers cannot call members SqlUserStore adds beyond UserStore, because ctx.services is typed by the contract:

src/routa.ts
import { createRouta } from "@routa-ts/core";
import { defineAppServices } from "./services.js";
import { createPool, SqlUserStore } from "./resources.js";
export default createRouta({
services: defineAppServices(async ({ onCleanup }) => {
const pool = await createPool(process.env.DATABASE_URL);
onCleanup(() => pool.end());
return { clock: { now: () => new Date() }, users: new SqlUserStore(pool) };
}),
});

TypeScript checks the new implementation against UserStore when the factory compiles. At runtime Routa checks only the service names.

A route file can declare services on its route root, and a method on its createRoute. Use the same defineServices helper. Routa runs these factories once for each request the scope handles, so they can hold per-request state or build on what middleware resolved.

src/orders/services.ts
import { defineServices } from "@routa-ts/core";
export interface OrderBook {
list(): Promise<Array<{ id: string; total: number }>>;
place(total: number): Promise<{ id: string; total: number }>;
}
export interface Receipts {
send(orderId: string): void;
}
/** Services every request to the orders route file receives. */
export interface OrdersServices {
orders: OrderBook;
}
/** Services only POST /orders receives. */
export interface CheckoutServices {
receipts: Receipts;
}
export const defineOrdersServices = defineServices<OrdersServices>();
export const defineCheckoutServices = defineServices<CheckoutServices>();
src/routes/orders/route.ts
import { createRoute, createRouteRoot } from "@routa-ts/core";
import { z } from "zod";
import { openOrderBook } from "../../orders/book.js";
import { createReceiptOutbox } from "../../orders/receipts.js";
import { defineCheckoutServices, defineOrdersServices } from "../../orders/services.js";
const Order = z.object({ id: z.string(), total: z.number() });
export default createRouteRoot("/orders")({
services: defineOrdersServices(({ ctx }) => ({
orders: openOrderBook(ctx.services.clock),
})),
get: createRoute({
responses: { success: { status: 200, schema: z.array(Order) } },
run: async ({ ctx, response }) => response.success(await ctx.services.orders.list()),
}),
post: createRoute({
services: defineCheckoutServices(({ ctx, onCleanup }) => {
const receipts = createReceiptOutbox(ctx.logger);
onCleanup(() => receipts.flush());
return { receipts };
}),
input: { body: z.object({ total: z.number() }) },
responses: { created: { status: 201, schema: Order } },
run: async ({ ctx, input, response }) => {
const order = await ctx.services.orders.place(input.body.total);
ctx.services.receipts.send(order.id);
return response.created(order);
},
}),
});

The example uses the AppServices contract above.

A request factory receives { ctx, onCleanup }. ctx holds the context the middleware before it provided, the services of earlier scopes, and the request logger. It holds no request input, so read input through middleware. For one request, Routa runs:

  1. Filesystem middleware, which sees application services.
  2. The route file’s factory.
  3. The route file’s middleware, which sees application and route-file services.
  4. The method’s factory, for the matched method only.
  5. The method’s middleware, and then the handler, which see every scope.

Each step’s types follow that order. A route-file factory cannot read its own services or the context its file’s middleware provides, and GET /orders never sees receipts. Each stage keeps its own ctx.services: a filesystem middleware that reads ctx.services after await next() still sees only application services. Each mapping is frozen, and concurrent requests get their own instances.

Service names must be unique across the scopes one request combines: the application, the route file, and the matched method. routa check reports ROUTA_SERVICES_DUPLICATE for a collision, and route registration rejects one that skipped the check. Unrelated route files and methods may reuse a name with a different interface.

Every .ts file under src/routes other than middleware.ts, schemas.ts, and *.test.ts is a route, so declare request contracts in the route file itself, exported, or in a module outside src/routes. routa generate adds the contracts to the route’s routaRoutes entry, types the handler’s ctx.services per method, and writes RoutaFactoryCtxByPath, the context each request factory receives:

.routa/routes.gen.ts
export type RoutaFactoryCtxByPath = {
"/orders": {
routeFile: {
"auth": { readonly "userId": string };
readonly "services": Readonly<RoutaApplicationServices>;
};
post: {
"auth": { readonly "userId": string };
readonly "services": Readonly<RoutaApplicationServices & import("../src/orders/services.js").OrdersServices>;
};
};
};

Middleware that needs a service declares a requirement interface, the services it reads and the members it calls. Pass the interface to createMiddleware<Requirements>(), name the helper it returns, and list the same names in requiresServices:

src/middleware/rate-limit.ts
import { createMiddleware } from "@routa-ts/core";
export interface RateLimitRequirements {
limiter: { take(key: string): Promise<boolean> };
}
const defineRateLimitMiddleware = createMiddleware<RateLimitRequirements>();
export const withRateLimit = defineRateLimitMiddleware({
requiresServices: ["limiter"],
rejects: { tooManyRequests: { status: 429 } },
run: async ({ ctx, next }) => {
if (!(await ctx.services.limiter.take("anonymous"))) {
return { type: "tooManyRequests" };
}
return next();
},
});

The helper infers requires, provides, rejects, and input the way createMiddleware does. TypeScript rejects a requiresServices list that leaves out a name or adds one the interface does not declare. The callback’s ctx.services is RateLimitRequirements and nothing else, so the middleware cannot reach a service it did not declare, even when its placement provides one. The inline createMiddleware<RateLimitRequirements>()({ ... }) is equivalent. Middleware without service requirements keeps the direct createMiddleware({ ... }) form, which has no typed ctx.services and rejects requiresServices.

A requirement interface follows the contract rules: exported, with required, plainly named members. It names what one middleware needs, so the same name may have a different type in a requirement and in an unrelated scope.

routa check checks the middleware at every placement against the services that exist before it runs:

Middleware Sees
Filesystem middleware.ts Application services
A route root’s middleware Application and route-file services
A createRoute’s middleware Application, route-file, and method services

A placement is valid when each required service exists there and its type is assignable to the requirement. Extra members on the implementation are fine. This application service satisfies RateLimitRequirements, so withRateLimit can run as filesystem middleware:

src/services.ts
import { defineServices } from "@routa-ts/core";
export interface AppServices {
limiter: { take(key: string): Promise<boolean>; close(): void };
}
export const defineAppServices = defineServices<AppServices>();
src/routes/middleware.ts
export { withRateLimit } from "../middleware/rate-limit.js";

A required name that no earlier scope declares fails the check, including a name that a later factory of the same request builds. Declaring limiter in the /orders route file’s services instead of the application’s reports:

ROUTA_SERVICES_UNAVAILABLE: src/routes/middleware.ts: Filesystem middleware withRateLimit requires service "limiter", which /orders does not provide before it runs. The route file's services declare it, but their factory runs after this middleware.
Suggestion: Filesystem middleware sees only application services. Declare "limiter" in the application services, or move the middleware into a route file or method that declares it.

A service with the right name and an incompatible type fails the TypeScript step of routa check. routa generate writes one check per placement into .routa/routes.gen.ts, and TypeScript reports the line of the placement that fails. With limiter: { take(key: string): boolean } in AppServices:

.routa/routes.gen.ts(111,68): error TS2344: Type 'Readonly<AppServices>' does not satisfy the constraint 'RateLimitRequirements'.
The types of 'limiter.take(...)' are incompatible between these types.
Type 'boolean' is not assignable to type 'Promise<boolean>'.
.routa/routes.gen.ts
export type RoutaServiceRequirementChecks = [
RoutaServicesSatisfy<"withRateLimit in src/routes/middleware.ts", Readonly<RoutaApplicationServices>, import("../src/middleware/rate-limit.js").RateLimitRequirements>,
];

Each placement gets its own check, so a middleware placed in two route files can pass in one and fail in the other.

At runtime, Routa checks that every name in requiresServices is on the middleware’s ctx.services immediately before it runs. A missing name, which only a project that bypassed routa check can reach, stops the request before the callback with the standard 500 problem. The client gets no details. The http.error log names the middleware, the service, the route, and the method:

Middleware withRateLimit on GET /orders requires service "limiter", but ctx.services does not provide it where the middleware runs. Declare "limiter" in a services scope that runs before the middleware.

Routa checks names at runtime, not the members of the services.

A service contract is an exported interface, or an exported type alias of an object type, whose members are all required and plainly named. Interfaces that share its name in one module merge into one contract, as TypeScript merges them. It may live in any project module, and every binding between services: and defineServices may be a local const or a relative import, including re-exports. Route files declare request services on the route root object or on an inline createRoute. Routa reports a declaration it cannot follow instead of guessing:

Problem Diagnostic
services is not built through a defineServices helper ROUTA_SERVICES_UNRESOLVED
The contract is inline, missing, or not exported ROUTA_SERVICES_CONTRACT_UNRESOLVED
An optional or computed member, an index signature, or an extends ROUTA_SERVICES_CONTRACT_UNSUPPORTED
Scopes that run in one request declare the same name ROUTA_SERVICES_DUPLICATE
Middleware requires a service its placement does not provide ROUTA_SERVICES_UNAVAILABLE

Requirement interfaces passed to createMiddleware<Requirements>() follow the same rules and report the same contract diagnostics.

TypeScript rejects optional services and index signatures in defineServices<...>() too. Declare services in the createRouta object itself, or in a const object literal, declared locally or imported, that you pass to createRouta or spread into it. When a spread, computed key, or config argument Routa cannot read may hide them, routa check warns with ROUTA_SERVICES_SPREAD_UNRESOLVED. The warning does not stop startup. Startup fails only when the hidden services have no generated metadata. When a visible services member comes before the spread, a hidden factory can replace it. Routa still checks that the hidden factory returns exactly the names the visible contract declares, and fails startup if they differ, but nothing checks the hidden factory against that contract’s types. Declare services after any spread.

Register a cleanup callback with onCleanup right after the factory acquires a resource. Routa awaits the callbacks one at a time, in reverse registration order, and attempts every callback even when an earlier one fails.

src/routa.ts
import { createRouta } from "@routa-ts/core";
import { defineAppServices } from "./services.js";
import { connectCache, createPool, SqlUserStore } from "./resources.js";
export default createRouta({
services: defineAppServices(async ({ onCleanup }) => {
const pool = await createPool(process.env.DATABASE_URL);
onCleanup(() => pool.end());
const cache = await connectCache(process.env.CACHE_URL);
onCleanup(() => cache.quit());
return { clock: { now: () => new Date() }, users: new SqlUserStore(pool, cache) };
}),
});

On disposal Routa quits the cache, then ends the pool. If connectCache throws, Routa ends the pool, then fails startup with the connectCache error. It does not retry the factory or substitute a service. A helper that acquires several resources and then throws releases its own partial work, because only callbacks registered before the failure run.

Register each callback as soon as its resource exists. A callback registered at the end of the factory never runs when an earlier step throws, so the resources acquired before that step leak.

You can also register one callback for several resources. Routa treats it as a single callback, so its internal order and its try/finally are yours:

src/routa.ts
import { createRouta } from "@routa-ts/core";
import { defineAppServices } from "./services.js";
import { connectCache, createPool, SqlUserStore } from "./resources.js";
export default createRouta({
services: defineAppServices(async ({ onCleanup }) => {
const pool = await createPool(process.env.DATABASE_URL);
const cache = await connectCache(process.env.CACHE_URL).catch(async (error: unknown) => {
// Keep the connection error primary even when ending the pool fails too.
await pool.end().catch((cleanupError: unknown) => console.error(cleanupError));
throw error;
});
onCleanup(async () => {
try {
await cache.quit();
} finally {
await pool.end();
}
});
return { clock: { now: () => new Date() }, users: new SqlUserStore(pool, cache) };
}),
});

The two styles fail differently:

Style When connectCache throws When cache.quit() throws
One callback per resource Routa ends the pool Routa still ends the pool and reports the quit failure
One combined callback Your catch must end the pool Your finally ends the pool; Routa reports the quit failure

Without the finally, a failed quit() skips pool.end(), because Routa attempts each callback but not each line inside one.

Cleanup runs once per application instance:

  • When the factory or the name check fails, Routa runs the registered callbacks and rethrows the original error.
  • When the server fails to listen, for example because the port is taken, Routa logs api.start_failed, releases the services, and exits with code 1.
  • When a listen option is invalid, for example a port out of range, Routa releases the services and fails startup with the listener’s error.
  • createApplication(...).dispose() waits for accepted requests to settle, then runs the callbacks. It sets no deadline and cancels nothing, so a request or callback that never settles keeps it pending.

A cleanup failure never replaces a startup error. Routa logs it as services.cleanup_failed. dispose() rejects with an AggregateError of the failures after every callback has been attempted.

Request factories register cleanup the same way. Routa releases a request’s services once, after the response is ready:

  1. The handler or a middleware reject selects the outcome, and Routa validates and serializes the response.
  2. The middleware chain unwinds.
  3. Routa releases the method’s services, then the route file’s, each in reverse registration order.
  4. Routa returns the prepared response.

A request cleanup failure is logged as services.cleanup_failed and never changes the response. Application services stay available throughout, and dispose() waits for active requests to finish their cleanup before releasing application services.

When a request factory throws or returns the wrong names, Routa skips every later factory, middleware, and the handler, and responds with the standard 500 problem, whatever the factory threw. A ZodError from a factory is an internal failure, not a validation error. The error is logged as http.error and never reaches the client. A middleware reject also skips later factories. Either way, Routa releases the scopes the request started, including the callbacks a failed factory registered, after the chain unwinds and in the same order. It does not retry a factory or substitute a service.

The generated .routa/testing.gen.ts exports createTestApp, which builds an in-memory instance of your project with replacement factories. Each replacement takes the place of one scope’s whole factory before construction and returns that scope’s complete contract:

src/orders.test.ts
import { createTestApp } from "../.routa/testing.gen.js";
import { testAppServices, testCheckoutServices } from "./testing/fakes.js";
const app = await createTestApp({
services: testAppServices,
routes: { "/orders": { methods: { post: { services: testCheckoutServices } } } },
});

The original factory of a replaced scope never runs, and each factory that does run owns its cleanup. Omitted scopes keep their factories and receive the replacements through ctx, so dependent services stay wired. Annotate a factory declared on its own, in a test file or in application code, with the generated ServicesFactory<"application">, ServicesFactory<"/orders">, or ServicesFactory<"POST /orders"> type, so you do not repeat its contract or context. Testing walks through fakes, cleanup, and disposal.

Routa reserves ctx.services in every project, including projects without services. Middleware cannot provide a services key or pass one to next():

  • TypeScript rejects provides: { services: ... }, a named provides binding with that key, and a next() payload that names it.
  • routa check reports ROUTA_CONTEXT_RESERVED.
  • At runtime, registration rejects a services provides schema that a cast hid from TypeScript, and a request fails with 500 when createContext, next(), or a direct write claims ctx.services.

To read provides through named bindings, routa check follows a const object literal that provides names. It reports ROUTA_MIDDLEWARE_PROVIDES_UNRESOLVED for any provides it cannot read, such as a call or a spread, instead of treating it as empty.

If an existing middleware provides services, rename the key and update the handlers that read it:

src/middleware/billing.ts
import { createMiddleware } from "@routa-ts/core";
import { z } from "zod";
export const withBilling = createMiddleware({
provides: {
billing: z.object({ plan: z.string() }),
},
run: ({ next }) => next({ billing: { plan: "team" } }),
});

When the value is an application dependency rather than per-request data, declare it as an application service instead.

Routa owns the wiring, the construction timing, the name checks, and the cleanup order. Your application owns the services, their configuration, the resources they acquire, how those resources are released, and every business decision the services make. Service contracts never appear in OpenAPI, and adopting services does not change any HTTP response.