Middlewares in Express.Js are functions that run codes that can affect an Express.Js application, especially the requests and responses.
app.use(middleware((req, res, next)=>{// execute some code}))// ORconst METHOD = "get" || "post" || "put" || "delete"app.METHOD(middleware((req, res, next)=>{// execute some code}))
Middlewares take three arguments:
req
: the request objectres
: the response objectnext
: next
is a function that passes execution to the next middleware when it is done.Middlewares are used inside the app.use()
or app.METHOD()
functions, where METHOD
refers to the HTTP
verbs GET
, POST
, PUT
, DELETE
, and more.
Middlewares can be chained. We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app.use()
or app.METHOD()
. We use a comma (,
) to separate them.
const middleware1 = (req, res, next)=>{//execute some codenext() // pass execution to the next middleware}const middleware2 = (req, res, next)=>{//execute some code}app.get("/", middleware1, middleware2);// ORapp.get("/", function(req, res, next){// first middlewarenext() //Pass execution to the next middleware},function(){// second middleware})
rest
for an indefinite amount of middlewaresapp.get("/", ...middlewares)
Below is the code for a live demo.
var express = require('express');var app = express();const PORT = 3000;app.get("/", function(req, res, next){//middleware 1req.middlewares = ["middleware1"];next()},function(req, res, next){//middleware 2req.middlewares.push("middleware2")next()},function(req, res, next){//middleware 3req.middlewares.push("middleware3")res.json(req.middlewares);})app.listen(PORT, ()=>{console.log("app running on port "+PORT)})
After middlewares are used to modify the request object of our app, when the default route is requested, a JSON response of the modifications is returned.