Middleware in Express.js is a function that has access to the request and response objects and is used to modify or perform some action on the incoming request before it is passed on to the next function.
For example, a middleware function might validate a user’s authentication before allowing the request to be passed on to the next function.
const validateUser = (req, res, next) => {
const { username, password } = req.body;
if (username === ‘admin’ && password === ‘password’) {
next();
} else {
res.status(401).send(‘Invalid credentials’);
}
};
app.post(‘/login’, validateUser, (req, res) => {
// Handle the request
});