Angular 6.x – 404 page with correct header using Angular Universal

Based on my previous post about adding a 404 page in Angular 4.x, I have added a tweak to return the correct 404 status code header. This process, however, requires the Angular Universal integration. This post assumes that you already know how to setup your Angular application with Angular Universal.

The original 404 component

Based on my previous post, here is what the 404 page component looks like:

import { Component } from '@angular/core';
  selector: 'app-notfound',
  templateUrl: './notfound.component.html'
export class NotfoundComponent { }

Adding the 404 status code

I have already upgraded to Angular 6.x since the Angular Universal integration. I have ditched my old ExpressJS server and replaced it with Angular Universal, which is still ExpressJS by the way. To be able to support both the client-side and server side (Universal), we need to know which environment we are running. Below is the full component code after my Angular Universal migration.

import { Component, OnInit, Optional } from '@angular/core';
import { PLATFORM_ID, APP_ID, Inject } from '@angular/core';
import { Title } from "@angular/platform-browser";
import { isPlatformBrowser } from '@angular/common';
import { RESPONSE } from "@nguniversal/express-engine/tokens";
import { Response } from 'express';

  selector: 'app-notfound',
  templateUrl: './notfound.component.html'

export class NotfoundComponent implements OnInit {

    @Inject(PLATFORM_ID) private platformId: Object,
    @Inject(APP_ID) private appId: string,
    @Optional() @Inject(RESPONSE) private response: Response,
    private titleService: Title
  ) {
    this.titleService.setTitle('Lysender - Page Not Found');

  ngOnInit() {
    if (!isPlatformBrowser(this.platformId)) {

We only show the status code when we are not running in the browser platform, ie: running on the server.

That’s it!

This entry was posted in Angular, Web Development and tagged , , . Bookmark the permalink.

Related Posts

One Response to Angular 6.x – 404 page with correct header using Angular Universal

  1. Pingback: Angular 4.x – Add a 404 page | Lysender's Daily Log Book

Leave a Reply

Your email address will not be published. Required fields are marked *