Skip to content

@edgetime/router

Request router and middleware pipeline, typed per-request context, providers, extensions and host dispatch. No dependencies.

npm install @edgetime/router

A request router and middleware pipeline for any runtime with the Fetch API. No dependencies.

import { Router } from '@edgetime/router';
type App = { env: { DB: Database }; vars: { userId: string } };
const app = new Router<App>()
.use(async (c, next) => {
c.set('userId', c.header('x-user') ?? 'anonymous');
return next();
})
.get('/users/:id', (c) => c.json({ id: c.params.id, viewer: c.get('userId') }))
.get('/files/*', (c) => c.text(c.params['*']));
export default { fetch: app.fetch };

app.fetch(request, env?, ctx?) never rejects and always resolves to a Response: anything thrown becomes one, and so does a handler that returns something else.

Registration is strict. A handler, middleware or provider that is not a function is refused with a TypeError, so a flag && guard that evaluates to false cannot silently drop a guard; build the list first and pass only functions.

  • Paths are literal segments, :name parameters and a trailing *. c.params is typed from the path string and percent-decoded.
  • A literal segment wins over a parameter, which wins over the wildcard. The router backtracks when a branch has no route for the method.
  • A trailing slash on the request path is ignored.
  • Equivalent paths are matched alike: an escape of a character that needs none is decoded before matching, so /%61dmin is /admin to routes and to prefix middleware. An encoded slash (%2F) stays inside its segment and never matches a / in a pattern. A % that does not start a valid escape is treated as a literal percent sign.
  • Registered paths and prefixes are spelled the same way, so get('/café') matches a request that arrives as /caf%C3%A9, and get('/a{b}') one that arrives as /a%7Bb%7D. A path containing ?, # or a backslash is refused at registration.
  • Parameter values are decoded. By default a request is answered 404 when decoding would give a :name value containing /, any value with a . or .. segment, a backslash or a NUL, so /files/..%2Fsecret cannot reach a :name used as a key. new Router({ strictParams: false }) passes such values through, for routes whose parameters carry encoded slashes; validate them yourself. The setting of the router serving the request applies, including to mounted routes.
  • get, post, put, patch and delete register one method, on(method, path, ...) any method, and all(path, ...) every method not registered on its own.
  • A path that matches under another method gets 405 with Allow. HEAD is served from the GET route without a body, and OPTIONS is answered with 204 and Allow.
  • Registering the same method and path twice throws.

A middleware is (c, next) => Response | Promise<Response>. A route takes any number of them; the last is the handler.

  • use(...middleware) applies to every request, in registration order.
  • use('/admin', ...middleware) applies to that literal prefix and everything under it.
  • Middleware also wraps 404 and 405 responses.
  • mount('/v1', child) copies a child router’s routes and middleware under a prefix. The child’s error handler is not carried over. It is a copy: routes added to the child afterwards are not mounted. Mounting at / applies the child’s own middleware to every route of the parent.
Member Purpose
c.req, c.env, c.ctx The request, the environment and the execution context.
c.replaceRequest(request) Hands later middleware and the handler another request with the same method and URL, such as one whose body is wrapped. Anything else throws.
c.path, c.params The request path the router matched: still percent-encoded, except that escapes of characters needing none are decoded. And the decoded route parameters.
c.url, c.query(name), c.header(name) The parsed URL (built on first use), a query value and a request header.
c.get(key), c.set(key, value) Per-request values, typed by the app’s vars.
c.lazy(key, build) Registers a factory that runs the first time key is read.
c.json(), c.text(), c.html(), c.redirect() Response helpers.
c.error The error behind the current response, for logging middleware.

On a runtime that passes no execution context, c.ctx.waitUntil() is a no-op.

onError((error, c) => Response) receives everything thrown, including the router’s own RouteError for 404 and 405. The response it returns still passes back through the middleware outside the point of failure. Without a handler, an error with a toResponse() method answers for itself, an error with a 4xx status gets that status with a generic body, and anything else becomes a plain 500. An onError handler that itself throws gets the same treatment, applied to the original error, so its status survives. Only the router’s own Not Found and Method Not Allowed messages are sent as text. errorHandler() from @edgetime/http renders problem details.

compose(...middleware) joins several middleware into one, so a stack can be defined once and applied to a router, a prefix or a single route.

provide(factories) registers a factory per vars key. A factory runs the first time a handler reads its key, and at most once per request, so a request that never needs a dependency does not build it. A factory that throws runs again on the next read and throws again. Handlers depend on the type of the value and not on how it is made; a test replaces the factory, or calls c.set() before the handler runs.

import { compose, provide, Router } from '@edgetime/router';
type App = { env: Env; vars: { db: Database; mailer: Mailer; auth: AuthInfo } };
const services = provide<App>({
db: (c) => connect(c.env.DATABASE_URL),
mailer: (c) => createMailer(c.env.MAIL_KEY),
});
const app = new Router<App>()
.use(services)
.post('/invites', compose(authenticated, limited), async (c) => {
const invite = await c.get('db').invites.create(c.get('auth').subject);
await c.get('mailer').send(invite);
return c.json(invite, 201);
});

An extension is a function that receives the router and registers routes, middleware and providers on it. extend(...extensions) installs them in order. It is the way to package a feature so an application adds it in one line.

import type { Extension } from '@edgetime/router';
export function health(path = '/health'): Extension {
return (router) => {
router.get(path, (c) => c.json({ status: 'ok' }));
};
}
const app = new Router<App>().extend(health());
  • An extension uses the router’s public methods and has no other access.
  • Type it by the env and vars it needs, such as Extension<{ vars: { requestId: string } }>. It then fits any application that has at least those.
  • It registers synchronously. One that returns a promise is refused with a TypeError.
  • Installing is all or nothing. If an extension throws, everything it registered is removed again, including an error handler it set. mount() behaves the same way.
  • An extension may call onError(). The last handler set wins, so set the application’s own after extend().
  • An extension that needs env or vars the application does not declare is a type error. Extensions typed differently go in separate extend() calls, so each is checked on its own. Middleware passed to use() is not checked this way; provide what it documents.
  • An async extension is refused, and until it finishes the router refuses all registration, so nothing it does after an await is added.
  • Use mount() instead when the feature is a router of its own under a prefix.
Export Purpose
perEnv(build) Memoizes a value per environment object, for clients built from bindings. A factory that throws is not cached.
byHost(hosts, fallback?) Dispatches by host name. Keys are exact names or *.example.com; an exact name wins, then the longest wildcard. A trailing dot on the request’s host is ignored. Returns 404 when nothing matches and there is no fallback.
hostOf(url), pathOf(url) Read the host name or path from request.url without parsing it. They do not validate input; use new URL() for anything a client controls, such as an Origin header or a redirect target.
normalizePath(path) The path normalisation the router applies before matching.
import { byHost } from '@edgetime/router';
export default {
fetch: byHost({ 'api.example.com': api, '*.example.com': tenants }, marketing),
};

Source: packages/router on GitHub.