Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
Express multiple roles middleware

I want to have 2 access roles: admin and superadmin.

Superadmin can create, read, update and delete posts. Admin can read, update posts.

I have the middlewares already:

const verifyAdminStatus = (req, res, next) => {
  //pseudocode: if (user === 'admin') next();
}

const verifySuperAdminStatus = (req, res, next) => {
  //pseudocode: if (user === 'superadmin') next();
}

For create and delete it works fine:

router.post("/api/posts", [verifyToken, verifySuperAdminStatus], createPost); 
router.delete("/api/posts/:id", [verifyToken, verifySuperAdminStatus], deletePost); 

But for update and read, I can't put both middlewares, because either one of them will not have the access. How can I implement a solution where both admins and superadmins can update and read. Do I need to create a new middleware that checks both?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you can use a factory of middleware to have only one middleware that manages the different cases as follow:

const authMiddleware = (roles) => {
   return (req,res,next) => {
      roles.forEach(role => {
        if(["admin", "superadmin"].includes(role)) return next();
      })
      return res.status(403).json({
        message: "Forbidden"
      })
   }
   
}

router.post("/api/posts", [verifyToken, authMiddleware(["Admin"])], createPost); 
router.delete("/api/posts/:id", [verifyToken, authMiddleware(["SuperAdmin"]], deletePost); 
router.delete("/api/posts/another-endpoint", [verifyToken, authMiddleware(["SuperAdmin", "Admin"]], deletePost); 

The last endpoint can be consumed for an Admin or Super Admin role.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!