Middleware
A function that is invoked by the Express routing layer before the final request handler, and thus sits in the middle between a raw request and the final intended route. A few fine points of terminology around middleware:
var foo = require('middleware')is called requiring or using a Node.js module. Then the statementvar mw = foo()typically returns the middleware.app.use(mw)is called adding the middleware to the global processing stack.app.get('/foo', mw, function (req, res) { ... })is called adding the middleware to the “GET /foo” processing stack.
They are special functions that run in-between the request coming in and the response coming out of the API.

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
Example
To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).
const express = require('express')
const app = express()
const myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
const sayHello = (req, res, next) => {
req.hello = 'Hello World';
next();
};
app.get('/', sayHello, (req, res) => {
res.send(req.hello);
})
app.get('/user', (req, res) => {
return res.json({});
})
app.listen(3000)
Every time the app receives a request, it prints the message “LOGGED” to the terminal.
Notice the call above to next(). Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The next() function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
If myLogger is loaded after the route to the root path, the request never reaches it and the app doesn’t print “LOGGED”, because the route handler of the root path terminates the request-response cycle.
The middleware function myLogger simply prints a message, then passes on the request to the next middleware function in the stack by calling the next() function.