Role-Based Route Protection

Demonstrate how to create a middleware function to protect specific routes based on user roles, redirecting unauthorized users.
const express = require('express');
const app = express();

// Middleware to check if the user has the required role
function roleMiddleware(requiredRole) {
  return function(req, res, next) {
    // Assume user's role is stored in req.user.role
    if (req.user && req.user.role === requiredRole) {
    } else {
      // Redirect or send an error if user doesn't have the required role
      res.status(403).send('Access denied');

// Protecting a specific route with the role 'admin'
app.get('/admin', roleMiddleware('admin'), (req, res) => {
  res.send('Welcome to the admin page!');

// Server setup (assuming running on port 3000)
app.listen(3000, () => console.log('Server running on port 3000'));
This code creates an Express server and a middleware function called roleMiddleware which accepts a requiredRole parameter. The middleware checks whether the requesting user has that required role and if not, it sends a 403 status with a message 'Access denied'. The middleware is used to protect the '/admin' route, allowing access only to users with the role 'admin'.