Request Handling & Routing | RedwoodSDK
RedwoodSDK

Request Handling & Routing

Like air traffic control, but for requests.


The request/response paradigm is at the heart of web development - when a browser makes a request, your server needs to respond with content. RedwoodSDK makes this easy with the defineApp function, which lets you elegantly handle incoming requests and return the right responses.

src/worker.tsx
import { defineApp } from "rwsdk/worker";
import { route } from "rwsdk/router";
import { env } from "cloudflare:workers";

export default defineApp([
  // Middleware
  function middleware({ request, ctx }) {
    /* Modify context */
  },
  function middleware({ request, ctx }) {
    /* Modify context */
  },
  // Request Handlers
  route("/", function handler({ request, ctx }) {
    return new Response("Hello, world!");
  }),
  route("/ping", function handler({ request, ctx }) {
    return new Response("Pong!");
  }),
  route("/api/users", {
    get: () => new Response(JSON.stringify(users)),
    post: () => new Response("Created", { status: 201 }),
  }),
]);

The defineApp function takes an array of middleware and route handlers that are executed in the order they are defined. In this example the request is passed through two middleware functions before being "matched" by the route handlers.


Matching Patterns

Routes are matched in the order they are defined. You define routes using the route function. Trailing slashes are optional and normalized internally.

src/worker.tsx
import { route } from "rwsdk/router";

defineApp([route("/match-this", () => new Response("Hello, world!"))]); 

route parameters:

  1. The matching pattern string
  2. The request handler function

There are three matching patterns:

Static

Match exact pathnames.

route("/", ...)
route("/about", ...)
route("/contact", ...)

Parameter

Match dynamic segments marked with a colon (:). The values are available in the route handler via params (params.id and params.groupId).

route("/users/:id", ...)
route("/users/:id/edit", ...)
route("/users/:id/addToGroup/:groupId", ...)

Wildcard

Match all remaining segments after the prefix, the values are available in the route handler via params.$0, params.$1, etc.

route("/files/*", ...)
route("/files/*/preview", ...)
route("/files/*/download/*", ...)

Query Parameters

RedwoodSDK uses the standard Web Request object. To access query parameters, you can use the standard URL API:

route("/search", ({ request }) => {
  const url = new URL(request.url);
  const