Is it possible to show a 404 page for not found routes in nestjs?

Viewed 4797

Am using nestjs to handle all the apis. I want to show a 404 page if a route is not found.

2 Answers

You can define a custom global ExceptionFilter that catches a NotFoundException exception and then handle the error accordingly:

@Catch(NotFoundException)
export class NotFoundExceptionFilter implements ExceptionFilter {
    catch(exception: NotFoundException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse();
        response.sendFile('./path/to/your/404-page.html');
    }
}

You can set this exception filter as global as follows:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);    
  // ...
  app.useGlobalFilters(new NotFoundExceptionFilter());

  await app.listen(3000);
}
bootstrap();

The right solution is to use ExceptionFilter as pointed out by @eol but to allow dependency injection you should register them on a module, instead of using useGlobalFilters (as pointed out in the docs):

@Catch(NotFoundException)
export class NotFoundExceptionFilter implements ExceptionFilter {
  catch(_exception: NotFoundException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.sendFile('./path/to/your/404-page.html');
  }
}

app.module.ts

import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: NotFoundExceptionFilter,
    },
  ],
})
export class AppModule {}

This will also register them globally.

Related