Skip to content

Write an extension

Package a feature as a function that receives the router, so an application adds it in one line.

An extension is a function that receives the router and registers routes, middleware and providers on it. Give it options through a factory, and type it by the env and vars it needs, so it fits any application that has them.

import type { Extension } from '@edgetime/router';
export function health(options: { path?: string } = {}): Extension {
return (router) => {
router.get(options.path ?? '/health', (c) => c.json({ status: 'ok' }));
};
}
const app = new Router<App>().extend(health(), billing({ plans }));
  • 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 } }>. An extension that needs env or vars the application does not declare is a type error.
  • 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.
  • An extension may call onError(). The last handler set wins, so set the application’s own after extend().
  • Use mount() instead when the feature is a router of its own under a prefix.

The packages follow these, and they make an extension safe to share:

  • Validate options once, in the factory, and throw there. A bad setting should stop start-up, not fail requests.
  • Keep nothing request-scoped at module level. Pass values through c.set() and c.get().
  • Ask for a port, the methods you call, and never a vendor’s type.
  • Guard every callback you accept: one that throws must not change the response. A callback that decides access fails closed, as if it had said no.
  • Bound anything you read or hold: bytes, items, keys or time.
  • Use only the router’s public exports, and add no dependency an application would not want bundled.