Webroute

Routing

Webroutes themselves contain much of what an app router might typically do. As such, webroutes are agnostic to how routing occurs.

Filesystem routing works out of the box without modification. Alternatively, we round off our app by using one of several provided web routers, or even plug into existing app frameworks.


Filesystem Routing

Webroute is particularly well-suited for filesystem routing contexts, like full-stack frameworks. Since each route contains everything it needs, we can simply export a route from a file, like a regular filesystem-based route handler.

posts/route.ts
export const GET = route().handle(() => {
  // Handle GET /posts
});

Note that any .path() or .method()s specified on the route itself will be ignored.

Standard Routers

Several routers are also provided for manually routing requests to our handlers. These routers are incredibly straightforward, but allow much flexibility and visibility over the routing process.

Initialising Routers

// npm i @webroute/router
import { createRadixRouter } from "@webroute/router";
// or: import { createLinearRouter } from "@webroute/router";
 
const router = createRadixRouter([
  {
    path: "/foo",
    methods: ["GET"],
    payload: myRoute, // This `payload` can be anything we like
  },
]);

To map many webroutes at once, we can make use of the Route.normalise helper.

const appRoutes = { myRoute, myOtherRoute };
 
// Create an array of { path, method, payload } for AppRoutes
const routeList = Object.values(appRoutes).map(Route.normalise);
 
const router = createRadixRouter(routeList);

Matching Requests

We can now match the incoming request to any appropriate handlers.

const app = (request: Request) => {
  const handler = router.match(request);
 
  return handler?.(request) ?? new Response("Not found", { status: 404 });
};

On this page