Today I first learnt to use Express middleware.
Express.js provides a sound documentation here.

Middleware functions

Middleware functions are functions that take 3 arguments: the request object, the response object, and the next function in the application’s request-response cycle.

These functions execute some code that can have side effects on the app, and usually add information to the request or response objects.

They can also end the cycle by sending a response when some condition is met.

If they don’t send the response when they are done, they start the execution of the next function in the stack. This triggers calling the 3rd argument, next().

Bind application-level middleware

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

Loading multiple middleware functions

1
2
3
4
5
6
7
app.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('Request Type:', req.method)
next()
})