Overview 🔎
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 can perform 💎
• Execute any code.
• Make changes to the request and the response objects.
• End the request-response cycle.
• Call the next middleware in the stack.
🔸🔹🔸🔹
Configurable middleware 📥
If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
in my-middleware.js
module.exports = function(options) {
return function(req, res, next) {
// Implement the middleware function
next();
}
}🔸🔹🔸🔹
Usage Middleware 📤
The middleware can now be used as shown below.
const mddleware = require('./my-middleware.js')
app.use(mddleware({ option1: '1', option2: '2' }))https://t.me/pgimg/77
〰〰〰〰〰〰
#JavaScript #Express #Middleware
@ProgrammingTip