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
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
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.
Examples
Express
function adminMiddleware(req, res, next) {
if (req.user && req.user.role === 'admin') {
next();
} else {
res.status(403).send('Access denied');
}
}Express
function userMiddleware(req, res, next) {
if (req.user) {
next();
} else {
res.status(401).send('Please log in');
}
}Sample Program
This example shows two routes: one for admins and one for users. Middleware checks the user's role before allowing access.
Express
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'); });
Important Notes
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.
Summary
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
1. What is the main purpose of using middleware for admin vs user route protection in Express?
easy
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]
Hint: Middleware checks roles to protect routes [OK]
Common Mistakes:
- Thinking middleware speeds up server
- Confusing middleware with logging only
- Believing middleware changes URLs
2. Which of the following is the correct way to apply middleware for admin route protection in Express?
easy
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]
Hint: Middleware goes between path and handler in route [OK]
Common Mistakes:
- Calling middleware inside handler instead of passing it
- Using middleware after sending response
- Passing middleware as a function call instead of reference
3. Given this middleware and route code, what will be the response if a user with role 'user' tries to access '/admin'?
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');
});medium
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]
Hint: Check role condition in middleware to predict response [OK]
Common Mistakes:
- Assuming next() always runs
- Ignoring status code sent by middleware
- Thinking response is 'Welcome Admin' for all roles
4. Identify the error in this Express route protection code:
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');
});medium
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]
Hint: Always send status code with error messages [OK]
Common Mistakes:
- Not setting status code on error
- Calling next() after sending response
- Placing middleware after route handler
5. You want to protect two routes: '/admin' for admins only and '/profile' for logged-in users. Which Express setup correctly applies middleware for this scenario?
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?hard
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]
Hint: Check middleware order: auth before admin [OK]
Common Mistakes:
- Reversing middleware order
- Using adminMiddleware alone for profile
- Not protecting admin route with authMiddleware
