Search code examples
denooak

Deno - how to implement a 404 page


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.


Solution

  • 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