We protect routes to keep some parts of a website safe. Admin routes are for special users who manage the site. User routes are for regular users.
Admin vs user route protection in Express
app.get('/admin', adminMiddleware, (req, res) => { res.send('Admin page'); }); app.get('/user', userMiddleware, (req, res) => { res.send('User page'); });
Middleware functions like adminMiddleware check if the user has the right role before allowing access.
If the check fails, middleware usually sends a '403 Forbidden' or redirects to login.
function adminMiddleware(req, res, next) {
if (req.user && req.user.role === 'admin') {
next();
} else {
res.status(403).send('Access denied');
}
}function userMiddleware(req, res, next) {
if (req.user) {
next();
} else {
res.status(401).send('Please log in');
}
}This example shows two routes: one for admins and one for users. Middleware checks the user's role before allowing access.
import express from 'express'; const app = express(); // Fake user data for demo app.use((req, res, next) => { // Simulate logged in user req.user = { id: 1, role: 'admin' }; next(); }); function adminMiddleware(req, res, next) { if (req.user && req.user.role === 'admin') { next(); } else { res.status(403).send('Access denied'); } } function userMiddleware(req, res, next) { if (req.user) { next(); } else { res.status(401).send('Please log in'); } } app.get('/admin', adminMiddleware, (req, res) => { res.send('Welcome Admin!'); }); app.get('/user', userMiddleware, (req, res) => { res.send('Welcome User!'); }); // Start server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always check user roles in middleware to keep routes safe.
Protect routes early to avoid running unnecessary code.
Use clear messages like 'Access denied' to inform users why they can't enter.
Route protection keeps parts of your app safe for the right users.
Middleware checks user roles before allowing access.
Admin routes are stricter than user routes.
Practice
Solution
Step 1: Understand middleware role
Middleware runs before route handlers and can check conditions like user roles.Step 2: Role-based access control
Middleware can allow access only if the user has the right role, such as admin or user.Final Answer:
To check user roles and allow or deny access accordingly -> Option AQuick Check:
Middleware controls access = D [OK]
- Thinking middleware speeds up server
- Confusing middleware with logging only
- Believing middleware changes URLs
Solution
Step 1: Understand middleware placement
Middleware should be passed as a second argument before the route handler function.Step 2: Check syntax correctness
app.get('/admin', adminMiddleware, (req, res) => { res.send('Admin page'); }); correctly places adminMiddleware between route path and handler.Final Answer:
app.get('/admin', adminMiddleware, (req, res) => { res.send('Admin page'); }); -> Option BQuick Check:
Middleware before handler = A [OK]
- Calling middleware inside handler instead of passing it
- Using middleware after sending response
- Passing middleware as a function call instead of reference
function adminMiddleware(req, res, next) {
if (req.user.role === 'admin') next();
else res.status(403).send('Access denied');
}
app.get('/admin', adminMiddleware, (req, res) => {
res.send('Welcome Admin');
});Solution
Step 1: Analyze middleware condition
The middleware checks if req.user.role is 'admin'. If not, it sends 403 with 'Access denied'.Step 2: User role is 'user'
Since role is 'user', the else branch runs, sending 403 and 'Access denied'.Final Answer:
'Access denied' with status 403 -> Option AQuick Check:
Non-admin blocked with 403 = A [OK]
- Assuming next() always runs
- Ignoring status code sent by middleware
- Thinking response is 'Welcome Admin' for all roles
function adminMiddleware(req, res, next) {
if (req.user.role === 'admin') next();
else res.send('Access denied');
}
app.get('/admin', adminMiddleware, (req, res) => {
res.send('Admin area');
});Solution
Step 1: Check middleware response
When denying access, middleware sends a message but does not set HTTP status code.Step 2: Importance of status code
Without status 403, client gets status 200 which is misleading for access denial.Final Answer:
Missing status code when sending 'Access denied' -> Option CQuick Check:
Send 403 on denial = C [OK]
- Not setting status code on error
- Calling next() after sending response
- Placing middleware after route handler
function authMiddleware(req, res, next) {
if (req.user) next();
else res.status(401).send('Login required');
}
function adminMiddleware(req, res, next) {
if (req.user?.role === 'admin') next();
else res.status(403).send('Admin only');
}
// Which setup is correct?Solution
Step 1: Understand middleware order
For '/admin', user must be logged in (authMiddleware) and have admin role (adminMiddleware).Step 2: Apply correct middleware per route
'/profile' only needs authMiddleware to check login. app.get('/admin', authMiddleware, adminMiddleware, (req, res) => res.send('Admin')); app.get('/profile', authMiddleware, (req, res) => res.send('Profile')); applies both correctly in order.Final Answer:
app.get('/admin', authMiddleware, adminMiddleware, (req, res) => res.send('Admin')); app.get('/profile', authMiddleware, (req, res) => res.send('Profile')); -> Option DQuick Check:
Auth then admin for admin route = B [OK]
- Reversing middleware order
- Using adminMiddleware alone for profile
- Not protecting admin route with authMiddleware
Ready to prove it?
Pass the test and this pattern moves unknown
