What is middleware
Middleware is a kind of function that can change the request
and response
object and also can finish the request and response cycle.
This article assumes that you have basic knowledge of middleware
Rights of middleware
Middleware has all rights that any route handler can have in expressjs
. Middleware can do everything which any route handler can do.
Middleware can
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
Withour wasting much time, lets queckly jump on the types of middleware
Types of middleware
There are five types of middleware
- Application-level middleware
- Router level middleware
- Error handling middleware
- Built-in middleware
- Third-party middleware
Router level and application leven middleware can be loaded with optional mount path
For the rest of the article, we'll use the following middleware for demonstration and express instance
const express = require('express');
const app = express(); // express instance
function MW(req,res,next){
console.log("I am middleware!");
next(0;
}
Application-level middleware
Application-level middleware can be registered with the express
instance directly.
If we don't use any mount path then middleware will be executed for every request.
app.use(MW);
We can use any mount path to register middleware.
// here, /path and /path/:userid are mount paths
app.use("/path",MW);
// it can also accept params
app.use("/path/:userId",MW);
We can also register more than one middleware for a single mount path at once
// insted of doing
app.use("/path",MW1);
app.use("/path",MW2);
app.use("/path",MW3);
// we can do
app.use("/path",MW1,MW2,MW3);
// we can also pass array of middleware
app.use("/path",[MW1,MW2,MW3]);
Router level middleware
Router level middleware can be defined in the same way as application-level middleware
var router = express.Router()
router.use("/path",MW1);
We can also assign middleware to any specific path.
router.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('Request Type:', req.method)
next()
})
Error-handling middleware
Error-handling middleware always takes four arguments
(err, req, res, next)
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
You must take care of the ordering of the middleware while declaring error handling middleware.
// i will be never called
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
app.get("/*",(_,res,next)=>{
try{
throw new Error("This is the error!");
}catch(e){
next(e)
}
})
Here, the above middleware will be never called because the route is declared after middleware, to make it work we need to define it after the route.
// This works fine
app.get("/*",(_,res,next)=>{
try{
throw new Error("This is the error!");
}catch(e){
next(e)
}
})
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
Built-in middleware
Built-in middleware is provided by express itself like, express.static()
etc.
Third-party middleware
Third-party middleware is provided by any third party of any NPM module, like cooki-parser
, body-parser
, etc.
Top comments (2)
Am having trouble getting a 3rd party middleware package for Nodejs (express or nest) that can handle transfer, deposited, withdraw, payment,
For example after spend time googling I got
Npm Coinpayment, this have everything I needed but this is for cryptocurrency
Glad to hear that it helped you!