From 49092ed83a6c3380058518d2b6211b200d916579 Mon Sep 17 00:00:00 2001 From: Steven Yung Date: Tue, 9 Aug 2022 21:23:17 +0200 Subject: [PATCH] feat: add `ctx.renderNotFound()` to explicitly render 404 template (#481) Co-authored-by: Luca Casonato --- docs/concepts/error-pages.md | 36 +++++++++++++++++++++++++++++++ src/server/context.ts | 7 ++++-- src/server/types.ts | 1 + tests/fixture/fresh.gen.ts | 18 +++++++++------- tests/fixture/routes/not_found.ts | 7 ++++++ tests/main_test.ts | 11 ++++++++++ 6 files changed, 70 insertions(+), 10 deletions(-) create mode 100644 tests/fixture/routes/not_found.ts diff --git a/docs/concepts/error-pages.md b/docs/concepts/error-pages.md index 1719a2ca..6ae9cea0 100644 --- a/docs/concepts/error-pages.md +++ b/docs/concepts/error-pages.md @@ -8,6 +8,8 @@ Fresh supports customizing the `404 Not Found`, and the matching route exists, and when a middleware, route handler, or page component throws an error respectively. +### 404: Not Found + The 404 page can be customized by creating a `_404.tsx` file in the `routes/` folder. The file must have a default export that is a regular Preact component. A props object of type `UnknownPageProps` is passed in as an argument. @@ -22,6 +24,40 @@ export default function NotFoundPage({ url }: UnknownPageProps) { } ``` +#### Manually render 404 pages + +The `_404.tsx` file will be invoked automatically when no route matches the URL. +In some cases, one needs to manually trigger the rendering of the 404 page, for +example when the route did match, but the requested resource does not exist. +This can be achieved with `ctx.renderNotFound`. + +```tsx +/** @jsx h */ +import { h } from "preact"; +import { Handlers, PageProps } from "$fresh/server.ts"; + +export handler: Handlers = { + async GET(req, ctx) { + const blogpost = await fetchBlogpost(ctx.params.slug) + if (!blogpost) { + return ctx.renderNotFound(); + } + return ctx.render({ blogpost }) + } +} + +export default function BlogpostPage({ data }) { + return ( +
+

{data.blogpost.title}

+ {/* rest of your page */} +
+ ); +} +``` + +### 500: Internal Server Error + The 500 page can be customized by creating a `_500.tsx` file in the `routes/` folder. The file must have a default export that is a regular Preact component. A props object of type `ErrorPageProps` is passed in as an argument. diff --git a/src/server/context.ts b/src/server/context.ts index 3828938e..8b3f8255 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -448,6 +448,8 @@ export class ServerContext { }; }; + const createUnknownRender = genRender(this.#notFound, Status.NotFound); + for (const route of this.#routes) { const createRender = genRender(route, Status.OK); if (typeof route.handler === "function") { @@ -456,6 +458,7 @@ export class ServerContext { ...ctx, params, render: createRender(req, params), + renderNotFound: createUnknownRender(req, {}), }); } else { for (const [method, handler] of Object.entries(route.handler)) { @@ -464,12 +467,12 @@ export class ServerContext { ...ctx, params, render: createRender(req, params), + renderNotFound: createUnknownRender(req, {}), }); } } } - const unknownHandlerRender = genRender(this.#notFound, Status.NotFound); const unknownHandler: router.Handler = ( req, ctx, @@ -478,7 +481,7 @@ export class ServerContext { req, { ...ctx, - render: unknownHandlerRender(req, {}), + render: createUnknownRender(req, {}), }, ); diff --git a/src/server/types.ts b/src/server/types.ts index 6e85858d..60904e54 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -65,6 +65,7 @@ export interface HandlerContext> extends ConnInfo { params: Record; render: (data?: Data) => Response | Promise; + renderNotFound: () => Response | Promise; state: State; } diff --git a/tests/fixture/fresh.gen.ts b/tests/fixture/fresh.gen.ts index 959c4829..2d240425 100644 --- a/tests/fixture/fresh.gen.ts +++ b/tests/fixture/fresh.gen.ts @@ -24,10 +24,11 @@ import * as $18 from "./routes/layeredMdw/layer2/index.ts"; import * as $19 from "./routes/layeredMdw/layer2/layer3/[id].ts"; import * as $20 from "./routes/layeredMdw/layer2/layer3/_middleware.ts"; import * as $21 from "./routes/middleware_root.ts"; -import * as $22 from "./routes/params.tsx"; -import * as $23 from "./routes/props/[id].tsx"; -import * as $24 from "./routes/static.tsx"; -import * as $25 from "./routes/wildcard.tsx"; +import * as $22 from "./routes/not_found.ts"; +import * as $23 from "./routes/params.tsx"; +import * as $24 from "./routes/props/[id].tsx"; +import * as $25 from "./routes/static.tsx"; +import * as $26 from "./routes/wildcard.tsx"; import * as $$0 from "./islands/Counter.tsx"; import * as $$1 from "./islands/Test.tsx"; import * as $$2 from "./islands/kebab-case-counter-test.tsx"; @@ -56,10 +57,11 @@ const manifest = { "./routes/layeredMdw/layer2/layer3/[id].ts": $19, "./routes/layeredMdw/layer2/layer3/_middleware.ts": $20, "./routes/middleware_root.ts": $21, - "./routes/params.tsx": $22, - "./routes/props/[id].tsx": $23, - "./routes/static.tsx": $24, - "./routes/wildcard.tsx": $25, + "./routes/not_found.ts": $22, + "./routes/params.tsx": $23, + "./routes/props/[id].tsx": $24, + "./routes/static.tsx": $25, + "./routes/wildcard.tsx": $26, }, islands: { "./islands/Counter.tsx": $$0, diff --git a/tests/fixture/routes/not_found.ts b/tests/fixture/routes/not_found.ts new file mode 100644 index 00000000..1732de1e --- /dev/null +++ b/tests/fixture/routes/not_found.ts @@ -0,0 +1,7 @@ +import { Handlers } from "../../../server.ts"; + +export const handler: Handlers = { + GET(_req, ctx) { + return ctx.renderNotFound(); + }, +}; diff --git a/tests/main_test.ts b/tests/main_test.ts index 3b77146c..bac99a77 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -392,3 +392,14 @@ Deno.test({ assertEquals(resp.headers.get("server"), "fresh test server"); }, }); + +Deno.test({ + name: "/not_found", + fn: async () => { + const resp = await router(new Request("https://fresh.deno.dev/not_found")); + assert(resp); + assertEquals(resp.status, 404); + const body = await resp.text(); + assertStringIncludes(body, "404 not found: /not_found"); + }, +});