Uut Budiarto Mascot
Build Nestjs RBAC Using PostgreSQL Database

Build Nestjs RBAC Using PostgreSQL Database

Role-Based Access Control or RBAC is essential for securing modern backend applications. RBAC allows developers to manage user permissions efficiently using predefined roles.

Why Use RBAC?

RBAC improves security by limiting user access based on roles. For example, administrators may access all resources while regular users only access specific endpoints.

Step 1 Create NestJS Project

Create a new NestJS application using the Nest CLI.

npm i -g @nestjs/cli
nest new backend-api

This generates the initial backend structure.

Step 2 Install PostgreSQL And Prisma

Install Prisma ORM and PostgreSQL dependencies.

npm install prisma --save-dev
npm install @prisma/client

Initialize Prisma configuration.

npx prisma init

Step 3 Create Database Models

Create relational models for users, roles, and permissions.

model User {
  id    String @id @default(uuid())
  email String @unique
  roles Role[]
}

model Role {
  id          String       @id @default(uuid())
  name        String
  permissions Permission[]
}

This schema creates scalable authorization relationships.

Step 4 Generate Prisma Migration

npx prisma migrate dev --name init

This command generates PostgreSQL database tables automatically.

Step 5 Create JWT Authentication

Install JWT packages for authentication.

npm install @nestjs/jwt passport-jwt

JWT tokens help identify authenticated users securely.

Step 6 Create RBAC Guard

Create authorization guards to protect routes.

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    return true;
  }
}

Guards validate user permissions before accessing APIs.

Step 7 Use Custom Roles Decorator

export const Roles = (...roles: string[]) =>
  SetMetadata('roles', roles);

This decorator simplifies permission management inside controllers.

Step 8 Protect API Routes

@Roles('ADMIN')
@Get('users')
findAllUsers() {
  return [];
}

Only users with ADMIN roles can access protected endpoints.

Best Practices

Always validate permissions at the backend level. Never trust frontend authorization logic alone. Use audit logs and secure token management for enterprise systems.

Conclusion

NestJS and PostgreSQL provide an excellent foundation for scalable RBAC systems. Combined with Prisma and JWT authentication, developers can build secure enterprise-ready backend architectures efficiently.

Similar Post

History Behind Modern Golang Programming Language
Development

History Behind Modern Golang Programming Language

Explore the complete history of Golang, Google’s powerful programming language designed for scalability, simplicity, concurrency, backend performance, cloud computing, and modern software development used by companies worldwide today.