Facebook Pixel

How do I do role-based access in Express?

Add a second middleware after auth that checks req.user.role. If not allowed, return 403. Apply with router.use('/admin', auth, requireAdmin). Stack middlewares for layered auth.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Express Route Protection With Middlewares

Write an auth middleware that verifies the JWT and sets req.user. Apply it to single routes, to a router (router.use(auth)), or in app.js. Keep public routes outside the auth middleware.

Read from req.cookies.token or req.headers.authorization (Bearer token). Verify with jwt.verify(token, process.env.JWT_SECRET). If valid, set req.user and call next; if not, return 401.

In the handler, load the resource and compare its owner to req.user.id. If they do not match, return 403. Do this for any user-specific resource like /posts/:id.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.