npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ltv/cwb

v0.2.1

Published

Cloudflare Workers Bootstrap with hono

Readme

@ltv/cwb — Cloudflare Workers Bootstrap

Batteries-included foundation for building OpenAPI-documented REST APIs on Cloudflare Workers with Hono and chanfana.

You bring route classes and data; @ltv/cwb provides app wiring, versioned modules, a standard response envelope, OpenAPI response schemas, typed errors, structured logging, typed env access, KV caching, and optional Drizzle ORM + D1 datasources with multi-tenant query scoping.

Runtime: Cloudflare Workers only. The package reads config from cloudflare:workers at import time. To import it in plain Node/Bun (e.g. tests), mock that module — see Testing.

TypeScript: the library is built with TypeScript 7.0.2. Its published types have been checked with TypeScript 7.0.2, 6.0.3 and 5.9.3 consumers, so there is no typescript peer dependency. See Consumer TypeScript setup.

Upgrading from 0.1.x? Read the migration guide. Versioning, supported runtimes and deprecations: support policy.

Table of Contents

Installation

bun add @ltv/cwb hono chanfana zod   # peers: hono ^4.13, chanfana ^3.4, zod ^4.4.3
# optional, for datasources (@ltv/cwb/datasources)
bun add drizzle-orm

Consumer TypeScript setup

  • Workers types. Published types reference Workers globals (D1Database, KVNamespace, ExecutionContext). Generate them with wrangler types (recommended) or install @cloudflare/workers-types, and use lib: ["es2024"].
  • Node types from pino. pino's type definitions import Node modules (events, worker_threads). Either set "skipLibCheck": true or install @types/node; otherwise tsc reports errors inside pino.d.ts.
// tsconfig.json of your Worker
{
  "compilerOptions": {
    "lib": ["es2024"],
    "types": ["./worker-configuration.d.ts"], // from `wrangler types`
    "skipLibCheck": true                      // or add @types/node
  }
}

Quick Start

// src/modules/users/user-get.route.ts
import {OpenAPIRoute} from 'chanfana';
import type {Context} from 'hono';
import {z} from 'zod';
import {ApiError, jsonCrudResponses} from '@ltv/cwb';

const User = z.object({id: z.string(), name: z.string()});

export class UserGet extends OpenAPIRoute {
  schema = {
    tags: ['Users'],
    request: {params: z.object({id: z.string()})},
    responses: jsonCrudResponses('User', User),
  };

  async handle(c: Context) {
    const {params} = await this.getValidatedData<typeof this.schema>();
    if (params.id !== '1') throw ApiError.notFound('User');
    return c.respond({id: params.id, name: 'Jane'});
  }
}
// src/index.ts
import {fromHono} from 'chanfana';
import {createApp, defineModule} from '@ltv/cwb';
import {UserGet} from './modules/users/user-get.route';

const users = defineModule({
  version: 1,
  routes: {
    'GET /users/:id': UserGet,
  },
});

const app = createApp({
  path: '/api',
  cors: true,
  healthCheck: true,
  modules: [users],
  openApi: (app) => fromHono(app, {docs_url: '/docs'}),
});

export default app; // GET /api/v1/users/:id, GET /health, GET /docs

Features

1. App Builder — createApp

createApp(config) returns a configured Hono app. Route keys are validated first, then middleware is applied in this order:

| # | Feature | Config | Default | Behavior | |---|---|---|---|---| | 1 | Global error handler | errors | production-safe defaults | createErrorHandler(config.errors): converts any thrown error into the standard error envelope (§5) | | 2 | Non-Error throws | — | always on | throw 'x' / throw {} is rethrown as an Error (original value as cause), so it gets the envelope instead of escaping app.fetch | | 3 | Response helpers | — | always on | Adds c.respond* methods (§3) | | 4 | Request ID | requestId | true | Sets c.var.requestId and X-Request-Id: a valid incoming X-Request-Id, else a well-formed cf-ray, else a generated cuid2 (details) | | 5 | Server timing | timing | isDev | Hono timing() — Server-Timing headers. Off in production unless timing: true, because it exposes handler durations | | 6 | CORS | cors | off | true = allow all origins (origin: '*'); object = Hono CORS options | | 7 | Request logging | logger, requestLogging | root logger, info | Sets the request-scoped logger (getRequestLogger(c)), then logs one line per request: method, path, status, duration, cfRay, cfColo (plus the requestId binding) | | 8 | Datasource registry | datasources | always on (empty) | Sets c.var.ds: each datasource is created on first access and reused for the rest of the request (§11) | | 9 | Health check | healthCheck | off | GET /health → {status: 'healthy', timestamp} | | 10 | App middleware | middleware | [] | Your middleware (auth, tenant resolution, rate limiting…), run before every module route and the docs routes, but after /health | | 11 | Not found | — | always on | Unknown routes return the JSON NOT_FOUND envelope | | 12 | Module routes | modules, path | path: '/' | Registers every module route under path; each app gets its own registry | | 13 | OpenAPI | openApi | required | Receives the Hono app and returns the chanfana router (e.g. fromHono(app)) |

interface AppConfig<E extends Env = Env> {
  cors?: boolean | CorsOptions;
  requestId?: boolean | {trustIncomingHeader?: boolean}; // RequestIdConfig
  timing?: boolean; // default: isDev
  healthCheck?: boolean;
  errors?: ErrorHandlerConfig; // see §5
  logger?: Logger; // base for request loggers and request log lines (default: root logger)
  requestLogging?: boolean | {level?: 'trace' | 'debug' | 'info' | 'warn'; skip?: (c: Context) => boolean};
  datasources?: DatasourceFactories; // c.var.ds.<name>, see §11
  middleware?: MiddlewareHandler[]; // before module routes
  path?: string;
  modules?: ApiModule[]; // default []
  openApi: (app: Hono<E>) => OpenAPIRouter; // e.g. (app) => fromHono(app)
}

Request ID.

  • An incoming X-Request-Id is reused when Hono's request-id middleware accepts it (at most 255 characters of [A-Za-z0-9_=-]).
  • Otherwise cf-ray is used if it matches ^[A-Za-z0-9-]{1,64}$, and otherwise a new cuid2 is generated. The deprecated, client-spoofable cf-request-id header is never used.
  • requestId: {trustIncomingHeader: false} ignores both headers and always generates a fresh id. Use it when untrusted callers must not choose their own ids. requestId: false disables the middleware.

Request logging. requestLogging: false removes the per-request line (the request-scoped logger is still set). {level, skip} changes the level or skips lines; skip(c) runs after the response, so c.res.status is available:

createApp({
  requestLogging: {level: 'debug', skip: (c) => c.req.path === '/health'},
  // ...
});

2. API Modules & Versioning

  • defineModule({version, routes}) groups chanfana routes.
  • Route keys use the format "METHOD /path". Each value is an OpenAPIRoute class.
  • version defaults to 'v1'. A number is prefixed with v (2 becomes v2), and a string is used as-is.
  • The final route path is {path}/{version}{route}, normalized: duplicate or trailing slashes are removed, so path: '/' gives /v1/users and path: '/api/' gives /api/v1/users. A plain ApiModule object without a version is mounted at {path}{route}.
  • createApp throws before registering anything when:
    • a route key is malformed (missing method, or a path not starting with /);
    • the method is not GET, POST, PUT, PATCH or DELETE (the method is case-insensitive);
    • two routes, in any modules, resolve to the same method and final path.
  • middleware on a module is registered together with each of that module's route handlers. It runs only when Hono dispatches the request to one of that module's routes. Hono picks the first matching route in registration order, so with overlapping patterns (/items/:id in module A before /items/public in module B) module A's route, and its middleware, handles /items/public. List the module with the more specific paths first.
  • The first matching route wins, in module and route order, as in Hono. If module A has GET /items/:id and module B has GET /items/public, list B first, or /v1/items/public is handled by A (and A's middleware).

Auth must go through middleware. createApp registers module routes before returning the app. Middleware added afterwards with app.use() runs after the routes and never guards them. Use createApp({middleware: [...]}) for app-wide middleware, or defineModule({middleware: [...]}) per module.

const requireAuth: MiddlewareHandler = async (c, next) => {
  const token = c.req.header('authorization');
  if (!token) return c.respondUnauthorized();
  c.set('tenantId', await tenantFromToken(token));
  return next();
};

createApp({
  middleware: [requireAuth],                                          // all module routes
  modules: [
    defineModule({routes: {'GET /admin': Admin}, middleware: [requireAdmin]}), // this module only
  ],
  openApi: (app) => fromHono(app),
});
defineModule({
  version: 2,
  routes: {
    'GET /users': UserList,
    'POST /users': UserCreate,
    'PATCH /users/:id': UserUpdate,
    'DELETE /users/:id': UserDelete,
  },
});

Endpoint registry. createApp creates a new EndpointRegistry for every app, so two apps never share routes. You can also use the class directly:

import {EndpointRegistry, buildEndpointPath} from '@ltv/cwb';

const registry = new EndpointRegistry()
  .get('/ping', Ping)
  .post(buildEndpointPath('/api', 'v1', '/items'), ItemCreate);
registry.register('get', '/private', Private, [requireAuth]); // middleware for this route only
registry.getEndpoints(); // copy of [{method, path, handler, middleware?}]
registry.applyTo(fromHono(app));

ENDPOINT_METHODS lists the accepted (lowercase) methods.

3. Response Helpers (c.respond*)

Typed on every Hono Context through module augmentation (ContextResponseHelpers).

The helpers exist at runtime only on apps built with createApp, or on apps that install the middleware themselves: app.use('*', contextHelpers). On a plain new Hono() app, c.respond type-checks but is undefined.

| Helper | Status | Envelope | |---|---|---| | c.respond(data, status?) | 200 | success | | c.respondCreated(data) | 201 | success | | c.respondAccepted(data) | 202 | success | | c.respondNoContent() | 204 | empty body; keeps headers set earlier (X-Request-Id, c.header()) | | c.respondPaginated(data, {page, limit, total}, status?) | 200 | success + meta.pagination | | c.respondError(code, message, status?, details?) | 400 | error | | c.respondBadRequest(message?, details?) | 400 | BAD_REQUEST | | c.respondUnauthorized(message?) | 401 | UNAUTHORIZED | | c.respondForbidden(message?) | 403 | FORBIDDEN | | c.respondNotFound(message?) | 404 | NOT_FOUND | | c.respondConflict(message?) | 409 | CONFLICT | | c.respondValidationError(message?, details?) | 422 | VALIDATION_ERROR | | c.respondInternalError(message?) | 500 | INTERNAL_ERROR |

status parameters are typed as Hono's ContentfulStatusCode, so null-body statuses such as 204 and 304 don't compile (the Workers runtime rejects a body on them). Use respondNoContent() for 204.

Success envelope

{
  "success": true,
  "data": {},
  "meta": {
    "timestamp": 1757829600000,
    "requestId": "8b1f...",
    "traceId": "optional",
    "pagination": {"page": 1, "limit": 10, "total": 42, "totalPages": 5, "hasNext": true, "hasPrev": false}
  }
}

Pagination. respondPaginated uses buildPaginationMeta(page, limit, total), which is also exported:

  • page is 1-based. totalPages is ceil(total / limit) (0 when there are no items), hasNext is page < totalPages and hasPrev is page > 1.
  • It throws a 400 BAD_REQUEST ApiError when page or limit is not a positive integer, or total is not a non-negative integer (NaN, fractions and Infinity included). Validate query params in the route schema (e.g. z.coerce.number().int().min(1)) so it never throws.

Error envelope (identical for c.respondError* and the global error handler)

{
  "success": false,
  "error": {"id": "tz4a98xxat96iws9zmbrgj3a", "code": "NOT_FOUND", "message": "User not found", "details": {}},
  "meta": {"timestamp": 1757829600000, "requestId": "8b1f..."}
}

The ApiResponse<T> type is a union discriminated on success: ApiSuccessResponse<T> | ApiErrorResponse, both with meta?: ApiResponseMeta.

const body = (await res.json()) as ApiResponse<User>;
if (body.success) body.data.name;
else body.error.code;

4. OpenAPI Response Schemas

zod-based chanfana responses builders that document the same envelope as the response helpers. Schema arguments must be zod schemas (TSchema extends z.ZodType).

| Kind | Helpers | |---|---| | Success | jsonSuccess (200), jsonCreated (201), jsonAccepted (202), jsonNoContent (204) | | Paginated | jsonPaginated (200, data: T[], required meta.pagination) | | Errors | jsonBadRequest (400), jsonUnauthorized (401), jsonForbidden (403), jsonNotFound (404), jsonConflict (409), jsonValidationError (422, details: [{field, message, code?}]), jsonInternalError (500) | | CRUD presets | jsonCrudResponses (get), jsonListResponses (list), jsonCreateResponses, jsonUpdateResponses, jsonDeleteResponses | | Custom | jsonCustomResponse(statusCode, description, schema?) (no envelope added) | | Schemas | MetaSchema (timestamp, requestId, traceId, optional pagination), PaginationMetaSchema (page, limit, total, totalPages, hasNext, hasPrev), ErrorSchema (with error.id) |

schema = {
  request: {body: contentJson(UserInput)},
  responses: jsonCreateResponses('User', User), // 201, 400, 401, 422, 409, 500
};

5. Error Handling

ApiError: throw it anywhere. The global errorHandler turns it into the error envelope.

throw new ApiError('Quota exceeded', {
  code: 'QUOTA_EXCEEDED',
  status: 402,
  category: ErrorCategory.BUSINESS_LOGIC,
  severity: ErrorSeverity.MEDIUM,
  details: {limit: 100},
  cause: err,
});
  • Every ApiError has these properties: id (a cuid2), code, status, category, severity, details and cause.
  • toJSON() returns ApiErrorJSON: id, name, code, message, status, category, severity, details. It never includes the stack, so serializing an error into a response or a third-party payload can't leak it.
  • ApiErrors are recognized by a brand (Symbol.for('@ltv/cwb/ApiError')), not only by instanceof. An ApiError created by a second installed copy of the library still keeps its status and message. Use ApiError.isApiError(value) for the same check.

Factory methods

| Status | Factories | |---|---| | 400 | badRequest(message?, details?), businessLogicError(message, code?, details?) | | 401 | unauthorized(message?, details?), invalidCredentials(details?), tokenExpired(details?) | | 403 | forbidden(message?, details?), insufficientPermissions(details?) | | 404 | notFound(resource?, details?) | | 409 | conflict(message?, details?), duplicateEntry(resource?, details?) | | 422 | validationError(message?, details?) | | 429 | rateLimited(message?, details?) | | 500 | internalError(message?, details?, cause?), databaseError(message?, details?, cause?) | | 503 | serviceUnavailable(service?, details?) | | 504 | timeout(operation?, details?) |

Helpers

  • ApiError.fromError(unknown, defaultMessage?, options?) wraps any value:
    • An ApiError (from any library copy) is returned unchanged.
    • A Hono HTTPException keeps its status and gets a matching code (UNAUTHORIZED, PAYLOAD_TOO_LARGE, ...).
    • Any other Error becomes INTERNAL_ERROR (500).
    • Any non-error value becomes UNKNOWN_ERROR (500).
  • ApiError.isApiError(err), ApiError.is(err, code), ApiError.isCategory(err, category) and ApiError.isSeverity(err, severity) are type guards.

Classification

  • ErrorCategory: authentication, authorization, validation, business_logic, external_service, database, rate_limit, system, unknown
  • ErrorSeverity: low, medium, high, critical

Error handler: createErrorHandler(config?)

createApp installs it with config.errors. errorHandler is the same handler with default options, for use with a plain Hono app (app.onError(errorHandler)).

  • Production by default. It is production unless NODE_ENV (from c.env, then the Worker env) is development, dev, test or local, compared case-insensitively. staging, prod, typos or an empty value all count as production (isDevelopmentEnvironment()).
  • What clients see.
    • ApiError and Hono HTTPException 4xx errors return their message and details, because clients need them.
    • Other errors (e.g. raw D1/driver errors) never expose their original message. A transformer can supply a client-safe message; without one, 4xx gets Request failed.
    • 5xx errors return Internal server error with no details in production, unless includeDetails is set.
    • Stack traces go only to logs and reporters, never into responses.
  • What logs and reporters get (ErrorInfo).
    • id, code, message, status, category, severity, timestamp, and details. details are always included (they are masked only in responses), so don't put secrets in them.
    • stack is the stack of the thrown error, i.e. the original throw site, not the handler's wrapper (when includeStackTrace).
    • cause is the serialized cause chain of the thrown error (SerializedError, at most 5 levels; stacks only when includeStackTrace).
    • context: requestId, userId, tenantId, method, path, ip, user agent, redacted headers and redacted query params. context.includeClientInfo: false omits ip and user agent.
  • Logging. Unless customLogger is set, 5xx errors are logged at error (Server error) and 4xx at warn (Client error) through the request-scoped logger, so the lines carry requestId. A log call that fails never breaks the response.
  • Hooks can't break the envelope. A classifier, transformer, customLogger or errorReporter that throws is logged and ignored.
  • Throttling never hides server errors. During error storms, only non-critical 4xx logs and reports are throttled; 5xx and critical errors are always logged and reported (they still count toward the rate). After a throttle window ends, the next error logs a warning: N errors suppressed by error log throttling.
  • chanfana errors use the envelope. This covers request-schema validation, a thrown InputValidationException, and NotFoundException and other ApiExceptions, whether fromHono uses its default mode or passthroughErrors: true. Validation failures become 422 VALIDATION_ERROR with details: [{field: 'body.email', message, code: '7001'}], matching jsonValidationError.
  • Hono HTTPExceptions that carry their own response (e.g. basicAuth with WWW-Authenticate) are returned as-is (other than chanfana errors) after logging.

| Option | Default | Description | |---|---|---| | logErrors | true | Log errors (pino, or customLogger) | | includeStackTrace | true | Add stack traces (thrown error and cause chain) to ErrorInfo (logs and reports only) | | includeDetails | not production | Expose original messages and details to clients, 5xx and untrusted errors included. Affects responses only: ErrorInfo.details is always set and reaches logs and reporters unredacted, so keep secrets out of details | | customLogger(info) | — | Replaces pino logging; may be async | | errorReporter(info) | — | e.g. Sentry; runs in the background via executionCtx.waitUntil; its failures never affect the response | | excludeHeaders | [] | Extra header names to redact. authorization, cookie, x-api-key, Access JWTs and similar are always redacted | | excludeQueryParams | [] | Extra query param names to redact. Always redacted: key, code, sig, auth, authorization, access_key, private_key, pwd, pass, otp, client_assertion, and any name containing token, secret, password, passwd, signature, credential, session, jwt, apikey, api_key, api-key, cookie, hmac, private, cert, saml, assertion, auth_code or authcode (e.g. X-Amz-Signature, page_token, x-shopify-hmac-sha256, x-forwarded-client-cert, SAMLResponse). The fragments apply to header names too. Register app-wide names with addSensitiveQueryParams / addSensitiveHeaders | | context.includeClientInfo | true | false omits ip / userAgent from ErrorInfo.context and also redacts cf-connecting-ip, cf-connecting-ipv6, true-client-ip, x-forwarded-for, x-real-ip and user-agent | | maxMessageLength | 1000 | Truncate messages (adds …) | | classifier(error, c) | — | Override category / severity. Unknown values count as unknown / medium in metrics | | transformer(error, c) | — | Returns ApiErrorOptions & {message?} (status, code, client-safe message, ...) for errors that are not ApiErrors | | rateLimit.maxErrorsPerMinute | 100 | Above this rate, logging and reporting of non-critical 4xx errors are throttled. Responses are never throttled | | rateLimit.throttleDurationSeconds | 60 | How long throttling lasts |

const handler = createErrorHandler({
  errorReporter: (info) => sentry.captureException(info),
  excludeHeaders: ['x-internal-token'],
  context: {includeClientInfo: false},
  transformer: (error) =>
    String(error).includes('UNIQUE constraint failed')
      ? {status: 409, code: 'DUPLICATE', message: 'Resource already exists'}
      : {},
});
app.onError(handler);

handler.getMetrics(); // {total, byCategory, bySeverity, byStatusCode, rate}

Metrics (ErrorMetrics) and throttling are tracked per Worker isolate by ErrorMetricsTracker.

6. Logging

pino in browser mode, tuned for Workers.

import {logger, createLogger, getRequestLogger} from '@ltv/cwb';

logger.info({userId}, 'User signed in');
const log = createLogger({component: 'billing'}); // child logger
getRequestLogger(c).info('inside a request'); // carries requestId
{"time":"2026-09-14T07:21:37.186Z","level":"INFO","env":"production","service":"my-api","runtime":"cloudflare-workers","requestId":"8f1c2a3b4d5e6f70-SJC","method":"GET","path":"/v1/users","status":200,"duration":3,"msg":"GET /v1/users 200 3ms"}
  • Writes JSON lines to console.*, with an uppercase level label and ISO time.
    • This works in Workers, where pino runs its browser build: formatters are passed in the browser options too, and base fields are attached through child().
  • Base fields on every line: env, service (from SERVICE_NAME) and runtime: "cloudflare-workers".
  • Levels. Output is filtered by LOG_LEVEL alone. The default is debug in development and info otherwise, so LOG_LEVEL=debug enables debug output in production too.
    • The value is trimmed and case-insensitive (INFO works). Valid levels are LOG_LEVELS: fatal, error, warn, info, debug, trace, silent.
    • An unknown value logs one console.warn and falls back to the default, instead of failing at module load. resolveLogLevel(value, fallback) is exported.
  • Logging never throws. Log entries are serialized safely: BigInt becomes a string, circular references become "[Circular]", and an entry that still can't be serialized is replaced by a Failed to serialize log entry line.
  • In production, every emitted line is also passed to globalThis.logshipper.log() if the host defines it. A failing shipper is ignored. The library no longer declares a global logshipper type.
  • Request-scoped logger: inside createApp requests, getRequestLogger(c) returns a child logger bound to requestId (stored in c.var.cwbLogger, typed optional because plain Hono apps don't set it). Outside createApp it returns the root logger. There's no module-global request context, so concurrent requests never mix fields. Datasource and cache logs derive from it too.
  • Serializers are exported as serializers. Headers and sensitive URL query params are redacted. None of them throw.
    • err uses serializeError: {type, message, stack?, code?, statusCode?, cause?} with the cause chain (at most 5 levels; cycles become [Circular]).
    • req accepts a Fetch Request or a HonoRequest, so log.info({req: c.req}) works.
    • res accepts any object with status / headers.
  • serializeError(error, {includeStack?, maxDepth?}) and the SerializedError type are exported for your own reporters.
  • These are exported for your own logging: redactHeaders(headers, extra?), SENSITIVE_HEADERS, redactQueryParams(query, extra?), redactUrl(url, extra?), SENSITIVE_QUERY_PARAMS, SENSITIVE_NAME_FRAGMENTS and isSensitiveName. Register app-specific names everywhere, including logger URL redaction, with addSensitiveQueryParams(...names).
  • For tests or custom sinks: createLoggerOptions(writers?), which works with both pino builds, and baseLogBindings.
  • The Logger type is exported.

7. Environment Config

Typed readers over Worker bindings/vars (cloudflare:workers env). wrangler vars can be strings or already-parsed JSON values (booleans, numbers, arrays, objects); every typed reader accepts both. A key counts as present when it's readable on the env object (own or inherited, but not Object.prototype members such as toString); the typed readers also treat a null value as missing.

import {env, NODE_ENV, isDev, isProd, LOG_LEVEL, SERVICE_NAME} from '@ltv/cwb';

env.default('RAW_KEY', 'fallback');     // raw value
env.default.string('API_URL', 'http://localhost');
env.default.int('PORT', 8787);
env.default.float('RATIO', 0.5);
env.default.number('LIMIT', 10);         // alias of int
env.default.bool('FEATURE_X', false);
env.default.json('CONFIG', {});
env.default.array('ORIGINS', []);
env.default.date('LAUNCH_AT');

| Reader | Accepts | Unconvertible value | |---|---|---| | string | strings; numbers and booleans via String, objects and arrays via JSON.stringify | default | | int / number | numbers (truncated), numeric strings (parseInt) | default (never NaN) | | float | numbers, numeric strings (parseFloat) | default (never NaN) | | bool | booleans; true/false/1/0/yes/no/on/off, case-insensitive | default | | json | parsed values returned as-is; strings are JSON.parsed | throws on invalid JSON | | array | arrays as-is; strings split on , (a,b or ["a","b"]); a number or boolean becomes one item | objects → default | | date | date strings, epoch milliseconds | default (never an Invalid Date) |

| Constant | Source | Default | |---|---|---| | NODE_ENV | NODE_ENV | production | | isDev / isProd | derived from NODE_ENV | — | | LOG_LEVEL | LOG_LEVEL (validated by resolveLogLevel) | debug in dev, info in prod | | SERVICE_NAME | SERVICE_NAME | @ltv/cwb |

// wrangler.jsonc of your Worker
"vars": {"NODE_ENV": "production", "LOG_LEVEL": "info", "SERVICE_NAME": "my-api"}

8. Shared Types

| Type | Purpose | |---|---| | BaseUser | {id, email?, name?} | | BaseTenant | {id, name} | | BaseContextVariables | user, tenant, tenantId, requestId, traceId. It has no index signature, so a typo such as c.get('tenatId') fails to compile; extend the interface to add your own variables | | BaseEnvironmentBindings | NODE_ENV, APP_VERSION | | AppEnv<Variables, Bindings> | Hono env generic: new Hono<AppEnv<MyVars, MyBindings>>() | | ApiResponse<T>, ApiSuccessResponse<T>, ApiErrorResponse, ApiResponseMeta | Response envelope types (union discriminated on success) | | ContextResponseHelpers | The c.respond* method signatures | | PaginationMeta, PaginationParams, QueryParams | Pagination and list-query shapes | | TenantContext, TenantContextVariables | Tenant context variables (tenantId, tenant with schema, features, config) | | RequestIdConfig, RequestIdOptions, RequestLoggingConfig, RequestLoggingOptions, RequestLogLevel | createApp options | | ApiErrorOptions, ApiErrorJSON, ErrorResponse, ErrorInfo, ErrorContext, ErrorMetrics, ErrorHandlerConfig, ErrorHandlerWithMetrics, ErrorClassifier, ErrorTransformer, ErrorCategoryType, ErrorSeverityType | Error types | | SerializedError, SerializeErrorOptions, RequestLike, ResponseLike, Logger | Logging types |

9. Utilities

| Export | Description | |---|---| | createId() | CUID2 id: 24 lowercase alphanumeric characters, starting with a letter | | buildEndpointPath(base, version, route) | Normalized route path | | ENDPOINT_METHODS | Accepted route methods (get, post, put, patch, delete) | | buildPaginationMeta(page, limit, total) | Pagination meta with totalPages/hasNext/hasPrev; throws a 400 ApiError on invalid input | | redactHeaders, redactQueryParams, redactUrl, SENSITIVE_HEADERS, SENSITIVE_QUERY_PARAMS, REDACTED | Redaction | | isDevelopmentEnvironment(nodeEnv), DEVELOPMENT_ENVIRONMENTS | Fail-safe environment check | | resolveLogLevel(value, fallback), LOG_LEVELS | LOG_LEVEL validation | | getRequestLogger(c) | Request-scoped logger, or the root logger outside createApp | | serializeError(error, options?) | JSON-safe error with its cause chain; never throws | | getWaitUntil(c), runInBackground(promise, waitUntil, onError) | Run background work safely with executionCtx.waitUntil |

10. KV Caching

KVCache is exported from @ltv/cwb. Datasources create one automatically when the Worker has the KV binding (§11).

import {KVCache, getRequestLogger, getWaitUntil} from '@ltv/cwb';

const cache = new KVCache(c.env.KV, {
  defaultNamespace: 'products',  // default 'cache'
  defaultTtl: 300,               // seconds
  waitUntil: getWaitUntil(c),    // keeps background writes alive
  logger: getRequestLogger(c),   // default: root logger
});
const product = await cache.memoize('byId', {id}, () => loadProduct(id), {ttl: 60});
const result = await cache.invalidate('products:byId:'); // {deleted, complete, cursor?, failed}
if (!result.complete) {
  // budget reached: continue later (e.g. Queue consumer / Cron) with the cursor
  await cache.invalidate('products:byId:', {cursor: result.cursor});
}
await cache.clearAll('products');
  • memoize(cacheKey, params, fetchFn, {ttl?, namespace?, revive?}) is read-through caching.

    • Keys look like {namespace}:{cacheKey}:{sha256(params)}. Params are serialized deterministically: object keys sorted recursively, undefined fields dropped, null kept, and toJSON() honored, so Date and URL params get distinct keys. Map entries and Set values are sorted, and bigint gets its own marker (1n ≠ 1).
    • Params that throw a TypeError: circular structures, and class instances without toJSON() (two different instances would otherwise share a key).
    • Stored values include falsy ones (null, 0, false, ''), which are real cache hits. An undefined result is returned but not cached.
    • Writes run in the background through waitUntil. A failed read falls back to fetchFn; a failed write is logged.
    • TTL is raised to at least 60 seconds, the Workers KV minimum (MIN_KV_TTL_SECONDS).
  • JSON-only values. Values go through JSON.stringify, so a hit returns only what JSON can represent: Date becomes an ISO string, Map/Set become {}, class instances lose their prototype, undefined fields are dropped, and BigInt can't be stored (the background write fails and is logged). A miss returns the original value, so the type differs between a cold and a warm cache. Cache plain JSON data, or pass revive to restore the type on hits:

    await cache.memoize('byId', {id}, () => loadProduct(id), {revive: (v) => Product.parse(v)});

    If revive throws, the hit is treated as a miss and fetchFn runs.

  • invalidate(prefix, {cursor?, maxOperations?}) deletes matching keys within a KV operation budget.

    • Workers allow 1,000 KV operations per invocation, and every list page and delete counts. The default budget is 900 (DEFAULT_MAX_KV_OPERATIONS).
    • Returns {deleted, complete, cursor, failed}. When complete is false, call it again with cursor.
    • failed means a list or delete call failed. After failed deletes, cursor points back to where the call started, so those keys are retried.
    • A maxOperations below 2 throws a RangeError.
  • clearAll(namespace?, options?) clears one namespace, or the whole KV namespace when called without one, with the same budget and result.

  • Consistency. KV is eventually consistent: list and deletes can take about 60 seconds to reach every location, so other locations may still serve removed keys for a while. A request that read stale data before an invalidation can also re-cache it through its background write, for the full TTL. Keep TTLs short for data that must refresh promptly, or version the namespace (e.g. users:v2) instead of invalidating.

11. Datasources

Import from @ltv/cwb/datasources.

BaseDatasource interface: name, context, and optional init, connect, disconnect, healthCheck, clear.

AbstractDatasource is a base class bound to a Hono context. Subclasses must declare readonly name.

  • logger is a child of the request logger (getRequestLogger(c), so it carries requestId inside createApp), tagged {component: 'datasource', name}.
  • withCache(key, params, fetch, options?) uses a KVCache when the KV binding exists. Entries go into cacheNamespace (default: name), background writes use executionCtx.waitUntil, and cache logs go through the datasource logger. Without KV it just calls fetch. Values follow the JSON-only contract; pass options.revive to restore types.
  • cacheBinding is an overridable getter naming the KV binding on c.env (default KV).
  • clear(options?) removes this datasource's cache entries within the KV operation budget and returns {deleted, complete, cursor, failed}.
  • Lifecycle methods: init, connect, disconnect and healthCheck have default implementations.
import {AbstractDatasource} from '@ltv/cwb/datasources';

class ProductDatasource extends AbstractDatasource {
  readonly name = 'products';

  protected override get cacheBinding() {
    return 'CACHE'; // reads c.env.CACHE instead of c.env.KV
  }

  list(page: number) {
    return this.withCache('list', {page}, () => fetchProducts(page), {ttl: 60});
  }
}

DrizzleD1Datasource<TSchema> gives you Drizzle ORM on Cloudflare D1. The whole @ltv/cwb/datasources subpath, AbstractDatasource included, requires the drizzle-orm peer dependency (0.45.x).

DrizzleD1Datasource and DrizzleD1TenantDatasource are abstract: extend them and declare a unique readonly name. The name tags logs and is the default cache namespace, so two datasources with the same name would share (and clear) each other's cache entries.

| Member | Description | |---|---| | super(c, options?) | Call from your subclass constructor; create one instance per request from the Hono context | | options.schema | Your tables and relations. Enables the typed relational API db.query.* | | options.binding | Name of the D1 binding on c.env. Default DB | | options.logQueries | Log SQL at debug level through the datasource logger. Bound parameters are omitted in production. Default false | | db | Typed DrizzleD1Database<TSchema>. Created lazily on first access; throws if the binding is missing | | batch([...queries]) | Runs several statements atomically in one D1 round trip, with a typed result tuple | | healthCheck() | Runs select 1 and returns true or false. Failures are logged |

It also inherits withCache(), logger, cacheBinding and the lifecycle methods from AbstractDatasource.

// db/schema.ts
import {sqliteTable, text} from 'drizzle-orm/sqlite-core';
export const users = sqliteTable('users', {
  id: text('id').primaryKey(),
  email: text('email').notNull(),
});
import {eq} from 'drizzle-orm';
import {DrizzleD1Datasource} from '@ltv/cwb/datasources';
import * as schema from './db/schema';

class UserDatasource extends DrizzleD1Datasource<typeof schema> {
  readonly name = 'users';

  constructor(c: Context) {
    super(c, {schema});
  }

  findById(id: string) {
    return this.withCache('byId', {id}, () =>
      this.db.query.users.findFirst({where: eq(schema.users.id, id)})
    );
  }
}

Accessing datasources with c.var.ds

Register one factory per datasource with createApp({datasources}), then use c.var.ds.<name> in app-wide middleware, module middleware and handlers.

Read it the way you read any Hono context variable. c.var.ds and c.get('ds') return the same registry:

await c.var.ds.tasks.remove(projectId, taskId);

// same registry via c.get, with destructuring
const {tasks: taskDs} = c.get('ds');
await taskDs.assertProject(projectId);

Destructuring reads the names you list, so it creates those datasources right away (still once per request). Names you don't destructure are not created.

  • Lazy and per request: a factory runs the first time a request reads its name, and that instance is reused for the rest of the request. Nothing is shared between requests, since concurrent requests share an isolate (and may belong to different tenants).
  • Typing: augment DatasourceRegistry once. With defineDatasources + InferDatasources, the types come from the factories.
  • Errors: reading an unregistered name throws Datasource "x" is not registered. Add a factory to createApp({datasources}). A factory that throws (e.g. TENANT_REQUIRED) produces the normal error envelope and isn't cached, so the next access retries it. A circular dependency throws a clear error.
  • Factories and datasource methods can use other datasources through c.var.ds. The registry is read-only and enumerable.
  • Keep factories synchronous. An async factory's promise is cached for the request, including a rejected one.
  • Reserved names: then, toJSON, asymmetricMatch and Object.prototype names (constructor, toString, valueOf, …) throw a TypeError when the app or middleware is created.
  • Logging c.var is safe: the registry serializes as {datasources: [...names]} without creating anything. Spreading it ({...c.var.ds}) creates every datasource.
  • datasources is optional in the types, so omitting it after augmenting fails only at runtime, with the "not registered" error. c.var.ds is typed on every Context but set only by createApp or datasourcesMiddleware, and the name ds can clash with a context variable of your own.
// src/datasources.ts
import {defineDatasources, type InferDatasources} from '@ltv/cwb';

export const datasources = defineDatasources({
  users: (c) => new UserDatasource(c),
  orders: (c) => new OrderDatasource(c), // tenant datasource (§12)
});

declare module '@ltv/cwb' {
  interface DatasourceRegistry extends InferDatasources<typeof datasources> {}
}
// src/index.ts
createApp({datasources, modules: [users], openApi: (app) => fromHono(app)});

// in a route handler
const user = await c.var.ds.users.findById(id);

To list the types by hand instead, declare interface DatasourceRegistry {users: UserDatasource} and type the factories as DatasourceFactories; a missing or mistyped factory then fails to compile.

One augmentation per TypeScript program. Declare DatasourceRegistry in a single place. Projects compiled in the same program (for example, tests with their own registry) need a separate tsconfig.json.

Plain Hono apps and sub-apps: app.use('*', datasourcesMiddleware(datasources)) sets c.var.ds without createApp.

Constructing a datasource directly (new UserDatasource(c)) still works, e.g. for an explicit tenant in jobs (§12).

12. Multi-Tenancy

DrizzleD1TenantDatasource<TSchema> extends DrizzleD1Datasource and scopes rows to one tenant. It is abstract too. Scoped tables need a tenantId column.

  • Tenant resolution: the first match wins: options.tenantId, then c.get('tenantId'), then c.get('tenant')?.id. The last two are set by your auth middleware. Background and cron code has no request tenant, so pass options.tenantId there.
  • With c.var.ds: a registered tenant datasource is created on first use, inside the handler, after your tenant middleware ran. For an explicit tenant (jobs, admin tools), construct it directly: new OrderDatasource(c, {tenantId}) (with a constructor that forwards tenantId to super).
  • Isolation: tenant state belongs to each instance, never to the module. Concurrent requests can't leak tenants into each other.
  • No tenant, no query: reading tenantId, or calling where(), values() or any scoped* helper without a tenant, throws ApiError TENANT_REQUIRED (403).
  • Use the scoped* helpers. They always apply the tenant filter. db is unscoped: use it for system or admin queries, or together with where()/values() for joins and custom queries.

Scoped helpers (for tables with a string tenantId column):

| Member | Description | |---|---| | scopedSelect(table, {where?, orderBy?, limit?, offset?}) | Resolves to the rows of SELECT * WHERE tenantId = current AND where [ORDER BY] [LIMIT] [OFFSET]. It returns rows, not a builder, so the tenant filter can't be replaced. orderBy takes a column or SQL expression, or an array of them. limit/offset must be non-negative integers, and offset requires limit (RangeError otherwise) | | scopedCount(table, where?) | Number of the current tenant's rows matching where | | scopedInsert(table, row) / scopedInsertMany(table, rows) | Insert with tenantId set to the current tenant, overriding any client-supplied value. Returns a ScopedInsertQuery: await it, call .returning(), or call .onConflictDoNothing() | | scopedUpdate(table, set, ...conditions) | Update the current tenant's rows only. Any tenantId in set is dropped, so rows can't be moved to another tenant | | scopedUpsert(table, row, {target, set}) | Insert for the current tenant, or update on conflict only if the conflicting row belongs to the current tenant (setWhere). set accepts values or sql expressions (e.g. sql`excluded.body`); tenantId is dropped. A conflict with another tenant's row affects 0 rows, so check .returning() or meta.changes. Returns a ScopedWriteQuery (await it or call .returning()) | | scopedDelete(table, ...conditions) | Delete the current tenant's rows only | | tenantId | Current tenant id. Throws TENANT_REQUIRED when none is set | | where(table, ...conditions) | Scoped where clause for custom queries. undefined conditions are ignored | | values(row \| rows) | Adds the current tenantId to insert values |

The write helpers return narrow queries, not Drizzle builders: ScopedWriteQuery (await it for the D1 result, or call .returning() for rows) and ScopedInsertQuery (which adds .onConflictDoNothing()). Nothing can be chained that would replace or bypass the tenant filter, such as .where(), .onConflictDoUpdate() or $dynamic(). They can't be passed to db.batch(); for batches, use ds.db with ds.where() / ds.values().

Tenant-aware cache: withCache entries live under {name}:tenant:{encodeURIComponent(tenantId)}. A caller-supplied options.namespace is nested inside that, as ...:tenant:{id}:{namespace}. One tenant's cached data is never served to another, and clear() removes only the current tenant's entries.

import {and, desc, eq} from 'drizzle-orm';
import {DrizzleD1TenantDatasource} from '@ltv/cwb/datasources';
import * as schema from './db/schema';
const {orders} = schema;

class OrderDatasource extends DrizzleD1TenantDatasource<typeof schema> {
  readonly name = 'orders';

  constructor(c: Context) {
    super(c, {schema}); // tenant from c.get('tenantId')
  }
}

// in a handler, after your middleware set the tenant (registered as `orders`, see §11)
const ds = c.var.ds.orders;

await ds.scopedInsert(orders, {id, total: 100});
const page = await ds.scopedSelect(orders, {
  where: eq(orders.status, 'open'),
  orderBy: desc(orders.createdAt),
  limit: 20,
  offset: 40,
});
const total = await ds.scopedCount(orders, eq(orders.status, 'open'));
await ds.scopedUpdate(orders, {total: 120}, eq(orders.id, id)).returning();
await ds.scopedUpsert(orders, {id, total: 100}, {target: orders.id, set: {total: 100}});
await ds.scopedDelete(orders, and(eq(orders.id, id), eq(orders.status, 'open')));

// custom queries: combine db with where()/values()
await ds.db.query.orders.findMany({where: ds.where(orders)});

// system-level (unscoped)
await ds.db.select().from(orders);

Scoping safety with raw db

  • ❌ ds.db.delete(orders) or ds.db.update(orders).set(x) without .where(ds.where(orders)) affects every tenant. Use scopedDelete / scopedUpdate.
  • ❌ ds.db.update(orders).set(req.body) lets a client move a row to another tenant through body.tenantId. scopedUpdate drops tenantId, and so does withoutTenantId(body).
  • ❌ ds.db.insert(t).values(...).onConflictDoUpdate(...) is unscoped on conflict. Use scopedUpsert; scoped helpers return narrow queries that don't expose it.
  • Prefer scopedSelect / scopedCount for paginated lists instead of ds.db.select().
  • where() scopes a single table. Joined tables need their own ds.where(joinedTable). For nested relational with: {...} includes, filter with the callback form where: (t, {eq}) => eq(t.tenantId, ds.tenantId).

Standalone helpers work with any Drizzle database:

  • tenantWhere(table, tenantId, ...conditions) builds a scoped where clause.
  • withTenantId(values, tenantId) sets tenantId on insert values.
  • withoutTenantId(values) removes tenantId from update values.
  • Types: TenantScopedTable, TenantTable, TenantInsert<T>, WithTenantId<V>, ScopedSelectOptions, ScopedOrderBy.

Package Exports

| Import | Contents | |---|---| | @ltv/cwb | App: createApp, defineModule, defineDatasources, datasourcesMiddleware, EndpointRegistry, buildEndpointPath, ENDPOINT_METHODS, contextHelpers, buildPaginationMetaErrors: createErrorHandler, errorHandler, isProductionContext, buildErrorContext, ErrorMetricsTracker, ApiError, ErrorCategory, ErrorSeverityLogging: logger, createLogger, getRequestLogger, serializers, serializeError, createLoggerOptions, baseLogBindings, redactHeaders, redactQueryParams, redactUrl, addSensitiveHeaders, addSensitiveQueryParams, isSensitiveName, SENSITIVE_HEADERS, SENSITIVE_QUERY_PARAMS, SENSITIVE_NAME_FRAGMENTS, REDACTEDConfig and utils: env, NODE_ENV, isDev, isProd, LOG_LEVEL, LOG_LEVELS, resolveLogLevel, SERVICE_NAME, isDevelopmentEnvironment, DEVELOPMENT_ENVIRONMENTS, KVCache, MIN_KV_TTL_SECONDS, DEFAULT_MAX_KV_OPERATIONS, getWaitUntil, runInBackground, createIdOpenAPI: json* helpers, MetaSchema, PaginationMetaSchema, ErrorSchemaTypes (§8) | | @ltv/cwb/datasources | Classes: AbstractDatasource, DrizzleD1Datasource, DrizzleD1TenantDatasource (abstract), BaseDatasource (interface)Helpers: tenantWhere, withTenantId, withoutTenantIdTypes: DrizzleSchema, DrizzleD1DatasourceOptions, DrizzleD1TenantDatasourceOptions, ScopedSelectOptions, ScopedOrderBy, ScopedWriteQuery, ScopedInsertQuery, TenantScopedTable, TenantTable, TenantInsert, WithTenantId |

These packages are not bundled into @ltv/cwb:

  • Runtime dependencies: pino, @paralleldrive/cuid2, cloudflare:workers.
  • Peer dependencies: hono ^4.13, chanfana ^3.4, zod ^4.4.3. With hono as a peer there's a single Hono copy, so instanceof HTTPException and the c.respond* / c.var.cwbLogger type augmentations work in your app.
  • Optional peer dependency: drizzle-orm 0.45.x, needed only for @ltv/cwb/datasources.

Both entry points share one chunk, so ApiError thrown from datasources is still recognized by errorHandler.

Development

Requires Bun 1.4.x (installs pin exact versions via bunfig.toml); the workerd end-to-end tests also need Node 24. Toolchain: TypeScript 7 (native tsc), tsdown, oxlint.

| Command | Description | |---|---| | bun install | Install dependencies | | bun run build | Build dist/ with tsdown: ESM, plus .d.ts generated by tsgo; both entries share one chunk | | bun run typecheck | tsc --noEmit for the library, then for examples/basic-worker (its own tsconfig.json) (TypeScript 7) | | bun run lint / bun run lint:fix | oxlint with type-aware rules (.oxlintrc.json, via oxlint-tsgolint) | | bun run format / bun run format:check | Prettier (@hiliosai/prettier) | | bun test / bun run test:watch | Test suite (Testing) | | bun run test:coverage | Tests + coverage gate (every src file ≥ 90% lines and functions) | | bun run test:e2e | Build, then run examples/basic-worker in real workerd (node --test tests-e2e) | | bun run check:size | Gzip size budget per built file | | bun run api:check / bun run api:update | Check / regenerate the public API snapshot etc/cwb.api.d.ts | | bun run cf-typegen | Regenerate worker-configuration.d.ts from wrangler.jsonc | | bun run check:package | Validate the built package (publint + are-the-types-wrong) |

CI and releases:

  • main accepts squash-merged PRs only. Every PR must pass verification (types, lint, format, tests with the coverage gate, build, package, size and API-report checks), end-to-end tests in real workerd, commitlint on each commit, a Conventional PR title check, a workflow audit (zizmor), and security scans (bun audit, TruffleHog, Semgrep).
  • After squash-merge, release-please opens a release PR that bumps the version from the commit types (fix → patch, feat → minor, breaking → major; pre-1.0 one level lower) and updates CHANGELOG.md. Merging it publishes to npm.
  • See docs/CONTRIBUTING.md, docs/deployment-guide.md, docs/support-policy.md and docs/SECURITY.md.

wrangler.jsonc declares the KV and DB bindings. It is used for type generation and by the tests' local bindings; the library itself is not deployed. More docs live in docs/.

Testing

bun test runs the suite in tests/:

  • cloudflare:workers is mocked by a preload file (tests/helpers/cloudflare-workers-module-mock.ts, configured in bunfig.toml). It provides a mutable workerEnv in which NODE_ENV is deliberately unset, so production defaults are what gets tested.
  • D1 and KV are real local bindings from wrangler's getPlatformProxy() (tests/helpers/local-workers-bindings.ts), running in workerd and kept in memory.
  • runWithHonoContext(env, fn) runs code inside a real Hono request context, with a stub executionCtx.waitUntil.
bun test                                   # everything
bun test tests/datasources                 # one folder
bun test tests/cache/kv-cache.test.ts      # one file
bun test -t "tenants are isolated"         # tests matching a name

The end-to-end suite (tests-e2e/, bun run test:e2e) builds the package and runs examples/basic-worker in real workerd through wrangler's test harness. It checks the error envelopes, D1 through a datasource, KV caching and the OpenAPI document against the built output.

Known Limitations

  • Joins and relational includes aren't scoped automatically. The scoped* helpers cover single-table queries. Joins, raw sql and relational with includes need an explicit ds.where(table) for each tenant-scoped table.
  • D1 has no interactive transactions. Use batch() for atomic multi-statement writes.
  • Error metrics and throttling are per isolate. Each Worker isolate keeps its own counters; they are not aggregated globally.
  • Only a D1 datasource is provided (DrizzleD1Datasource). Other Drizzle drivers can extend AbstractDatasource.
  • Large cache invalidations take several invocations. Each call stays within the per-invocation KV operation budget; continue with the returned cursor.
  • KV is eventually consistent. Invalidated keys can still be served elsewhere for about a minute, and a concurrent request can re-cache stale data (§10).
  • Module routes match in registration order. With overlapping patterns, list the more specific module first (§2).