Node.js Handling invalid routes
Last Updated :
04 Jun, 2024
While developing Node.Js application it is important to handle invalid routes. It can be done by writing a custom route or redirecting all the invalid routes to any custom page.
- Let’s develop an simple nodejs server for handling invalid routes:
- Step 1: Create a project folder Create a separate folder for invalid routes project.
- Step 2: Create package.json Package.json will be created by typing the following command in terminal or command prompt:
npm init -y
- Step 3: Create a javascript file on the root of the project:
- Step 4: Create a simple server using express:
-
javascript
// importing express package for creating the express server
const express = require('express');
const app = express(); // creating an express object
const port = 8000; //setting server port to 8000
// for mounting static files to express server
app.use(express.static(__dirname+'public/'));
// listening server
app.listen(port, function (err) {
if(err){
console.log("error while starting server");
}
else{
console.log("server has been started at port "+port);
}
})
- Step 5: Define routes
app.get('/', function (req, res) {
res.send("Ashish")
})
app.get('/geeksforgeeks', function (req, res) {
res.sendFile(__dirname+'/public/geeksforgeeks.html')
})
Now, we will start our server by following command in terminal or command promopt:
node server.js
If you have nodemon installed in your system then it can also be done by using the following link: To know more about nodemon and how to use it, please refer:
Thisnodemon server.js
Here, in our project till now we have developed two routes as:
- Root route(/) This route will be accessed at http://localhost:8000/

- Geeksforgeeks route(/geeksforgeeks) This route will be accessed at http://localhost:8000/geeksforgeeks

Now, let’s try to access a different random route which is not defined in the server file. As shown in the screenshot we are getting the error while trying to access /india route.

Writing the Custom route for handling all invalid routes:
We will add a route for all invalid routes as shown below:
app.get(‘*’, function(req, res){
res.sendFile(__dirname+’/public/error.html’);
}
Now, the updated server file will be as given below:
javascript
// importing express package for creating the express server
const express = require('express');
const app = express(); // creating an express object
const port = 8000; // setting server port to 8000
app.use(express.static(__dirname+'/public'));
// creating routes
app.get('/', function (req, res) {
res.send("Ashish")
})
app.get('/geeksforgeeks', function (req, res) {
res.sendFile(__dirname+'/public/geeksforgeeks.html')
})
app.get('*', function (req, res) {
res.sendFile(__dirname+'/public/error.html');
})
// listening server
app.listen(port, function (err) {
if(err){
console.log("error while starting server");
}
else{
console.log("server has been started at port "+port);
}
})
Let’s try to access the same India route for which we were getting
Cannot Get /India error
For doing it url will be :
http://localhost:8000/india
Now, if we will try to access any random invalid or wrong route we will get that error page as shown above.
- Points to remember:
- Route for invalid routing should be placed at the last of all routes because routes are called in the order in which they are written.
- If we will write this route in the starting or in the middle somewhere then all routes which are written after this route will not work and will be redirected to be handled as the invalid route.
Let’s understand this with an example: We are changing the orders of routes here
javascript
// importing express package for creating the express server
const express = require('express');
const app = express(); // creating an express object
const port = 8000; // setting server port to 8000
app.use(express.static(__dirname+'/public'));
// creating routes
app.get('*', function (req, res) {
res.sendFile(__dirname+'/public/error.html');
})
app.get('/', function (req, res) {
res.send("Ashish")
})
app.get('/geeksforgeeks', function (req, res) {
res.sendFile(__dirname+'/public/geeksforgeeks.html')
})
// listening server
app.listen(port, function (err) {
if(err){
console.log("error while starting server");
}
else{
console.log("server has been started at port "+port);
}
})
Now, we will get the invalid route response while accessing any route either it is defined or not in code because we are handling the invalid routes on the top of server.js


So, it is necessary to write the custom route at the end of the all routes so that it will not interfere with the function of any other route.
In this way, we can handle the Invalid routes access in nodejs.
Similar Reads
Handling Requests And Responses in Node.js
Node.js is a powerful JavaScript runtime for building server-side applications. It provides an efficient way to handle HTTP requests and responses using the built-in http module or frameworks like Express.js.Understanding HTTP Requests and ResponsesAn HTTP request is sent by a client (browser or API
4 min read
Exception Handling in Node.js
Exception handling refers to the mechanism by which the exceptions occurring in a code while an application is running is handled. Node.js supports several mechanisms for propagating and handling errors. There are different methods that can be used for exception handling in Node.js: Exception handl
3 min read
RESTful Routes in Node.js
Routing: Routing is one of the most significant parts of your website or web application. Routing in Express is basic, adaptable, and robust. Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed(directed) to the code that handles them. Â What is RESTful Routin
4 min read
Uses of Demultiplexer in Node.js
A demultiplexer in Node.js is a concept or tool used to route or distribute data or requests to various handlers based on certain criteria, similar to how a traditional demultiplexer works in digital circuits by taking a single input signal and routing it to one of several outputs. In the context of
4 min read
How to Handle Errors in Node.js ?
Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior
4 min read
Error Handling In NestJS
NestJS is a progressive, Node.js framework for building efficient and scalable server-side applications. One of the key advantages of NestJS is its powerful dependency injection system and modular structure, which makes building enterprise-level applications more manageable. In this article, we will
5 min read
How to build Node.js Blog API ?
In this article, we are going to create a blog API using Node.js. A Blog API is an API by which users can fetch blogs, write blogs to the server, delete blogs, and even filter blogs with various parameters.Functionalities:Fetch BlogsCreate BlogsDelete BlogsFilter BlogsApproach: In this project, we w
4 min read
Explain the concept of Domain in Node.js
Introduction: The Node.js domain module is used to catch outstanding errors. Domains provide a way to handle multiple different input-output operations as a single group. If either the event emitter or the callback is registered in the domain and when an error event or throws an error, Â the domain o
6 min read
Next JS File Conventions: route.js
In Next.js, the route.js file plays a crucial role in the App Router (introduced in Next.js 13) by defining and managing routing configurations. This file helps in customizing the behavior of routes, including rendering components, handling dynamic segments, and applying middleware.In this article,
3 min read
Next.js Dynamic Route Segments
Dynamic routing is a core feature in modern web frameworks, enabling applications to handle variable paths based on user input or dynamic content. In Next.js 13+, with the introduction of the App Router, dynamic routes are implemented using a folder-based structure inside the app directory.This arti
2 min read