Lightweight and fast router for JavaScript.
Install:
# ✨ Auto-detect
npx nypm install rou3
Import:
ESM (Node.js, Bun, Deno)
import {
createRouter,
addRoute,
findRoute,
removeRoute,
findAllRoutes,
routeToRegExp,
NullProtoObj,
} from "rou3";
CDN (Deno, Bun and Browsers)
import {
createRouter,
addRoute,
findRoute,
removeRoute,
findAllRoutes,
routeToRegExp,
NullProtoObj,
} from "https://esm.sh/rou3";
Create a router instance and insert routes:
import { createRouter, addRoute } from "rou3";
const router = createRouter(/* options */);
addRoute(router, "GET", "/path", { payload: "this path" });
addRoute(router, "POST", "/path/:name", { payload: "named route" });
addRoute(router, "GET", "/path/foo/**", { payload: "wildcard route" });
addRoute(router, "GET", "/path/foo/**:name", {
payload: "named wildcard route",
});
Match route to access matched data:
// Returns { payload: 'this path' }
findRoute(router, "GET", "/path");
// Returns { payload: 'named route', params: { name: 'fooval' } }
findRoute(router, "POST", "/path/fooval");
// Returns { payload: 'wildcard route' }
findRoute(router, "GET", "/path/foo/bar/baz");
// Returns undefined (no route matched for/)
findRoute(router, "GET", "/");
Important
Compiler is an experimental feature, may contain issues and the API may change between versions. See #156 for more context.
Compiles the router instance into a faster route-matching function.
IMPORTANT: compileRouter
requires eval support with new Function()
in the runtime for JIT compilation.
Example:
import { createRouter, addRoute } from "rou3";
import { compileRouter } from "rou3/compiler";
const router = createRouter();
// [add some routes]
const findRoute = compileRouter(router);
findRoute("GET", "/path/foo/bar");
Compile the router instance into a compact runnable code.
IMPORTANT: Route data must be serializable to JSON (i.e., no functions or classes) or implement the toJSON()
method to render custom code.
Example:
import { createRouter, addRoute } from "rou3";
import { compileRouterToString } from "rou3/compiler";
const router = createRouter();
// [add some routes with serializable data]
const compilerCode = compileRouterToString(router, "findRoute");
// "const findRoute=(m, p) => {}"
Published under the MIT license.
Made by @pi0 and community 💛
🤖 auto updated with automd