A fast HTTP router for Deno, internally using a highly performant Radix Tree (aka compact Prefix Tree). It supports route parameters, wildcards, and constraint-based routing.
Acknowledgements & Credits
deno-routeris a native Deno port of the legendary find-my-way Node.js router by Tomas Della Vedova. It retains the ultra-fast routing engine and Radix tree structure of the original project, while upgrading the API to strictly type-safe, modern Web StandardRequestandResponseobjects suitable for the Deno and Fetch ecosystems.
You can import deno-router locally or directly from your preferred Deno registry:
import Router from "./mod.ts";The core API is designed around Deno's native Request and Response paradigm. Handler functions take a Context object, which encapsulates the original Request alongside any extracted URL params.
import Router from "./mod.ts";
const router = new Router();
// Register a basic literal route
router.on('GET', '/', (ctx) => {
return new Response('{"message":"hello world"}', {
headers: { "content-type": "application/json" }
});
});
// Register a parametric route
router.on('GET', '/users/:id', (ctx) => {
const userId = ctx.params.id;
return new Response(`Hello user ${userId}`);
});
// Start a Deno server
Deno.serve(async (req) => {
return await router.lookup(req);
});- Static Routes:
/example - Parametric Routes:
/example/:userId - Wildcards:
/example/* - Multi-Parametric:
/example/near/:lat-:lng/radius/:r - Regex Parameters:
/example/:file(^\\d+).png
Nodes are matched in the following order to ensure expected determinism:
- Static
- Parametric node with static ending
- Parametric (regex) / Multi-parametric
- Parametric
- Wildcard
For improved developer experience, you can use the lower-cased HTTP methods instead of router.on():
router.get('/path', handler);
router.post('/path', handler);
router.put('/path', handler);
router.delete('/path', handler);
// Also supports patch, head, options, etc.deno-router supports restricting handlers to only match certain constraints (like headers, hosts, or versions).
import versionStrategy from "./lib/strategies/accept-version.ts";
const myRouter = new Router({
constraints: {
"version": {
...versionStrategy,
deriveConstraint: (req: Request) => req.headers.get("accept-version") || ""
}
}
});
// Handlers are selectively matched based on the constraint!
myRouter.on('GET', '/', { constraints: { version: '1.2.0' }}, (ctx) => {
return new Response("Action from v1.2.0");
});
myRouter.on('GET', '/', { constraints: { version: '2.0.0' }}, (ctx) => {
return new Response("Action from v2.0.0");
});Because deno-router maintains the exact same tree structure as find-my-way, it averages over 1 million route lookups per second (sub-microsecond resolution). Run the included benchmark suite to test your setup:
deno task benchfind-my-way - MIT
deno-router - MIT
Original constraints and optimization logic Copyright © 2017-2023 Tomas Della Vedova