Powerful Flexible Crud And Role-based Middleware In Nestjs
Posted on Dec 3
• Originally published at make-it.run
MDX Content: # Designing a Flexible CRUD and Role-Based Middleware System in NestJS
Building CRUD endpoints is straightforward in NestJS, but making them reusable, role-aware, and easy to extend requires some upfront design. This post outlines how to structure a small framework inside your NestJS app to:
items={[ { content: ["Generate CRUD modules quickly"] }, { content: ["Attach basic middleware (logging, validation, auth)"] }, { content: ["Support role-based access control (RBAC)"] }, { content: ["Allow role–route permissions to be changed without rewriting all controllers"] } ]} />
variant="ordered" items={[ { title: "Generic CRUD layer", content: ["A base controller and service that provide create/read/update/delete operations for any entity."] }, { title: "Authorization layer (RBAC)", content: ["Roles, permissions, and guards that check if the current user can access a given route."] }, { title: "Configuration layer", content: ["A central config (or DB-driven config) defining which roles can call which CRUD operations per resource."] } ]} />
This lets you add a new module (e.g., Posts, Products) by wiring it into the generic CRUD and registering its permissions.
items={[ { title: "admin", content: ["full access to all resources"] }, { title: "manager", content: ["limited write + read"] }, { title: "user", content: ["mostly read-only, maybe create for some resources"] } ]} />
You can model roles using a TypeScript enum and then define a permission model per resource with actions like create, read, update, and delete. A RolePermissionsMap ties each role to an array of resource-specific permissions. This map can initially live in a config file and later be moved to a database for runtime configurability.
NestJS supports generic controllers and services well. The idea is to implement a BaseCrudController
A typical BaseCrudController has methods decorated with @Post, @Get, @Put, and @Delete, and accepts generic DTO types for creation and updates. The controller constructor receives a service instance and a resourceKey string that identifies the logical resource, such as 'users'
Source: Dev.to