0
0
Expressframework~5 mins

Role-based access control in Express

Choose your learning style9 modes available
Introduction

Role-based access control helps decide who can do what in your app. It keeps things safe by letting only the right people access certain parts.

When you want only admins to change settings.
When users should see only their own data.
When different user roles have different permissions.
When you want to protect sensitive routes in your app.
Syntax
Express
function checkRole(role) {
  return function(req, res, next) {
    if (req.user && req.user.role === role) {
      next();
    } else {
      res.status(403).send('Access denied');
    }
  };
}
This is a middleware function that checks the user's role before allowing access.
Use next() to continue if the role matches, otherwise send a 403 error.
Examples
This route is only for users with the 'admin' role.
Express
app.get('/admin', checkRole('admin'), (req, res) => {
  res.send('Welcome Admin');
});
This route is only for users with the 'user' role.
Express
app.get('/user', checkRole('user'), (req, res) => {
  res.send('Welcome User');
});
Sample Program

This example shows a simple Express app with role-based access control. It pretends the user is logged in as an admin. The '/admin' route lets the admin in, but the '/user' route denies access because the role doesn't match.

Express
import express from 'express';

const app = express();

// Simulate logged-in user
app.use((req, res, next) => {
  req.user = { name: 'Alice', role: 'admin' };
  next();
});

function checkRole(role) {
  return (req, res, next) => {
    if (req.user && req.user.role === role) {
      next();
    } else {
      res.status(403).send('Access denied');
    }
  };
}

app.get('/admin', checkRole('admin'), (req, res) => {
  res.send('Welcome Admin');
});

app.get('/user', checkRole('user'), (req, res) => {
  res.send('Welcome User');
});

// Start server
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always check the user's role after they are authenticated.

Use middleware to keep your code clean and reusable.

Return a 403 status code to clearly show access is forbidden.

Summary

Role-based access control limits what users can do based on their role.

Use middleware functions in Express to check roles before routes run.

Keep your app safe by protecting sensitive routes with role checks.