Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
expressjs
communitycreator

How to chain middlewares in Express.js

Theodore Kelechukwu Onyejiaku

Middlewares in Express.Js are functions that run codes that can affect an Express.Js application, especially the requests and responses.

Middleware syntax

app.use(middleware((req, res, next)=>{
  // execute some code
}))

// OR
const METHOD = "GET" || "POST" || "PUT" || "DELETE"
app.METHOD(middleware((req, res, next)=>{
  // execute some code
}))

Arguments

Middlewares take three arguments:

  • req: the request object
  • res: the response object
  • next: 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.

Chaining middlewares

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.

Code

Using commas to separate middlewares

const middleware1 = (req, res, next)=>{
  //execute some code
  next()  // pass execution to the next middleware
}
const middleware2 = (req, res, next)=>{
  //execute some code
}

app.get("/", middleware1, middleware2);

// OR
app.get("/", function(req, res, next){
  // first middleware
  next()  //Pass execution to the next middleware
},
function(){
  // second middleware
})

Using rest for an indefinite amount of middlewares

app.get("/", ...middlewares)

Live demo

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 1
  req.middlewares = ["middleware1"];
  next()
},
function(req, res, next){
  //middleware 2
  req.middlewares.push("middleware2")
  next()
},
function(req, res, next){
  //middleware 3
  req.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. See the output here.

RELATED TAGS

javascript
expressjs
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring