Blitz
The fastest JavaScript router.
import Blitz from "@bit-js/blitz";
const router = new Blitz();
router.on("GET", "/", () => new Response("Hi"));
router.on("GET", "/search/*", (ctx) => new Response(ctx.params.$));
router.on("PUT", "/update/:id", (ctx) => new Response(ctx.params.id));
router.route("/api", anotherRouter);
const fetch = router.build();
Patterns
Blitz supports URL params and wildcards. Wildcard like /*
does not match /
.
Context
The request context contains:
path
: The request pathname (Always start with a slash).pathStart
: The request pathname start index in the request URL.pathEnd
: The request pathname end index in the request URL.params
: Request URL parameters.req
: The raw request object.
Other routers
Other utility routers.
Edge router
The basic Blitz
router only works on non-edge runtimes as those block the use of the Function
constructor for code generation.
EdgeRouter
works everywhere as it matches routes using a recursive approach.
import { EdgeRouter } from "@bit-js/blitz";
const router = new EdgeRouter();
API usage is the same as Blitz
.
EdgeRouter
should be used in edge runtimes as Blitz
is around 1.5x faster and use less memory in other scenarios.
It is possible to re-use the matcher of EdgeRouter
after adding more routes, unlike Blitz
.
router.on("GET", "/", () => new Response("Hi"));
router.on("GET", "/user/:id", (ctx) => new Response(ctx.params.id));
const fetch = router.build();
router.on("GET", "/user/*", (ctx) => new Response(ctx.params.$));
fetch(req);
URL routers
These are internals router built for path matching only.
import { internal } from "@bit-js/blitz";
const router = new internal.Radix<number>();
const router = new internal.Edge<number>();
router.on("/", 0);
router.on("/:id", 1);
router.on("/*", 2);
router.route("/api", otherInternalRouter);
const f = router.buildMatcher({}, 3);
f(ctx);
The match context only has:
ctx.path
: The parsed pathname.ctx.params
: The output parameters.
FS router
A cross-runtime file system router API.
Example usage with Bun:
import { FileSystemRouter } from "@bit-js/blitz";
const glob = new Bun.Glob("**/*");
const router = new FileSystemRouter({
on: Bun.file,
scan: (dir) => glob.scanSync(dir),
style: "basic",
});
const match = router.scan(`${import.meta.dir}/internals`);
export default {
fetch(req: Request) {
return new Response(match(req).result);
},
};
Route style
Route style is a function that accepts a relative path and returns the correct route pattern.
type Style = (path: string) => string | null;
If the return result is null
the path will be ignored.
Default style
basic
: NextJS route style (wildcard only supports [...]
and wildcard parameter name is always $
).preserve
: No modifications to the path.
Result
The result is a request context with result
property is the matched result.