What if a tiny missed role check lets anyone see secret data?
Why Role-based access control in Express? - Purpose & Use Cases
Imagine building a website where some pages should only be seen by admins, others by regular users, and some by guests. You try to check user roles manually in every route handler.
Manually checking roles everywhere leads to repeated code, mistakes, and security holes. It's easy to forget a check or mix up permissions, risking unauthorized access.
Role-based access control (RBAC) lets you define roles and permissions once, then automatically enforce them across your app. This keeps your code clean and secure.
app.get('/admin', (req, res) => { if (req.user.role === 'admin') { res.send('Welcome admin'); } else { res.status(403).send('Forbidden'); } });
const checkRole = role => (req, res, next) => {
if (req.user.role === role) next();
else res.status(403).send('Forbidden');
};
app.get('/admin', checkRole('admin'), (req, res) => {
res.send('Welcome admin');
});RBAC makes it easy to manage who can do what, improving security and saving time as your app grows.
Think of a company intranet where only HR can see employee salaries, managers can approve requests, and everyone else has limited access.
Manual role checks are repetitive and risky.
RBAC centralizes permission logic for safety and clarity.
It scales well as your app and team grow.