0
0
Expressframework~30 mins

Admin vs user route protection in Express - Hands-On Comparison

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use app.get('/dashboard', (req, res) => { res.send('User Dashboard'); }).