Defining default routes and 404 pages

Loading

In web development, handling default routes and 404 pages is crucial for ensuring smooth navigation and enhancing user experience. Default routes define what content appears when a user accesses a base URL or an undefined route. A 404 page is a response for non-existent routes, helping users understand that they have reached an invalid URL.

This guide will walk you through the step-by-step process of defining default routes and 404 pages in different web frameworks, including React, Express.js, and ASP.NET.


Step 1: Understanding Routing and Default Routes

What are Routes?

Routes determine how URLs map to different components or pages in a web application. Each route corresponds to a specific page or response.

What is a Default Route?

A default route is a fallback page loaded when no specific route is defined or when a user visits the root URL (“/”) of the application.

For example:

  • In a single-page application (SPA), navigating to / might show the homepage.
  • In a server-side app, a request to / could return the main landing page.

What is a 404 Page?

A 404 page appears when a user enters an invalid URL that doesn’t match any predefined route. This page usually displays a “Page Not Found” message and provides navigation options.


Step 2: Implementing Default Routes and 404 Pages in React

React uses React Router for handling routes. Here’s how you can set up default routes and 404 pages in React.

1. Install React Router

If not already installed, install React Router using:

npm install react-router-dom

2. Define Routes in App.js

Modify App.js to include default and 404 routes.

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";
import NotFound from "./NotFound";

function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} /> {/* Default Route */}
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} /> {/* 404 Route */}
</Routes>
</Router>
);
}

export default App;

3. Create NotFound.js

The 404 page component (NotFound.js):

import React from "react";
import { Link } from "react-router-dom";

function NotFound() {
return (
<div>
<h2>404 - Page Not Found</h2>
<p>Oops! The page you are looking for does not exist.</p>
<Link to="/">Go Back to Home</Link>
</div>
);
}

export default NotFound;

Step 3: Implementing Default Routes and 404 Pages in Express.js

Express.js is a backend framework for handling server-side routes.

1. Install Express

Run the following command to install Express:

npm install express

2. Create an Express Server (server.js)

Define default and 404 routes in Express:

const express = require("express");
const app = express();

// Default Route
app.get("/", (req, res) => {
res.send("Welcome to the Home Page!");
});

// Other Routes
app.get("/about", (req, res) => {
res.send("This is the About Page.");
});

// 404 Page
app.use((req, res) => {
res.status(404).send("404 - Page Not Found");
});

// Start Server
app.listen(3000, () => {
console.log("Server running on port 3000");
});

3. Explanation

  • The default route / returns the home page.
  • Any request to /about returns the About page.
  • If a user enters an undefined route, app.use() catches it and sends a 404 response.

Step 4: Implementing Default Routes and 404 Pages in ASP.NET Core

ASP.NET Core uses routing middleware for handling requests.

1. Define Routes in Startup.cs

Modify the Configure method in Startup.cs:

app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Welcome to Home Page!");
});

endpoints.MapGet("/about", async context =>
{
await context.Response.WriteAsync("This is the About Page.");
});

endpoints.MapFallback(async context =>
{
context.Response.StatusCode = 404;
await context.Response.WriteAsync("404 - Page Not Found");
});
});

2. Explanation

  • MapGet("/") handles requests to the home page.
  • MapGet("/about") defines an About page.
  • MapFallback() captures all other routes and returns a 404 response.

Step 5: Enhancing the 404 Page for Better User Experience

A well-designed 404 page improves user experience. Here are some best practices:

1. Provide Navigation Options

Add a “Go Back Home” button or a search bar to help users navigate.

Example (HTML-based 404 page):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 - Not Found</title>
</head>
<body>
<h2>Oops! Page Not Found</h2>
<p>The page you are looking for doesn't exist.</p>
<a href="/">Return to Home</a>
</body>
</html>

2. Use Friendly Language

Instead of just “404 – Page Not Found”, try:

“Oops! We can’t seem to find the page you’re looking for. Let’s get you back on track!”

3. Track 404 Errors

Use analytics to log 404 errors and improve navigation.

Example (Express.js logging 404 routes):

app.use((req, res, next) => {
console.log(`404 Error: ${req.originalUrl}`);
res.status(404).send("404 - Page Not Found");
});

Step 6: Testing Your Default and 404 Pages

After implementation, test the routing setup:

1. Test in the Browser

  • Visit / → Should load the home page.
  • Visit /about → Should load the about page.
  • Visit /random → Should load the 404 page.

2. Use cURL (for API-based Routes)

Run the following in a terminal:

curl -i http://localhost:3000/nonexistent

It should return 404 - Page Not Found.

Leave a Reply

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