Express.js - middleware
In this article, we would like to show you how to create and use middleware functions in Express.js.
Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next middleware function (next
) in express.js application’s request-response cycle.
They are used to:
- execute any code,
- modify
req
andres
objects for tasks like parsing request bodies, adding response headers, authentication etc. - end the request-response cycle,
- call the next middleware function in the stack.
Note:
If the current middleware function doesn't end the request-response cycle, it must call
next()
to pass control to the next middleware function. Otherwise, the request will be left hanging.
In this example, we create a simple request tracker that prints every request date in the console and then calls the next()
function.
xxxxxxxxxx
const express = require('express');
const app = express();
app.use((req, res, next) => {
// get and print current date
const date = new Date();
console.log('A new request registered at ' + date);
// call the next middleware function in the stack
next();
});
app.listen(3000);
Now when you run the application and send any request (e.g just open http://localhost:3000/) you should get the following result in the console:
xxxxxxxxxx
A new request registered at Fri Aug 27 2021 16:41:27 GMT+0200 (Central European Summer Time)
To assign the middleware to a specific route and all its subroutes, you need to specify that route as the first argument of the app.use()
.
Example:
xxxxxxxxxx
const express = require('express');
const app = express();
// request tracker
app.use('/users', (req, res, next) => {
// get and print current date
const date = new Date();
console.log('A new request received at ' + date);
// call the next middleware function in the stack
next();
});
app.listen(3000);
Now the middleware won't work for localhost:3000/. You need to request any subroute of '/users'
, only then it will print the time.
Request:
xxxxxxxxxx
http://localhost:3000/users
Console:
xxxxxxxxxx
A new request received at Fri Aug 27 2021 16:51:11 GMT+0200 (Central European Summer Time)