From a078182735fe94509da14ff4fd554ad5ec6e4239 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Thu, 20 Jul 2023 14:37:13 +0200 Subject: [PATCH] docs: return Responses from async routes (#1493) --- docs/concepts/routes.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/concepts/routes.md b/docs/concepts/routes.md index f0487b39..7b394ef7 100644 --- a/docs/concepts/routes.md +++ b/docs/concepts/routes.md @@ -142,3 +142,32 @@ export default async function MyPage(req: Request, ctx: RouteContext) { return

foo is: {value}

; } ``` + +### Returning Response objects + +Quite often a route handler needs to render a 404 page or bail out of rendering +in another manner. This can be done by returning a `Response` object. + +```tsx +// Async route component +export default async function MyPage(req: Request, ctx: RouteContext) { + const value = await loadFooValue(); + + // Return 404 if `value` is null + if (value === null) { + return ctx.renderNotFound(); + } + + // Returning a response object directly works too + if (value === "redirect") { + const headers = new Headers(); + headers.set("location", "/some-other-page"); + return new Response(null, { + status: 302, + headers, + }); + } + + return

foo is: {value}

; +} +```