Bird
Raised Fist0
Expressframework~10 mins

Admin vs user route protection in Express - Interactive Practice

Choose your learning style10 modes available

Start learning this pattern below

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a middleware that checks if a user is logged in.

Express
function isLoggedIn(req, res, next) {
  if (req.user) {
    [1]();
  } else {
    res.status(401).send('Unauthorized');
  }
}
Drag options to blanks, or click blank then click option'
Aend
Bsend
Cstatus
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to call next() causes the request to hang.
Using res.send() instead of next() inside middleware.
2fill in blank
medium

Complete the code to protect an admin route by checking the user's role.

Express
app.get('/admin', isLoggedIn, (req, res) => {
  if (req.user.role === [1]) {
    res.send('Welcome Admin');
  } else {
    res.status(403).send('Forbidden');
  }
});
Drag options to blanks, or click blank then click option'
A'admin'
B'user'
C'guest'
D'moderator'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'user' role instead of 'admin'.
Using assignment = instead of comparison ===.
3fill in blank
hard

Fix the error in the middleware to correctly check admin access.

Express
function isAdmin(req, res, next) {
  if (req.user && req.user.role [1] 'admin') {
    next();
  } else {
    res.status(403).send('Forbidden');
  }
}
Drag options to blanks, or click blank then click option'
A==
B=
C===
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using single equals = causes assignment instead of comparison.
Using loose equality == can cause unexpected behavior.
4fill in blank
hard

Fill both blanks to create a middleware that allows only admins or users accessing their own profile.

Express
function canAccessProfile(req, res, next) {
  if (req.user.role === [1] || req.user.id === [2]) {
    next();
  } else {
    res.status(403).send('Forbidden');
  }
}
Drag options to blanks, or click blank then click option'
A'admin'
Breq.params.userId
C'user'
Dreq.body.userId
Attempts:
3 left
💡 Hint
Common Mistakes
Checking req.body.userId instead of req.params.userId.
Using role 'user' instead of 'admin' for admin check.
5fill in blank
hard

Fill all three blanks to create a route that uses both middlewares for admin-only access and logs the access.

Express
app.post('/admin/data', [1], [2], (req, res) => {
  console.log('Admin access by:', [3]);
  res.send('Data updated');
});
Drag options to blanks, or click blank then click option'
AisLoggedIn
BisAdmin
Creq.user.username
DcanAccessProfile
Attempts:
3 left
💡 Hint
Common Mistakes
Using canAccessProfile instead of isAdmin for admin-only route.
Logging req.user.id instead of req.user.username.

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

  1. Step 1: Understand middleware role

    Middleware runs before route handlers and can check conditions like user roles.
  2. Step 2: Role-based access control

    Middleware can allow access only if the user has the right role, such as admin or user.
  3. Final Answer:

    To check user roles and allow or deny access accordingly -> Option A
  4. 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

  1. Step 1: Understand middleware placement

    Middleware should be passed as a second argument before the route handler function.
  2. Step 2: Check syntax correctness

    app.get('/admin', adminMiddleware, (req, res) => { res.send('Admin page'); }); correctly places adminMiddleware between route path and handler.
  3. Final Answer:

    app.get('/admin', adminMiddleware, (req, res) => { res.send('Admin page'); }); -> Option B
  4. Quick 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
A. 'Access denied' with status 403
B. 'Welcome Admin'
C. Server error due to missing next()
D. Empty response with status 200

Solution

  1. Step 1: Analyze middleware condition

    The middleware checks if req.user.role is 'admin'. If not, it sends 403 with 'Access denied'.
  2. Step 2: User role is 'user'

    Since role is 'user', the else branch runs, sending 403 and 'Access denied'.
  3. Final Answer:

    'Access denied' with status 403 -> Option A
  4. Quick 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
A. Route handler should be before middleware
B. Middleware should not call next()
C. Missing status code when sending 'Access denied'
D. req.user.role check is incorrect syntax

Solution

  1. Step 1: Check middleware response

    When denying access, middleware sends a message but does not set HTTP status code.
  2. Step 2: Importance of status code

    Without status 403, client gets status 200 which is misleading for access denial.
  3. Final Answer:

    Missing status code when sending 'Access denied' -> Option C
  4. 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?
hard
A. app.get('/admin', adminMiddleware, authMiddleware, (req, res) => res.send('Admin')); app.get('/profile', adminMiddleware, (req, res) => res.send('Profile'));
B. app.get('/admin', (req, res) => res.send('Admin')); app.get('/profile', authMiddleware, (req, res) => res.send('Profile'));
C. app.get('/admin', authMiddleware, (req, res) => res.send('Admin')); app.get('/profile', adminMiddleware, (req, res) => res.send('Profile'));
D. app.get('/admin', authMiddleware, adminMiddleware, (req, res) => res.send('Admin')); app.get('/profile', authMiddleware, (req, res) => res.send('Profile'));

Solution

  1. Step 1: Understand middleware order

    For '/admin', user must be logged in (authMiddleware) and have admin role (adminMiddleware).
  2. 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.
  3. Final Answer:

    app.get('/admin', authMiddleware, adminMiddleware, (req, res) => res.send('Admin')); app.get('/profile', authMiddleware, (req, res) => res.send('Profile')); -> Option D
  4. Quick 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