Friend’s here; we will try to understand how the Middleware works in the Nodejs. We will try to implement here own Middleware after that we will use Expressjs. Firstly we will try to understand what does Middleware means. After that, we will try to achieve our Middleware.
What is Middleware in the Nodejs?
Whenever we type any URL into our browser(client)
address bar. We are requesting information from the webserver where we want to do anything such as fetching any information. The server gets our request based on the requesting information. It interprets and prepares the response as per the request. It may have text, images any possible value.
When the webserver receives the request from the user in the form of data, the Nodejs gives you a request object. There will be the information on the browser, IP address, languages, and much more information in that object. Users can pass parameters also with that. After processing the request, NodeJs give back the response. These requests and responses are shortened to req and res.
Middleware functions are the best place to modify or update the req and res. For example, we are fetching the details of the user from the database. While fetching the data middleware will authenticate the user after authentication only webserver responds the exact data or the error that 401 (unauthorized access).
In a nutshell, we can say that. Middleware will give you access to the req and res. The next middleware function is a variable named next.
In short we can say that following for the Middleware:-
- As the names suggest, it comes in the middle of the request and response cycle.
- Middleware has access to re and res and req.
- Middleware has access to next for the request and response cycle.

Middleware can do following tasks:
- Middleware execute the code
- Middleware make changes to request and response
- It can end the response cycle
- Middleware can execute the call that in the stack
These are the basic definitions of the Middleware in the NodejS. In the next section, we will learn what does next() do in the Middleware.
What is next() in the middleware?
Middleware is, in a nutshell, a function that will have access to the response cycle. In middleware, we can do many things, such as waiting for asynchronous databases or any network to proceed to the next step. We can take this example, and users are trying to edit the user information. In the middleware, we can check the authentication after properly authenticated we can check the authorization also. So in the middleware, we can do multiple things.

In the above image, we can see the there we have taken an example in which we are updating the admin password. In that when the user will call the API to the web server, we will encrypt the data.
In the first phase, we will check that the login user is authenticated. If authentication fails, the web server will send a 401 error to the user.
After authentication, we will check the user is authorized to make the changes. If the user is authorized, the user will make changes, and the response cycle will complete. If the user is not authorized, the webserver will send a 401 error to the user.
Now we will see the types of middleware:
- Application-level middleware which generally uses app.use()
- Router level middleware which generally uses router.use()
- Built-in middleware like express
- The middleware which handled the error
- There are some third ware middleware are there like cookieParser, bodyparser etc
We will see examples for all the above middleware
- Application-level middleware
In the application level, we will take an example we have an eCommerce site there we have routes like:
checkOutProduct, getOrderDetails, isAdmin
Here all these API calls we do after the user is login into the system.
For that, we create a middleware in which before accessing the routes, it will check that the user is login or not.
const express = require('express');
// custom middleware create
const LoggerMiddleware = (req,res,next) =>{
console.log(`Logged ${req.url} ${req.method} -- ${new Date()}`)
next();
// it will trigger next response if user is login it will return the data
// otherwise return 401
}
const app = express()
// application level middleware
app.use(LoggerMiddleware);
// get user orders route
app.get('/getUserOrders',(req,res)=>{
res.json({
'status':true
})
})
//checkout product POST METHOD
app.post('/checkOutProduct',(req,res)=>{
res.json({
'status':true
})
})
// is admin
app.post('/isAdmin',(req,res)=>{
res.json({
'status':true
})
})
app.listen(3002,(req,res)=>{
console.log('server running on port 3002')
})
2. Router level middleware
In router level middleware, the same concept is there like application. In the application level, the middleware is at the application level in the route level middleware. It will protect a specific URL or route.
For example, there is one route in which the user wants to see all the transaction details.
But this is very confidential data, and only super admin has access to see the details. So there we need the router level. It will restrict unwanted access to the route.
const express = require('express');
const app = express();
const router = express.Router()
// route level middleware
router.use((req, res, next) => {
next()
})
router.get("/user/paymentDetails/:userId", (req, res, next) => {
next()
}, (req, res, next) => {
next()
}, (req, res) => {
res.json({
status: true,
id: req.params.id
})
})
app.use('/', router)
app.listen(3000, (req, res) => {
console.log('server running on 3000')
})
3. Third-party Middlewares
There are many third-party middlewares that we can install that module and use their functionality in our application. It will increase the speed of development. We can handle it at any level, like the application or the route level. For example bodyparser, cookieparser.
For installing the body parser run this command
npm install body-parser
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended:false})) // middleware
app.use(bodyParser.json())
app.post('/userDetail',(req,res)=>{
res.json({
"status":true,
"payload":req.body
})
})
var server = app.listen(3000, function() {
console.log('Listenint Port : 3000 ');
});
4. Middleware which handled the error
ExpressJS comes with default error handling params, which will act like middleware function in the same way as in application level and route level. For error handling, it comes with four parameters. For example
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something Went wrong please check!')
})
Conclusion
I have tried my best to discuss and describe the middleware concept. In a nutshell, we can say that when the user requests anything on browser or API request is generated with the user input. When the call reaches the webserver, it evaluates it that it’s coming from the right sources or not before sending back the final response. It will do all the needful operation. The operation will take place; that part is middleware. After evaluating all the possibilities, it will acknowledge the proper response to the user. I hope you have all liked the Article. Please give your valuable comment.