Deno - how to implement a 404 page
Asked Answered
L

3

5

I have been struggling to implement a 404 page in deno(oak server framework) - if i load any addtress that does not exist, i get just a blank page..

blank page sample

tried: (page404MiddleWare.ts):

import {Context, exists, send} from "./deps.ts";
export const page404MiddleWare = async (ctx: Context, next: Function) => {
   ctx.response.body = "404 page";
   await next();
}

But that seems like a bad practise.

Lagomorph answered 13/9, 2020 at 13:39 Comment(0)
J
8

I would add a default route for all non existing urls and redirect user there:

router.get("/(.*)", async (context: Context) => {      
    context.response.status = 404;
    context.response.body = "404 | Page not Found";
});

and all rest routes:

...
...

router.get(
  "/api/users",
  UserController.fetch,
);

router.get(
  "/api/me",
  UserController.me,
);
...
...

Checkout my Deno REST boilerplate project for more details: https://github.com/vicky-gonsalves/deno_rest

Jemadar answered 14/9, 2020 at 8:39 Comment(1)
Helped me. Keep up the job whilst helping!Wadi
S
0

The question's old, but this worked for me:

    const app = new Application();
    
    // add your middlewares here
    app.use(router.routes());
    app.use(router.allowedMethods());
    
    // and then redirect to 404, if there wasn't found any route earlier
    app.use((context: Context) => {
        context.response.type = "text/html; charset=utf-8";
        context.response.status = 404;
        context.response.body = "<h1>404, Page not found!</h1>";
    });

Essentially you add a custom middleware, which returns 404 after it goes through your earlier middlewares, without returning any response. Hope it helps someone! :)

Southeastwards answered 30/8, 2022 at 11:52 Comment(0)
R
0

I've created this middleware. Use it as most first, may be after logger middleware.

    export const errorBody =
      (): Middleware =>
      async ({ request, response }, next) => {
        await next();

        const status = response.status;
        if (
          status >= 400 &&
          request.method === "GET" &&
          response.writable &&
          !response.body
        ) {
          response.type = "text/plain; charset=UTF-8";
          response.body = `HTTP ${status}`;
          response.status = status;
        }
      };

  const app = new Application();

  app.use(loggerMiddleware.logger);
  app.use(errorBody());
  app.use(loggerMiddleware.responseTime);

  app.use(router.routes());
  app.use(router.allowedMethods());



Rolanderolando answered 22/2, 2024 at 15:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.