sdk/router
RedwoodSDK’s router is a lightweight server-side router that’s designed to work with defineApp from rwsdk/worker.
The route function is used to define a route.
import { route } from "rwsdk/router";
route("/", () => new Response("Hello, World!"));Method-Based Routing
Section titled “Method-Based Routing”The route function also accepts a MethodHandlers object to handle different HTTP methods on the same path:
route("/api/users", { get: () => new Response(JSON.stringify(users)), post: () => new Response("Created", { status: 201 }), delete: () => new Response("Deleted", { status: 204 }),});Method handlers can also be arrays of functions for route-specific middleware:
route("/api/users", { get: [isAuthenticated, getUsersHandler], post: [isAuthenticated, validateUser, createUserHandler],});Type signature:
type MethodHandlers = { delete?: RouteHandler; get?: RouteHandler; head?: RouteHandler; patch?: RouteHandler; post?: RouteHandler; put?: RouteHandler; config?: { disable405?: true; disableOptions?: true; }; custom?: { [method: string]: RouteHandler; };};Custom methods: For non-standard HTTP methods (e.g., WebDAV):
route("/api/search", { custom: { report: () => new Response("Report data"), },});Default behavior:
- OPTIONS requests return
204 No ContentwithAllowheader - Unsupported methods return
405 Method Not AllowedwithAllowheader - Use
config.disableOptionsorconfig.disable405to opt out
Important Notes
Section titled “Important Notes”HEAD Requests: Unlike Express.js, RedwoodSDK does not automatically map HEAD requests to GET handlers. You must explicitly define a HEAD handler if you want to support HEAD requests.
route("/api/users", { get: getHandler, head: getHandler, // Explicitly provide HEAD handler});prefix
Section titled “prefix”The prefix function is used to modify the matched string of a group of routes, by adding a prefix to the matched string. This essentially allows you to group related functionality into a seperate file, import those routes and place it into your defineApp function.
import { route } from "rwsdk/router";
import { LoginPage } from "./LoginPage";
export const routes = [ route("/login", LoginPage), route("/logout", () => { /* handle logout*/ }),];import { prefix } from "rwsdk/router";
import { routes as userRoutes } from "@/app/pages/user/routes";
defineApp([prefix("/user", userRoutes)]);This will match /user/login and /user/logout
render
Section titled “render”The render function is used to statically render the contents of a JSX element. It cannot contain any dynamic content. Use this to control the output of your HTML.
Options
Section titled “Options”The render function accepts an optional third parameter with the following options:
-
rscPayload(boolean, default:true) - Toggle the RSC payload that’s appended to the Document. Disabling this will mean that interactivity can no longer work. Your document should not include any client side initialization. -
ssr(boolean, default:true) - Enable or disable server-side rendering beyond the ‘use client’ boundary on these routes. When disabled, ‘use client’ components will render only on the client. This is useful for client components which only work in a browser environment. NOTE: disablingssrrequiresrscPayloadto be enabled.
import { render } from "rwsdk/router";
import { ReactDocument } from "@/app/Document";import { StaticDocument } from "@/app/Document";
import { routes as appRoutes } from "@/app/pages/app/routes";import { routes as docsRoutes } from "@/app/pages/docs/routes";import { routes as spaRoutes } from "@/app/pages/spa/routes";
export default defineApp([ // Default: SSR enabled with RSC payload render(ReactDocument, [prefix("/app", appRoutes)]),
// Static rendering: SSR enabled, RSC payload disabled render(StaticDocument, [prefix("/docs", docsRoutes)], { rscPayload: false }),
// Client-side only: SSR disabled, RSC payload enabled render(ReactDocument, [prefix("/spa", spaRoutes)], { ssr: false }),]);Error Handling
Section titled “Error Handling”Errors in route handlers and middleware are handled automatically by RedwoodSDK. The framework provides several ways to handle errors:
Using ErrorResponse
Section titled “Using ErrorResponse”The ErrorResponse class allows you to return structured errors with status codes:
import { route } from "rwsdk/router";import { ErrorResponse } from "rwsdk/worker";
route("/api/users/:id", async ({ params }) => { const user = await getUserById(params.id); if (!user) { throw new ErrorResponse(404, "User not found"); } return Response.json(user);});When an ErrorResponse is thrown, RedwoodSDK automatically converts it to an HTTP response with the specified status code and message.
Try-Catch in Route Handlers
Section titled “Try-Catch in Route Handlers”You can use try-catch blocks to handle errors in your route handlers:
import { route } from "rwsdk/router";import { ErrorResponse } from "rwsdk/worker";
route("/api/users", async ({ request }) => { try { const data = await request.json(); const user = await createUser(data); return Response.json(user, { status: 201 }); } catch (error) { if (error instanceof ErrorResponse) { throw error; // Re-throw ErrorResponse to preserve status code } // Handle other errors throw new ErrorResponse(500, "Internal server error"); }});Server-Side Rendering Errors
Section titled “Server-Side Rendering Errors”Errors that occur during React Server Component rendering are automatically caught and handled. These errors are logged and the request is rejected, which will be caught by the outer error handler in defineApp.
Global Error Handling
Section titled “Global Error Handling”You can wrap the fetch method exposed by defineApp to handle all errors globally:
import { defineApp, ErrorResponse } from "rwsdk/worker";import { route } from "rwsdk/router";
const app = defineApp([ route("/", () => <HomePage />), route("/api/users", async () => { // This might throw an error const users = await fetchUsers(); return Response.json(users); }),]);
export default { fetch: async (request: Request, env: Env, ctx: ExecutionContext) => { try { return await app.fetch(request, env, ctx); } catch (error) { // Handle all unhandled errors globally if (error instanceof ErrorResponse) { return new Response(error.message, { status: error.code }); }
if (error instanceof Response) { return error; }
// Log error to monitoring service console.error("Unhandled error:", error);
// Send to monitoring service asynchronously // Use waitUntil to prevent the worker from being killed // before the async operation completes ctx.waitUntil( sendToMonitoring(error).catch((monitoringError) => { console.error("Failed to send error to monitoring:", monitoringError); }), );
// Return a generic error response return new Response("Internal Server Error", { status: 500 }); } },};Important: When sending errors to monitoring services (Sentry, DataDog, etc.), these calls are often async. Use ctx.waitUntil() from Cloudflare’s ExecutionContext to ensure the worker doesn’t terminate before the async operation completes. Without waitUntil, the worker may be killed before the monitoring service receives the error.
This pattern allows you to:
- Catch all errors that escape route handlers and middleware
- Send errors to monitoring services (Sentry, DataDog, etc.) without blocking the response
- Return consistent error responses
- Prevent unhandled exceptions from reaching Cloudflare Workers
Unhandled Errors
Section titled “Unhandled Errors”If an error is thrown that is not an ErrorResponse or Response instance, and you haven’t wrapped the fetch method, RedwoodSDK will:
- Log the error to the console
- Re-throw the error (which will surface as an unhandled exception in Cloudflare Workers)
To prevent unhandled exceptions, you can either:
- Wrap the
fetchmethod fromdefineApp(recommended for global error handling) - Wrap potentially failing code in try-catch blocks within route handlers and either:
- Return an
ErrorResponsefor structured errors - Return a
Responsefor custom error responses - Handle the error gracefully within your route handler
- Return an