Middleware in Express
Deepak Panghal
MERN Stack developer | DSA | C++ | LeetCode | DUCS'26 MSC CS | Delhi University
Middleware are used in middle of request and response cycle
For making our website and web apps scalable and maintainable we can use middleware
Middleware empowers developers to add functionality, enhance security, and streamline the request-response cycle
What are middleware
Middleware, in the context of Express.js, is a bridge that connects the request and response objects. It intercepts incoming HTTP requests, performs specific actions, and can modify both the request and response objects. Essentially, middleware functions are invoked sequentially in the order they are defined, offering a powerful mechanism to control the flow of requests through an application.
We can use middleware in different aspects like route specific validation and authentication , serving static files, parsing JSON , handling URL-encoded data
Below is an example of practical use cases of middleware
we can use multiple middleware in between our request and response cycle and all the middleware we use in our app is called middleware stack , also the order of middleware in stack is same as they are defined in code (so middleware that appear first in code is executed first then the one that appear later in code)
We can use next() function which is available in all middleware to execute the code in next middleware
领英推荐
We can create our own middleware using use() function of express
use function takes a function as argument which will be added to middleware stack and that function will have access to request , response and next function as it's arguments
const express = require('express')
const app = express()
app.use((req,res,next) => {
// your middleware code here
// use next function at end to execute next middleware of middleware // stack
next()
})
we can also call other 3rd party middleware inside the use() function to gain functionality provided by 3rd party middleware
let's see example by using a 3rd party middleware morgan
first install it using npm
npm i morgan
then we can use it inside our app
// we can use 3rd party middleware to make our development easier
const morgan = require('morgan')
app.use(morgan('dev'))
You can read more about middlewares and their features on express official website Here