To create a Express.js middleware that accepts parameters with JavaScript, we return a function that takes the arguments we want.
For instance, we write
const hasRole = (role) => {
return (req, res, next) => {
if (role !== req.user.role) {
res.redirect("...");
} else {
next();
}
};
};
const middlwareHasRoleAdmin = hasRole("admin");
app.get("/hasToBeAdmin", middlwareHasRoleAdmin, (req, res) => {});
to define the hasRole
function.
It returns a middleware function that checks the role
and either redirects with res.redirect
or move to the next middleware with next
.
Then we call hasRole
with 'admin'
to return a middleware with role
set to 'admin'
.
And we use the middlwareHasRoleAdmin
middleware in our /hasToBeAdmin route.