Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Admin vs User Route Protection in Express
📖 Scenario: You are building a simple web server using Express. The server has two types of users: admins and regular users. You want to protect certain routes so that only admins can access them, while other routes are open to all logged-in users.
🎯 Goal: Create an Express app that defines a user object with a role, sets up middleware to check if the user is an admin, and protects routes accordingly. The /admin route should only be accessible by admins, and the /dashboard route should be accessible by any logged-in user.
📋 What You'll Learn
Create a user object with a role property set to 'user' or 'admin'.
Create a middleware function called isAdmin that checks if the user role is 'admin'.
Protect the /admin route using the isAdmin middleware.
Create a /dashboard route accessible by any user.
💡 Why This Matters
🌍 Real World
Web apps often have different user roles. Protecting routes ensures only authorized users access sensitive pages.
💼 Career
Understanding route protection is key for backend developers to secure web applications and manage user permissions.
Progress0 / 4 steps
1
Create a user object with role
Create a constant called user with an object that has a role property set to the string 'user'.
Express
Hint
Use const user = { role: 'user' }; to create the user object.
2
Create isAdmin middleware
Create a function called isAdmin that takes req, res, and next as parameters. Inside, check if user.role is equal to 'admin'. If yes, call next(). Otherwise, send a 403 status with the message 'Access denied'.
Express
Hint
Check the user's role and call next() if admin, else send 403.
3
Protect /admin route with isAdmin middleware
Create an Express app by requiring express and calling it. Then create a /admin GET route that uses the isAdmin middleware. The route handler should send the text 'Welcome Admin'.
Express
Hint
Use app.get('/admin', isAdmin, (req, res) => { res.send('Welcome Admin'); }).
4
Add /dashboard route accessible by any user
Add a GET route /dashboard to the Express app that sends the text 'User Dashboard'. This route should not use any middleware.
Express
Hint
Use app.get('/dashboard', (req, res) => { res.send('User Dashboard'); }).
Practice
(1/5)
1. What is the main purpose of using middleware for admin vs user route protection in Express?
easy
A. To check user roles and allow or deny access accordingly
B. To speed up the server response time
C. To log every request made to the server
D. To change the URL of the route dynamically
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 A
Quick 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
A. app.get('/admin', (req, res) => adminMiddleware, res.send('Admin page'));
B. app.get('/admin', adminMiddleware, (req, res) => { res.send('Admin page'); });
C. app.use('/admin', (req, res) => { adminMiddleware(); res.send('Admin page'); });
D. app.get('/admin', (req, res) => { res.send('Admin page'); adminMiddleware(); });
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.
C. Missing status code when sending 'Access denied'
D. req.user.role check is incorrect syntax
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 C
Quick 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?