@ltv/cwb
v0.2.1
Published
Cloudflare Workers Bootstrap with hono
Maintainers
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:workersat 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
typescriptpeer 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-ormConsumer TypeScript setup
- Workers types. Published types reference Workers globals (
D1Database,KVNamespace,ExecutionContext). Generate them withwrangler types(recommended) or install@cloudflare/workers-types, and uselib: ["es2024"]. - Node types from pino. pino's type definitions import Node modules (
events,worker_threads). Either set"skipLibCheck": trueor install@types/node; otherwisetscreports errors insidepino.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 /docsFeatures
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-Idis reused when Hono's request-id middleware accepts it (at most 255 characters of[A-Za-z0-9_=-]). - Otherwise
cf-rayis used if it matches^[A-Za-z0-9-]{1,64}$, and otherwise a new cuid2 is generated. The deprecated, client-spoofablecf-request-idheader 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: falsedisables 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 anOpenAPIRouteclass. versiondefaults to'v1'. A number is prefixed withv(2becomesv2), and a string is used as-is.- The final route path is
{path}/{version}{route}, normalized: duplicate or trailing slashes are removed, sopath: '/'gives/v1/usersandpath: '/api/'gives/api/v1/users. A plainApiModuleobject without aversionis mounted at{path}{route}. createAppthrows before registering anything when:- a route key is malformed (missing method, or a path not starting with
/); - the method is not
GET,POST,PUT,PATCHorDELETE(the method is case-insensitive); - two routes, in any modules, resolve to the same method and final path.
- a route key is malformed (missing method, or a path not starting with
middlewareon 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/:idin module A before/items/publicin 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/:idand module B hasGET /items/public, list B first, or/v1/items/publicis handled by A (and A's middleware).
Auth must go through
middleware.createAppregisters module routes before returning the app. Middleware added afterwards withapp.use()runs after the routes and never guards them. UsecreateApp({middleware: [...]})for app-wide middleware, ordefineModule({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 plainnew Hono()app,c.respondtype-checks but isundefined.
| 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:
pageis 1-based.totalPagesisceil(total / limit)(0 when there are no items),hasNextispage < totalPagesandhasPrevispage > 1.- It throws a 400
BAD_REQUESTApiErrorwhenpageorlimitis not a positive integer, ortotalis 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
ApiErrorhas these properties:id(a cuid2),code,status,category,severity,detailsandcause. toJSON()returnsApiErrorJSON: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 byinstanceof. AnApiErrorcreated by a second installed copy of the library still keeps its status and message. UseApiError.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
HTTPExceptionkeeps its status and gets a matching code (UNAUTHORIZED,PAYLOAD_TOO_LARGE, ...). - Any other
ErrorbecomesINTERNAL_ERROR(500). - Any non-error value becomes
UNKNOWN_ERROR(500).
- An
ApiError.isApiError(err),ApiError.is(err, code),ApiError.isCategory(err, category)andApiError.isSeverity(err, severity)are type guards.
Classification
ErrorCategory:authentication,authorization,validation,business_logic,external_service,database,rate_limit,system,unknownErrorSeverity: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(fromc.env, then the Worker env) isdevelopment,dev,testorlocal, compared case-insensitively.staging,prod, typos or an empty value all count as production (isDevelopmentEnvironment()). - What clients see.
ApiErrorand HonoHTTPException4xx errors return their message and details, because clients need them.- Other errors (e.g. raw D1/driver errors) never expose their original message. A
transformercan supply a client-safemessage; without one, 4xx getsRequest failed. - 5xx errors return
Internal server errorwith no details in production, unlessincludeDetailsis 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, anddetails.detailsare always included (they are masked only in responses), so don't put secrets in them.stackis the stack of the thrown error, i.e. the original throw site, not the handler's wrapper (whenincludeStackTrace).causeis the serializedcausechain of the thrown error (SerializedError, at most 5 levels; stacks only whenincludeStackTrace).context: requestId, userId, tenantId, method, path, ip, user agent, redacted headers and redacted query params.context.includeClientInfo: falseomits ip and user agent.
- Logging. Unless
customLoggeris set, 5xx errors are logged aterror(Server error) and 4xx atwarn(Client error) through the request-scoped logger, so the lines carryrequestId. A log call that fails never breaks the response. - Hooks can't break the envelope. A
classifier,transformer,customLoggerorerrorReporterthat throws is logged and ignored. - Throttling never hides server errors. During error storms, only non-critical 4xx logs and reports are throttled; 5xx and
criticalerrors 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, andNotFoundExceptionand otherApiExceptions, whetherfromHonouses its default mode orpassthroughErrors: true. Validation failures become 422VALIDATION_ERRORwithdetails: [{field: 'body.email', message, code: '7001'}], matchingjsonValidationError. - Hono
HTTPExceptions that carry their own response (e.g.basicAuthwithWWW-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 uppercaselevellabel and ISOtime.- This works in Workers, where pino runs its browser build: formatters are passed in the
browseroptions too, and base fields are attached throughchild().
- This works in Workers, where pino runs its browser build: formatters are passed in the
- Base fields on every line:
env,service(fromSERVICE_NAME) andruntime: "cloudflare-workers". - Levels. Output is filtered by
LOG_LEVELalone. The default isdebugin development andinfootherwise, soLOG_LEVEL=debugenables debug output in production too.- The value is trimmed and case-insensitive (
INFOworks). Valid levels areLOG_LEVELS:fatal,error,warn,info,debug,trace,silent. - An unknown value logs one
console.warnand falls back to the default, instead of failing at module load.resolveLogLevel(value, fallback)is exported.
- The value is trimmed and case-insensitive (
- Logging never throws. Log entries are serialized safely:
BigIntbecomes a string, circular references become"[Circular]", and an entry that still can't be serialized is replaced by aFailed to serialize log entryline. - 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 globallogshippertype. - Request-scoped logger: inside
createApprequests,getRequestLogger(c)returns a child logger bound torequestId(stored inc.var.cwbLogger, typed optional because plain Hono apps don't set it). OutsidecreateAppit 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.errusesserializeError:{type, message, stack?, code?, statusCode?, cause?}with thecausechain (at most 5 levels; cycles become[Circular]).reqaccepts a FetchRequestor a HonoRequest, solog.info({req: c.req})works.resaccepts any object withstatus/headers.
serializeError(error, {includeStack?, maxDepth?})and theSerializedErrortype 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_FRAGMENTSandisSensitiveName. Register app-specific names everywhere, including logger URL redaction, withaddSensitiveQueryParams(...names). - For tests or custom sinks:
createLoggerOptions(writers?), which works with both pino builds, andbaseLogBindings. - The
Loggertype 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,undefinedfields dropped,nullkept, andtoJSON()honored, soDateandURLparams get distinct keys.Mapentries andSetvalues are sorted, andbigintgets its own marker (1n≠1). - Params that throw a
TypeError: circular structures, and class instances withouttoJSON()(two different instances would otherwise share a key). - Stored values include falsy ones (
null,0,false,''), which are real cache hits. Anundefinedresult is returned but not cached. - Writes run in the background through
waitUntil. A failed read falls back tofetchFn; a failed write is logged. - TTL is raised to at least 60 seconds, the Workers KV minimum (
MIN_KV_TTL_SECONDS).
- Keys look like
JSON-only values. Values go through
JSON.stringify, so a hit returns only what JSON can represent:Datebecomes an ISO string,Map/Setbecome{}, class instances lose their prototype,undefinedfields are dropped, andBigIntcan'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 passreviveto restore the type on hits:await cache.memoize('byId', {id}, () => loadProduct(id), {revive: (v) => Product.parse(v)});If
revivethrows, the hit is treated as a miss andfetchFnruns.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}. Whencompleteis false, call it again withcursor. failedmeans a list or delete call failed. After failed deletes,cursorpoints back to where the call started, so those keys are retried.- A
maxOperationsbelow 2 throws aRangeError.
- Workers allow 1,000 KV operations per invocation, and every list page and delete counts. The default budget is 900 (
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:
listand 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.
loggeris a child of the request logger (getRequestLogger(c), so it carriesrequestIdinsidecreateApp), tagged{component: 'datasource', name}.withCache(key, params, fetch, options?)uses aKVCachewhen the KV binding exists. Entries go intocacheNamespace(default:name), background writes useexecutionCtx.waitUntil, and cache logs go through the datasource logger. Without KV it just callsfetch. Values follow the JSON-only contract; passoptions.reviveto restore types.cacheBindingis an overridable getter naming the KV binding onc.env(defaultKV).clear(options?)removes this datasource's cache entries within the KV operation budget and returns{deleted, complete, cursor, failed}.- Lifecycle methods:
init,connect,disconnectandhealthCheckhave 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).
DrizzleD1DatasourceandDrizzleD1TenantDatasourceare abstract: extend them and declare a uniquereadonly 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
DatasourceRegistryonce. WithdefineDatasources+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,asymmetricMatchandObject.prototypenames (constructor,toString,valueOf, …) throw aTypeErrorwhen the app or middleware is created. - Logging
c.varis safe: the registry serializes as{datasources: [...names]}without creating anything. Spreading it ({...c.var.ds}) creates every datasource. datasourcesis optional in the types, so omitting it after augmenting fails only at runtime, with the "not registered" error.c.var.dsis typed on everyContextbut set only bycreateAppordatasourcesMiddleware, and the namedscan 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
DatasourceRegistryin a single place. Projects compiled in the same program (for example, tests with their own registry) need a separatetsconfig.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, thenc.get('tenantId'), thenc.get('tenant')?.id. The last two are set by your auth middleware. Background and cron code has no request tenant, so passoptions.tenantIdthere. - 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 forwardstenantIdtosuper). - 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 callingwhere(),values()or anyscoped*helper without a tenant, throwsApiErrorTENANT_REQUIRED(403). - Use the
scoped*helpers. They always apply the tenant filter.dbis unscoped: use it for system or admin queries, or together withwhere()/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)ords.db.update(orders).set(x)without.where(ds.where(orders))affects every tenant. UsescopedDelete/scopedUpdate.- ❌
ds.db.update(orders).set(req.body)lets a client move a row to another tenant throughbody.tenantId.scopedUpdatedropstenantId, and so doeswithoutTenantId(body).- ❌
ds.db.insert(t).values(...).onConflictDoUpdate(...)is unscoped on conflict. UsescopedUpsert; scoped helpers return narrow queries that don't expose it.- Prefer
scopedSelect/scopedCountfor paginated lists instead ofds.db.select().where()scopes a single table. Joined tables need their ownds.where(joinedTable). For nested relationalwith: {...}includes, filter with the callback formwhere: (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)setstenantIdon insert values.withoutTenantId(values)removestenantIdfrom 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. Withhonoas a peer there's a single Hono copy, soinstanceof HTTPExceptionand thec.respond*/c.var.cwbLoggertype augmentations work in your app. - Optional peer dependency:
drizzle-orm0.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:
mainaccepts 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 updatesCHANGELOG.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:workersis mocked by a preload file (tests/helpers/cloudflare-workers-module-mock.ts, configured inbunfig.toml). It provides a mutableworkerEnvin whichNODE_ENVis 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 stubexecutionCtx.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 nameThe 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, rawsqland relationalwithincludes need an explicitds.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 extendAbstractDatasource. - 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).
