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.
0
0
Admin vs user route protection in Express
Introduction
When you want only admins to add or delete content.
When users should only see their own profile page.
When you want to stop guests from accessing private pages.
When you want to separate what admins and users can do.
When you want to keep sensitive data safe from regular users.
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
This middleware lets the request continue only if the user is an admin.
Express
function adminMiddleware(req, res, next) {
if (req.user && req.user.role === 'admin') {
next();
} else {
res.status(403).send('Access denied');
}
}This middleware checks if the user is logged in before allowing access.
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'); });
OutputSuccess
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.