Consider an Express app with middleware that checks if a user is an admin before allowing access to admin routes.
What will be the response if a logged-in user without admin rights tries to access /admin/dashboard?
app.use('/admin', (req, res, next) => { if (!req.user || !req.user.isAdmin) { return res.status(403).send('Access denied'); } next(); }); app.get('/admin/dashboard', (req, res) => { res.send('Welcome to admin dashboard'); });
Think about what the middleware does when the user is not an admin.
The middleware checks if req.user exists and if req.user.isAdmin is true. If not, it sends a 403 status with 'Access denied'. So non-admin users cannot reach the admin route handler.
Choose the middleware that allows access to /user/profile only if the user is logged in, but admins can access all routes.
Admins are also users, so check if the user is logged in regardless of admin status.
Option D checks if req.user exists, allowing both normal users and admins. Option D throws a TypeError when req.user doesn't exist (accessing .isAdmin). Option D blocks admins (condition true if req.user.isAdmin). Option D redirects instead of sending 401.
Given this middleware, why does the /admin/settings route allow non-admin users?
app.use('/admin', (req, res, next) => { if (!req.user.isAdmin) { res.status(403).send('Forbidden'); return; } next(); }); app.get('/admin/settings', (req, res) => { res.send('Admin settings'); });
Think about what happens after res.status(403).send() is called.
After sending a response, the middleware still calls next(), so the request continues to the route handler, which sends a success response. The middleware should return after sending the response to stop further processing.
req.user in the admin middleware after login?Assuming a login middleware sets req.user = { id: 1, isAdmin: true }, what will req.user be inside this admin middleware?
app.use((req, res, next) => {
req.user = { id: 1, isAdmin: true };
next();
});
app.use('/admin', (req, res, next) => {
// What is req.user here?
next();
});Middleware runs in order. What does the first middleware do?
The first middleware sets req.user to the admin user object. The admin middleware runs after, so req.user is that object.
You want to protect admin routes and user routes separately in an Express app. Which design is best?
Think about code clarity and security best practices.
Separating middleware for user and admin routes keeps code clear and secure. Option B mixes concerns and can be confusing. Option B scatters checks and is error-prone. Option B is insecure.