Backend Boilerplates
typescript
Intermediate
NestJS Guards with Roles
NestJS role-based access control using a custom guard and a roles decorator.
typescript
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(ctx: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', ctx.getHandler());
if (!roles) return true;
const { user } = ctx.switchToHttp().getRequest();
return roles.includes(user.role);
}
}
Prerequisites
- NestJS >= 10
- @nestjs/core
Pro Tips
- → Apply globally in AppModule providers.
Commercial Licensing
Acquire a production access token or template license for enterprise deployment.
Module Info
- Language
- typescript
- Level
- Intermediate
- Read time
- 4 min
- Published
- Jul 2024
- License
- Commercial License
Newsletter
New modules every week, directly to your inbox.
Similar Modules
Laravel Artisan Seeder Command
Artisan command to re-seed production data with a confirmation prompt.
php
·
Intermediate
CSV to PostgreSQL Bulk Loader
Stream a large CSV directly into PostgreSQL using COPY for maximum throughput.
python
·
Intermediate
Go Event Sourcing Store
Minimal append-only event store in Go backed by a Postgres table.
go
·
Advanced