rbac-express-auth
v1.0.4
Published
Lightweight RBAC middleware for Express.js
Maintainers
Readme
rbac-express
Simple and lightweight Role-Based Access Control (RBAC) middleware for Express.js applications.
Why rbac-express-auth?
Most Express applications require role-based authorization, but implementing it repeatedly across projects leads to duplicated and error-prone code.
rbac-express-auth solves this by providing a clean, reusable authorization middleware that works seamlessly with JWT-based authentication systems.
Installation
npm install rbac-express-auth
Basic Usage
import express from "express";
import { authorize } from "rbac-express-auth";
const app = express();
// Example authenticated user
app.use((req, res, next) => {
req.user = { role: "ADMIN" };
next();
});
app.get(
"/admin",
authorize(["ADMIN"]),
(req, res) => {
res.send("Admin access granted");
}
);
How it Works
- The middleware expects
req.userto be populated (usually by an authentication middleware). - It checks whether the user's role is included in the allowed roles.
- If authorized, the request proceeds to the next handler.
- If unauthorized, a standardized error response is returned.
Error Handling
The middleware returns structured HTTP errors:
401 Unauthorized– ifreq.useris missing403 Forbidden– if the user's role is not permitted
Using with JWT Authentication
Make sure your authentication middleware sets req.user:
app.use((req, res, next) => {
// decoded JWT payload
req.user = { id: "123", role: "USER" };
next();
});
Then protect your routes
app.get("/vendor", authorize(["VENDOR"]), handler);
Best Practices
- Always run authentication middleware before
authorize() - Use constants or enums for role names
- Avoid hardcoding roles inside controllers
Links
Github Repository
https://github.com/akshaypunia0/RBAC-auth-npm-package
npm Package
https://www.npmjs.com/package/rbac-express-auth
