How to implement role-based auth in Node.js
Role-based authentication provides granular access control in Node.js applications by assigning specific permissions to user roles for secure resource management. As the creator of CoreUI with extensive Node.js experience since 2014, I’ve implemented RBAC systems in numerous enterprise applications and admin dashboards. The most scalable approach combines JWT tokens with role information and middleware functions that verify both authentication and authorization. This pattern enables flexible permission management while maintaining clean separation between authentication and business logic.
Implement role-based middleware that checks both user authentication and role permissions for protected routes.
const jwt = require('jsonwebtoken')
// Role-based authorization middleware
function authorize(roles = []) {
return (req, res, next) => {
const token = req.headers['authorization']?.split(' ')[1]
if (!token) {
return res.status(401).json({ error: 'Access denied' })
}
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) return res.status(403).json({ error: 'Invalid token' })
if (roles.length && !roles.includes(decoded.role)) {
return res.status(403).json({ error: 'Insufficient permissions' })
}
req.user = decoded
next()
})
}
}
// Usage on routes
app.get('/admin/users', authorize(['admin']), (req, res) => {
// Admin-only route
})
app.get('/api/profile', authorize(['user', 'admin']), (req, res) => {
// User and admin access
})
This code creates a flexible authorization middleware that accepts an array of allowed roles. It verifies the JWT token and checks if the user’s role matches any of the permitted roles for the route. The middleware can be applied to any route with specific role requirements, enabling granular access control throughout your application.
Best Practice Note:
This is the authorization architecture we use in CoreUI backend services for enterprise role management. Consider implementing hierarchical roles and permission-based access control for more complex authorization scenarios in large applications.



