@itaylor/type-router-worker
v0.1.0
Published
Worker bindings for type-router - type-safe, declarative request routing for Cloudflare Workers and other fetch-handler runtimes
Downloads
21
Maintainers
Readme
type-router-worker
Worker bindings for type-router: type-safe, declarative request routing for Cloudflare Workers and any other fetch-handler runtime (Deno.serve, Bun, service workers). Zero dependencies beyond type-router itself.
It reuses type-router's default path extractor for both halves of the contract —
the compile-time layer (params inferred from the path string) and the runtime
matcher (same :param syntax, same URL decoding, same typed query-param
support). Only the shell differs from the browser router: a server has no
"current route", so there is no navigation state and there are no lifecycle
hooks — a router here is a pure (Request, Ctx) -> Response dispatcher.
Features
- 🎯 Type-safe routes: parameter names and types inferred from path strings,
same syntax as type-router (
/user/:id?tab&count=number) - 🧩 Bring your own context: handlers receive your request-scoped
Ctx(env bindings, parsed URL, authenticated user, ...) untouched - 🔀 Composable groups:
handleresolves tonullon a miss, so routers chain with??— auth boundaries and host guards stay explicit in yourfetchhandler instead of hiding in middleware - 📜 Declaration order = match priority: the route table reads like an API spec, top to bottom
- 🔍 Typed query parameters: declared in the path, decoded with their annotated types, never affect matching
- 🪶 Tiny: one file, no dependencies
Installation
# Deno
deno add @itaylor/type-router-worker
# npm (use any of npx, yarn dlx, pnpm dlx, or bunx)
npx jsr add @itaylor/type-router-workerQuick Start
import { createWorkerRouter } from '@itaylor/type-router-worker';
type Ctx = { env: Env; url: URL };
const router = createWorkerRouter<Ctx>()(
[
{
path: '/health', // no method = GET
handler: () => new Response('ok'),
},
{
path: '/user/:id',
handler: (ctx, params) => new Response(`user ${params.id}`),
},
{
method: 'DELETE',
path: '/user/:id',
handler: (ctx, params) => new Response(null, { status: 204 }),
},
{
path: '/search?q&page=number',
handler: (ctx, params) =>
Response.json({ q: params.q ?? '', page: params.page ?? 1 }),
},
] as const,
);
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const ctx = { env, url: new URL(request.url) };
return (await router.handle(request, ctx)) ??
new Response('not found', { status: 404 });
},
};Core Concepts
Routes
A route is { method?, path, handler }. method defaults to 'GET' — most
worker route tables are predominantly GETs, so only non-GET routes need to say
so. The path syntax is exactly type-router's: :param segments (required,
string) and declared query parameters after ? (optional, typed by their
annotations — ?q is string | undefined, ?count=number, ?exact=bool,
?tags=string[]).
Routes match in declaration order; the first (method, path) match wins. Put
literal paths before overlapping :param paths:
{ path: '/files/special', handler: ... }, // first
{ path: '/files/:name', handler: ... }, // then the catch-allMethod matching is exact — HEAD does not fall back to GET; declare it if you
serve it. One hazard the GET default buys: forgetting method on an intended
POST route makes it a second GET route for that path, and with declaration-order
matching either it or the real GET route is silently dead — name the method on
every non-GET route.
Context
createWorkerRouter<Ctx>() is curried: name your context type once, and every
handler receives it as the first argument. The router never inspects Ctx —
build whatever your app needs per request and pass it to handle.
Composing routers (auth boundaries, host guards)
handle resolves to null when nothing matches (unless you set onMiss), so
routers that share a context chain directly with ?? — first match wins, and
the final fallback is just the right-hand side:
const pageRouter = createWorkerRouter<Ctx>()(pageRoutes);
const assetRouter = createWorkerRouter<Ctx>()(assetRoutes);
const devRouter = createWorkerRouter<Ctx>()(devSeamRoutes);
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const ctx = { env, url: new URL(request.url) };
return (await pageRouter.handle(request, ctx)) ??
(await assetRouter.handle(request, ctx)) ??
(await devRouter.handle(request, ctx)) ??
new Response('not found', { status: 404 });
},
};When a group needs its own setup — authentication, a different Ctx — break the
chain with an ordinary if, and the boundary stays visible in fetch:
const publicRouter = createWorkerRouter<Ctx>()(publicRoutes);
const apiRouter = createWorkerRouter<AuthedCtx>()(apiRoutes, {
// Unmatched /api/* paths get a JSON 404, not fall-through.
onMiss: () => Response.json({ error: 'not_found' }, { status: 404 }),
});
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const ctx = { env, url: new URL(request.url) };
const pub = await publicRouter.handle(request, ctx);
if (pub) return pub;
if (ctx.url.pathname.startsWith('/api/')) {
const account = await authenticate(request, env);
if (!account) return new Response('unauthorized', { status: 401 });
return (await apiRouter.handle(request, { ...ctx, account }))!;
}
return new Response('not found', { status: 404 });
},
};WebSocket upgrades
There is no UPGRADE HTTP method — a WebSocket handshake arrives as a GET
request carrying an Upgrade: websocket header. So a WebSocket endpoint is just
a GET route whose handler inspects that header and returns the runtime's 101
response (which is an ordinary Response, so nothing special is needed from the
router). Carry the Request in your Ctx so the handler can reach the headers:
type Ctx = { env: Env; request: Request };
const route = makeWorkerRoute<Ctx>();
const wsRoute = route({
path: '/ws/:room', // upgrades are GETs, so the default method is right
handler: (ctx, params) => {
if (ctx.request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {
return new Response('expected a websocket upgrade', { status: 426 });
}
// Cloudflare Workers:
const pair = new WebSocketPair();
const [client, server] = Object.values(pair);
server.accept();
server.addEventListener('message', (e) => {
/* ... params.room ... */
});
return new Response(null, { status: 101, webSocket: client });
// Deno.serve equivalent:
// const { socket, response } = Deno.upgradeWebSocket(ctx.request);
// socket.onmessage = (e) => { /* ... */ };
// return response;
},
});Non-upgrade GETs to the same path land in the same handler (it's one route),
which is what the 426 branch is for — or split them into two plain functions
inside the handler if the endpoint also serves a page.
Precise param types: makeWorkerRoute
Routes written inline in the array get params typed as
Record<string, string> — every access is a string, but key exactness and
typed query params aren't enforced (this mirrors the browser router's
inline-route semantics). For fully precise per-route params, define routes with
makeWorkerRoute outside the array, the analogue of type-router's makeRoute:
import { makeWorkerRoute } from '@itaylor/type-router-worker';
const route = makeWorkerRoute<Ctx>();
const userRoute = route({
method: 'GET',
path: '/user/:id?tab&page=number',
handler: (ctx, params) => {
// params: { id: string; tab?: string; page?: number } — exact keys
return new Response(params.id);
},
});
const router = createWorkerRouter<Ctx>()([userRoute] as const);Define such routes as standalone consts. Wrapping a route with the helper
inline inside the array buys nothing over a bare object there, and costs the
router its precise computePath path union (the array's contextual type widens
the call's inferred path to string).
Trailing slashes
By default matching is lax — /health and /health/ both match, like the
browser router. Pass { trailingSlash: 'strict' } when trailing-slash URLs must
stay 404s (for example, preserving an existing API's exact behavior).
computePath
Build concrete URLs from route patterns, typed to the router's declared paths:
router.computePath('/user/:id', { id: 'a b' }); // '/user/a%20b'
router.computePath('/nope'); // ❌ TypeScript error: unknown routematch
The matching step alone — handy in tests and for custom dispatch:
const m = router.match('GET', '/user/42');
// m: { route, params: { id: '42' } } | nullAPI Reference
createWorkerRouter<Ctx>()(routes, options?)
Returns a WorkerRouter. routes is a const array of
{ method?, path, handler } (method defaults to 'GET'); options:
| Option | Type | Default | Description |
| --------------- | ------------------- | ------- | --------------------------------------------- |
| trailingSlash | 'lax' \| 'strict' | 'lax' | Whether /x/ matches the pattern /x |
| onMiss | (ctx) => Response | — | Response for unmatched requests (else null) |
Router methods
handle(request, ctx)→Promise<Response | null>— match and run.match(method, pathWithQuery)→{ route, params } | null.computePath(pattern, params?)→string.
makeWorkerRoute<Ctx>()
Returns a route(def) identity helper that pins the path literal for fully
precise params inference. Use for routes defined outside the
createWorkerRouter call.
Errors
- Invalid patterns (
//empty segments) throw at router construction. - Handler errors propagate out of
handle— add your own try/catch boundary infetchif you want a global 500.
License
MIT
