DEV Community


Role-based access to API in Node.js

shadabshaikh0 profile image Shadab Majid Shaikh Updated on ・1 min read

Let's start with a simple example of a college management system.

  1. Can students modify their marks? => NO, students are not authorized only teachers can do this :(

But how this is handled in the college management system, the answer is

Role-based authorization to API

How to authorize resources according to the user role, What is your approach?

1. Simple and easy approach

Let's declare authorized roles in every endpoint and check with the user role if the user's role is present in authorized roles. Hurray! You have access.

route.get('/changemarks',(req, res) => {
    const authorizedRoles = ['teacher','admin']
    // Extract user role from req && Let's assume userRole is student
    const userRole = extractUserRole(req)
    // student is not present in authorizedRoles array 
    const isAuthorized = authorizedRoles.includes(userRole);
       // return with your customized error


  1. Simple and fast


  1. Not easily configurable

2. Middleware in every route of your project.

Don't you think the above code should be separated out as an authorization handler? Let's add authorization handler in every request as middleware.

route.get('/changemarks', authorizationHandler(['Teacher','Admin'], (req, res) => {

const authorizationHandler =  (authorizedRoles) => {
  return function(req, res, next) {
    const userRole = extractUserRole(req)
    if ( !authorizedRoles.includes(userRole) ) res.redirect(...);
    else next();


  1. Easy and only one middleware, no need to add the same code in every route.


  1. Hard-coded authorized roles in middleware's parameter ex.['Teacher','Admin']

Discussion (0)

Editor guide