bluehost-banner
How to setup 404 redirection page in Angular Universal for Seo

How to setup 404 redirection page in Angular Universal for Seo

In this tutorial, we are going to learn how we can set 404 pages in angular and handle not found pages.

What is 404 redirection:

The 404 redirection is a technique in which we redirect the user to another page(404 page)  when the requested page is not available on your site.

For example, let's say your application have two pages Homepage and aboutpage, now somebody comes and request for conact page,so what will happen? it might go to redirection loop.

Example:

app.routing.module.ts

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];

In the above code, we have mentioned two routes one for the home page and another for the about page.

Setting up a 404 page

With help of 404 page we can show not found page on requesting invalid page.

To help users understand they are not on the right path, we show them a not found page rather than a blank page if they attempt to navigate that invalid path.

Create Page not found componenet:

ng g c notfound

It will generate a not found component.

Now go to app.routing.module.ts file and update your routing as below:

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '**', component: NotfoundComponent }
];

Here, we've added a path **, which means it matches all of the app's invalid routes and displays a NotfoundComponent which we have just made.

Setting up 404 status code

By default Angular, a 404 page returns a soft 404 error means when there is no page found it will show a 404 page, but in the network, you will see a 200 status code, not 404.

In this case, use the below code to return actually 404 status code.

import {
  Component,
  OnInit,
  Inject,
  PLATFORM_ID,
  Optional,
} from "@angular/core";
import { REQUEST } from "@nguniversal/express-engine/tokens";
import { isPlatformServer } from "@angular/common";
import { Request } from "express";

@Component({
  selector: "not-found",
  templateUrl: "./not-found.component.html",
})
export class NotFoundComponent implements OnInit {
  constructor(
    @Inject(PLATFORM_ID) private platformId: any,
    @Optional() @Inject(REQUEST) private request: Request
  ) {}

  ngOnInit() {
    if (isPlatformServer(this.platformId)) {
      if (this.request.res) {
        this.request.res.status(404);
      }
    }
  }
}

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment