pathbits
v1.0.0
Published
URL path matching, query helpers, and a tiny middleware router for Node.js
Maintainers
Readme
pathbits
URL path tools for Node.js: compile patterns with params and wildcards, build paths, parse query strings, and run a small middleware-style router.
Zero runtime dependencies. Node 18+.
Install
npm install pathbitsQuick start
import { match, build, createRouter, parseQuery } from "pathbits";
match("/users/:id", "/users/42");
// { path: "/users/42", params: { id: "42" }, pattern: "/users/:id" }
build("/posts/:slug", { slug: "hello-world" });
// "/posts/hello-world"
parseQuery("a=1&b=2&b=3");
// { a: "1", b: ["2", "3"] }
const router = createRouter();
router.get("/users/:id", async (ctx) => {
ctx.state.userId = ctx.params.id;
});
await router.handle({ method: "GET", url: "/users/7?x=1" });Pattern syntax
| Pattern | Matches |
| --- | --- |
| /users/:id | /users/42 |
| /files/:id(\\d+) | digits only |
| /assets/* | one segment |
| /docs/** | rest of path |
| /optional/:id? | optional param |
Router
const api = createRouter({ prefix: "/api" });
api.use(async (ctx, next) => {
ctx.state.started = Date.now();
await next();
});
api.get("/health", async (ctx) => { ctx.state.ok = true; });
api.post("/items", async (ctx) => { /* ... */ });Routes are ranked by specificity (static segments beat params beat wildcards).
License
MIT
