6

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.

Daniel
  • 93
  • 7

2 Answers2

9

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

Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
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! :)

not Sam
  • 23
  • 5