Minimal HTTP router library based on the
URLPattern API.
- API docs: See
@fartlabs/rton JSR →jsr.io/@fartlabs/rt
import{Router}from"@fartlabs/rt";constrouter=newRouter().get("/",()=>newResponse("Hello, World!")).default(()=>newResponse("Not found",{status: 404}));Deno.serve((request)=>router.fetch(request));Handle common HTTP verbs (GET, POST, PUT, DELETE) on resourceful routes.
import{Router}from"@fartlabs/rt";constrouter=newRouter().get("/users",()=>newResponse("List users")).post("/users",async({ request })=>{constbody=awaitrequest.json();returnResponse.json({created: true,user: body});}).put("/users/:id",async({ params, request })=>{constid=params?.pathname.groups?.id;constbody=awaitrequest.json();returnResponse.json({updated: id,user: body});}).delete("/users/:id",({ params })=>{constid=params?.pathname.groups?.id;returnnewResponse(`Deleted ${id}`,{status: 204});}).default(()=>newResponse("Not found",{status: 404}));Deno.serve((req)=>router.fetch(req));Use URLPattern named parameters and a catch‑all wildcard for flexible matching.
constrouter=newRouter()// Named params are available via URLPattern groups.get("/hello/:name",({ params })=>{constname=params?.pathname.groups?.name??"World";returnnewResponse(`Hello, ${name}!`);})// Wildcard catch-all.get("/*",()=>newResponse("Catch-all"));Access query string values via new URL(request.url).searchParams.
constrouter=newRouter().get("/search",({ request })=>{const{ searchParams }=newURL(request.url);constq=searchParams.get("q")??"";returnnewResponse(`You searched for: ${q}`);});Add middleware that enriches a shared state object and delegates with next().
interfaceState{user?: {name: string};}constrouter=newRouter<State>()// auth-like middleware that enriches state, then calls next().get("/*",async({ state, next })=>{state.user={name: "Wazoo"};returnawaitnext();}).get("/:name",({ params, state })=>{constname=params?.pathname.groups?.name;if(state.user?.name!==name){returnnewResponse("Forbidden",{status: 403});}returnnewResponse(`Hello, ${name}!`);});Provide a custom 404 response and a centralized error handler for thrown errors.
constrouter=newRouter().get("/boom",()=>{thrownewError("Kaboom");}).default(()=>newResponse("Custom 404",{status: 404})).error((err)=>newResponse(`Oops: ${err.message}`,{status: 500}));Compose routers by mounting one router's routes into another.
constapi=newRouter().get("/v1/ping",()=>newResponse("pong"));constrouter=newRouter().use(api);1. Install Deno.
2. Start a new Deno project.
deno init3. Add rt as a project dependency.
deno add jsr:@fartlabs/rtRun tests:
deno testType-check the project:
deno task checkIf you prefer composing routers in JSX, check out RTX: a library of JSX
components that build @fartlabs/rt routers.
- GitHub:
github.com/FartLabs/rtx - JSR docs:
jsr.io/@fartlabs/rtx
We appreciate your help!
Run deno fmt to format the code.
Run deno lint to lint the code.
This project is licensed under the WTFPL. See LICENSE for
details.
Developed with ❤️ @FartLabs