Skip to content
Related Articles

Related Articles

Improve Article
Setting a Default route in Express.js
  • Difficulty Level : Hard
  • Last Updated : 30 Nov, 2020

What is a default route?

As we know that in an express application, there are so many URLs and requests involved. It might be possible that the user hit a route which is not included in our express app. In that case, the user will get an error for handling these kinds of issues, we set a default route to our express app that informs the user that, he has hit a wrong route or redirect the user to a specific route.

The below is an example error page when a user hits a wrong route:

Follow these precautions while defining your default route:

  • There will be only one default route in your web app.
  • The default route will be defined after all other routes for the app are defined i.e. at the end.

Steps to set the default route in the express app:

Step 1: Create your project folder.



Step 2: Now in your terminal, run the following command from the root of your project folder:

 $ npm init

Step 3: Install express using the following command:

 $ npm install express

Step 4: Require ‘express’ and set your all general routes as per the requirements of your application.

Step 5: Below all routes, set your default route as shown below:

app.get("*", function (req, res) {
    res.render("Error_page");   
});

Example: An example of an express app with a default route given below.

Filename: index.js

Javascript




// Requiring modules
const express = require("express");
const app = express();
  
// Root route of express app
app.get("/", (req, res) => {
  res.send("Hello Geeks");
});
  
app.get("/new", (req, res) => {
  res.send("welcome to new page");
});
  
// All the general routes of your
// web app are defined above the
// default route
  
// Default route
app.get("*", (req, res) => {
  
  // Here user can also design an
  // error page and render it 
  res.send("PAGE NOT FOUND");
});
  
// Server setup
app.listen(3001, () => {
  console.log(
`Server listening on http://localhost:3001`);
});

Run the index.js file using the following command:

node index.js

Output:

Server listening on http://localhost:3001

Now open your browser and navigate to http://localhost:3001, you will see the following message on screen:

Hello Geeks

Now hit any different URL other than our defined URL’s, like here we have hit http://localhost:3001/xyz. Following will be the output on your screen:

PAGE NOT FOUND
My Personal Notes arrow_drop_up
Recommended Articles
Page :