The Problem
If you’ve built a decent-sized NestJS application, you know the authorization dance. You start with basic Roles, then suddenly you need fine-grained permissions, then maybe some attribute-based access control (ABAC).
Before you know it, your controllers are cluttered with @UseGuards(RolesGuard), and your RolesGuard itself is a massive switch statement checking for every possible permission string. It's repetitive, hard to test, and honestly, a bit boring to maintain.
The Solution: nestjs-permissions
I got tired of reinventing this logic for every project, so I built nestjs-permissions. The goal was simple: Declarative, type-safe authorization that stays out of your way while keeping your code clean.
Why use it?
- Decorator-Driven: No more complex metadata injection. Just wrap your routes.
- Type-Safe: Keep your permissions consistent across your frontend and backend.
- Framework-Native: It plays nicely with the standard NestJS Request lifecycle.
Quick Start
Getting started takes about 5 minutes.
1. Install it:
npm install nestjs-permissions
2. Configure your module:
import { Module } from '@nestjs/common';
import { PermissionsModule } from 'nestjs-permissions';
@Module({
imports: [
PermissionsModule.register({
// Your config here
})
],
})
export class AppModule {}
3. Protect your routes:
import { Get, Controller } from '@nestjs/common';
import { RequirePermissions } from 'nestjs-permissions';
@Controller('dashboard')
export class DashboardController {
@Get('admin')
@RequirePermissions('admin.read')
async getDashboard() {
return 'Secret Admin Data';
}
}
What’s Under the Hood?
Under the hood, nestjs-permissions leverages the NestJS Reflector to cleanly extract metadata from your route handlers. It automatically taps into the execution context, checking the incoming request against the required permissions without forcing you to write boilerplate guards for every module.
When NOT to use it
If you need hyper-complex, attribute-based access control (like checking if User A owns Document B before allowing a read), you might want to look into something heavier like CASL.
However, if you are building a Role-Based Access Control (RBAC) or Claim-based system, nestjs-permissions will save you hours of boilerplate.
Give it a try!
I’m actively looking for feedback. If you have a NestJS project coming up, give it a spin and let me know what you think. PRs are welcome, and bugs are—hopefully—rare!
Check it out here:
🔗 NPM Package
🔗 GitHub Repository
Let me know in the comments how you handle authorization in your NestJS apps!
Top comments (0)