Handling 404 pages in AngularJS applications

Loading

In AngularJS applications, managing routing and page navigation is an essential aspect of building a seamless user experience. One of the common challenges developers face is dealing with non-existent routes (i.e., URLs that do not match any of the defined routes), commonly known as “404 pages.” In this article, we will explore how to handle 404 pages in AngularJS applications, including custom error pages and proper redirection.


1. Introduction to 404 Pages in AngularJS

In a traditional multi-page application (MPA), a 404 page is displayed when the user tries to access a URL that does not exist on the server. However, in a single-page application (SPA) like those built with AngularJS, routing is handled on the client side. AngularJS manages routes using either the ngRoute module (with $routeProvider) or the UI-Router (with $stateProvider), and both provide mechanisms to handle unknown routes.

Handling a 404 page in AngularJS typically involves setting up a fallback route that displays a custom error message or redirects the user to a predefined page (e.g., the home page or a dedicated error page).


2. Handling 404 with ngRoute

If you’re using the built-in ngRoute module for routing, you can handle 404 errors by using the otherwise() method, which provides a fallback route when no other routes match the requested URL.

Example: Configuring 404 Page with ngRoute

angular.module('myApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
// Fallback route for non-existent pages
.otherwise({
templateUrl: '404.html',
controller: 'ErrorController'
});
})
.controller('HomeController', function($scope) {
$scope.message = 'Welcome to the Home Page!';
})
.controller('AboutController', function($scope) {
$scope.message = 'About us.';
})
.controller('ErrorController', function($scope) {
$scope.errorMessage = 'Page not found!';
});

In this example:

  • The .otherwise() method is used to specify the fallback route for any URL that doesn’t match /home or /about.
  • If a user navigates to a non-existent route, AngularJS will load the 404.html template and the ErrorController, displaying a message like “Page not found!”

404 Template:

<!-- 404.html -->
<div class="error-page">
<h1>Error 404: Page Not Found</h1>
<p>{{ errorMessage }}</p>
</div>

This template will show a simple 404 error message with the text “Page not found.”


3. Handling 404 with UI-Router

If you are using UI-Router, handling 404 pages can be done in a similar way. UI-Router provides a more advanced routing system, which allows for nested routes and more flexible state management.

Example: Configuring 404 Page with UI-Router

angular.module('myApp', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
// Define routes
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeController'
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'AboutController'
});

// Fallback URL when no state matches
$urlRouterProvider.otherwise('/404');

// 404 state definition
$stateProvider
.state('404', {
url: '/404',
templateUrl: '404.html',
controller: 'ErrorController'
});
})
.controller('HomeController', function($scope) {
$scope.message = 'Welcome to the Home Page!';
})
.controller('AboutController', function($scope) {
$scope.message = 'About us.';
})
.controller('ErrorController', function($scope) {
$scope.errorMessage = 'Page not found!';
});

In this example:

  • $urlRouterProvider.otherwise('/404') is used to redirect users to the /404 route whenever they try to access a non-existent route.
  • The 404 state is defined with the URL /404, and the ErrorController is used to handle the 404 error and display the relevant error message.

404 Template:

<!-- 404.html -->
<div class="error-page">
<h1>Error 404: Page Not Found</h1>
<p>{{ errorMessage }}</p>
</div>

Just like the ngRoute example, this template displays an error message when the user navigates to a non-existent route.


4. Redirecting to the Home Page on 404

Sometimes, instead of showing a 404 page, you might want to automatically redirect users to the home page or a specific route when they access a non-existent URL. This can be easily done with both ngRoute and UI-Router.

Redirecting in ngRoute:

angular.module('myApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
// Redirect non-existent routes to home
.otherwise({
redirectTo: '/home'
});
});

In this example, instead of showing a 404 page, the app will redirect users to the /home route if they access an undefined route.

Redirecting in UI-Router:

angular.module('myApp', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
// Define routes
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeController'
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'AboutController'
});

// Redirect to home if URL does not match any state
$urlRouterProvider.otherwise('/home');
});

Here, if the user navigates to a non-existent URL, they will be automatically redirected to the /home route.


5. Using Custom 404 Pages for Better UX

Custom 404 pages are essential for improving the user experience and guiding users back to the correct path. You can make your 404 pages interactive, display helpful links, or even provide a search function to help users find what they’re looking for.

Example: Custom 404 Page with Links

<!-- 404.html -->
<div class="error-page">
<h1>Oops! The page you're looking for doesn't exist.</h1>
<p>It looks like you've hit a broken link or a wrong URL.</p>
<p>Click below to go back:</p>
<ul>
<li><a href="#/home">Home Page</a></li>
<li><a href="#/about">About Us</a></li>
<li><a href="#/contact">Contact Us</a></li>
</ul>
</div>

This custom 404 page gives users clear options to navigate to valid pages and avoid confusion.

Leave a Reply

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