Consider this Express middleware that checks user permissions before allowing access to a route.
function checkPermission(permission) {
return (req, res, next) => {
if (req.user?.permissions?.includes(permission)) {
next();
} else {
res.status(403).send('Forbidden');
}
};
}
app.get('/admin', checkPermission('admin'), (req, res) => {
res.send('Welcome Admin');
});What will the server respond if a user without the 'admin' permission tries to access '/admin'?
Look at the middleware logic and what happens when the permission is missing.
The middleware checks if the user has the required permission. If not, it sends a 403 Forbidden response. So users without 'admin' permission get blocked.
You want to create middleware that allows access if the user has any of the given permissions.
Which option correctly implements this?
Use an array method that returns true if at least one element matches.
some() returns true if any permission matches. every() requires all permissions, which is not what we want here.
Look at this middleware code:
function checkPermission(permission) {
return (req, res, next) => {
if (req.user.permissions.includes(permission)) {
next();
} else {
res.status(403).send('Forbidden');
}
};
}Sometimes the server crashes with TypeError: Cannot read property 'includes' of undefined. Why?
Think about what happens if the user is not logged in.
If req.user or req.user.permissions is undefined, calling includes causes a TypeError. The middleware should check these exist first.
Consider this middleware:
function checkPermission(permission) {
return (req, res, next) => {
if (req.user?.permissions?.includes(permission)) {
next();
next();
} else {
res.status(403).send('Forbidden');
}
};
}What happens when a user with the permission accesses the route?
Calling next() more than once in Express middleware is problematic.
Express throws an error if next() is called multiple times in the same middleware chain because it confuses the request flow.
You want to create permission middleware but user permissions are loaded asynchronously from a database.
Which approach correctly handles this in Express?
Express supports async middleware functions that return promises.
Making middleware async and awaiting permission loading ensures the check completes before continuing. Other options cause race conditions or bad design.