In this article, we will learn how to build middleware in Node JS. Node.js (Node) is a platform for executing JavaScript code server-side, which is ideal for developing applications that require a persistent connection between the browser and the server and is commonly used in real-time applications like chats, news feeds, and push notifications.
Node JS middleware functions provide all the access for requesting, responding to, and moving to the next middleware function in the request-response cycle of an application. Node JS also supports different helper functions for data processing. Simply understand, middleware is something that is present in between the request and response cycle which perform a certain task on the basis of which the next step is determined. Middleware can perform the following tasks:
- Changing the request and response objects
- Executing the code
- Calling the next middleware in the stack
- Ending the request-response cycle
Prerequisites
Creating Middleware In Node JS
Project Setup
Open the terminal and create a new directory named node-middleware
and switch to that directory using the following command.
mkdir node-middleware
cd node-middleware
Inside the node-middleware
directory, let’s initialize a node project using npm init
command.
After initializing a pacakge.json file will be generated like the image provided below.
Now, let’s install an express js package which will be used for routing purposes using which we can the system.
npm install express
Now let’s create a web server named index.js
in the root directory of our project.
const express = require('express')
const app = express();
app.get('/hello', (req, res) => {
res.json({
"message": "Hello world",
"status": true
})
})
app.listen(3000, function () {
console.log('App listening on port 3000!');
});
The above code will initialize the express framework and set up the server at port 3000. In the above code, when a user hits the route localhost:3000/hello
it will return aHello World
message as a response.
Creating Middleware
Now, let’s create a simple middleware that will verify whether the user can access the above route or not using the authorization token provided in the header.
Create a file name auth.js
in the folder named middleware
in the root of the above-created directory. In this file, we will check whether a token is available in the header or not, and according to the further task will be carried out.
const authorize = (req, res, next) => {
const authorization = req.headers["authorization"];
if (!authorization) {
// Return error if no authorization header is present
return res.status(401).json({
message: "Operation Failed",
data: "Authorization token not found.",
});
}
return next();
};
module.exports = {
authorize
}
The above code checks whether the request header has authorization or not. If the authorization value is not found it returns the error message to the user and if the authorization is available it executes the next code inside the /hello
route function.
Now. let’s include the middleware on our web server page so that we can add the middleware to the route to prevent unauthorized access to the route. The final code will look like following
const express = require('express')
const { authorize } = require("./middleware/auth");
const app = express();
app.get('/hello', authorize, (req, res) => {
res.json({
"message": "Hello world",
"status": true
})
})
app.listen(3000, function () {
console.log('App listening on port 3000!');
});
Here, we have included the authorized middleware in the /hello
route. Now, if a user tries to access the route without an authorization token in the header, it will return the following error.
{
"message": "Operation Failed",
"data": "Authorization token not found."
}
And the following response will be provided to the user if they try to access the above URL with authorization in the header.
{
"message": "Hello world",
"status": true
}
Conclusion
In this article, you have learned some basic things about node js middleware and how to implement middleware in node js. You can follow this link to learn more about Node JS.