Middlewares in Express.js
Middleware is one of the key concepts for creating HTTP servers in Express.js. By definition, middleware is a function that runs before any route handler. Middleware functions take three parameters:
req - the request object.
res - the response object.
next - a function that passes control to the next middleware in the chain.
Middleware can be helpful for tasks like input validation and authentication. Below are some examples of how middleware works and how to write it.
Example Use Case: Count the number of requests to the server.
1st way: Using Function as Middleware
const express = require('express')
const app = express()
let reqCount = 0; // global variable
function requestCounter(req, res, next) {
reqCount+=1;
console.log(`Number of request: ${reqCount}`)
next() // Move to the next middleware or route handler
}
app.get('/', requestCounter, (req, res) => {
res.send('Hello, world!');
})
app.listen(3000);
Note: The next function provided by the Express, must be called once all the logic within the middleware is completed. Failing to call
next()
will prevent the request from reaching the target route.
2nd Way: Using app.use() for Middleware
const express = require('express')
const app = express()
let reqCount = 0;
app.use('/', function(req, res, next) {
reqCount+=1;
console.log(`Number of request: ${reqCount}`)
next()
})
app.get('/', (req, res) => {
res.send('Hello, world!');
})
app.listen(3000);
In this example, every request to '/'
triggers the middleware function first. Once next()
is called, the request moves to the route handler (app.get('/')
in this case), which sends the response.
You can pass multiple middleware functions to
app.get()
before the final route handler.
Subscribe to my newsletter
Read articles from Ayush Khemani directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by