Home Web Front-end JS Tutorial Designing RBAC Permission System with Nest.js: A Step-by-Step Guide

Designing RBAC Permission System with Nest.js: A Step-by-Step Guide

Jan 05, 2025 pm 06:48 PM

Designing RBAC Permission System with Nest.js: A Step-by-Step Guide

Preface

For backend management systems, features like access control and personalized user interfaces are essential. For instance, a super administrator can view all pages, regular users can access pages A and B, and VIP users can view pages A, B, C, and D. The logic behind these functionalities is based on the design of three key concepts:

  • User: The basic unit, such as Alice, Bob, Charlie.
  • Role: A user can have one or more roles. For example, Alice may have both the roles of a regular user and a VIP.
  • Permission: A role is associated with multiple permissions. For example, the VIP role might have permissions to view, edit, and add, while the super administrator can view, edit, add, and delete.

The relationship can be illustrated with the following diagram:

Designing RBAC Permission System with Nest.js: A Step-by-Step Guide

Next, we’ll use Nest to implement the foundation of such a system from scratch — the permission design.

Creating the Database

First, we need to create the database. We’ll use the MySQL database and execute the following command to create it:

CREATE DATABASE `nest-database` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
Copy after login
Copy after login

Project Initialization

We’ll start a new Nest project by running the following command:

nest new nest-project
Copy after login
Copy after login

Then, install the necessary database dependencies, primarily typeorm and mysql2:

npm install --save @nestjs/typeorm typeorm mysql2
Copy after login
Copy after login

Next, configure typeorm in app.module.ts:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'password',
      database: 'nest-database',
      synchronize: true,
      logging: true,
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      poolSize: 10,
      connectorPackage: 'mysql2',
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
Copy after login
Copy after login

Table Design

Typically, an RBAC (Role-Based Access Control) system will have 5 tables as follows:

  • User table (user): Stores basic user information like username, password, and email.
  • Role table (role): Stores role details like role name and role code.
  • Permission table (permission): Stores permission details like permission name and permission code.
  • User-role relation table (user_role_relation): Tracks the relationship between users and roles.
  • Role-permission relation table (role_permission_relation): Tracks the relationship between roles and permissions.

The domain model can be visualized as follows:

Designing RBAC Permission System with Nest.js: A Step-by-Step Guide

Next, we’ll create three non-relation tables in Nest and define their relationships.

user.entity.ts:

CREATE DATABASE `nest-database` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
Copy after login
Copy after login

In the User table, the roles field is defined to connect with the user_role_relation table. The relationship logic is: user.id === userRoleRelation.userId and role.id === userRoleRelation.roleId. Matching Role records are automatically linked to User.

role.entity.ts:

nest new nest-project
Copy after login
Copy after login

The permissions field in the Role table works similarly. It connects with the role_permission_relation table using the logic: role.id === rolePermissionRelation.roleId and permission.id === rolePermissionRelation.permissionId.

permission.entity.ts:

npm install --save @nestjs/typeorm typeorm mysql2
Copy after login
Copy after login

The Permission table doesn’t have relationships; it simply records available permissions.

Data Initialization

Here’s a service to initialize some test data:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'password',
      database: 'nest-database',
      synchronize: true,
      logging: true,
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      poolSize: 10,
      connectorPackage: 'mysql2',
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
Copy after login
Copy after login

Run the initData service via a browser or Postman, and the data will populate the database.

Designing RBAC Permission System with Nest.js: A Step-by-Step Guide


With the basic permission structure set up, you can now implement features like registration, login, and JWT-based authentication.

Now it's your turn!


We are Leapcell, your top choice for deploying NestJS projects to the cloud.

Designing RBAC Permission System with Nest.js: A Step-by-Step Guide

Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:

Multi-Language Support

  • Develop with JavaScript, Python, Go, or Rust.

Deploy unlimited projects for free

  • pay only for usage — no requests, no charges.

Unbeatable Cost Efficiency

  • Pay-as-you-go with no idle charges.
  • Example: $25 supports 6.94M requests at a 60ms average response time.

Streamlined Developer Experience

  • Intuitive UI for effortless setup.
  • Fully automated CI/CD pipelines and GitOps integration.
  • Real-time metrics and logging for actionable insights.

Effortless Scalability and High Performance

  • Auto-scaling to handle high concurrency with ease.
  • Zero operational overhead — just focus on building.

Explore more in the Documentation!

Follow us on X: @LeapcellHQ


Read on our blog

The above is the detailed content of Designing RBAC Permission System with Nest.js: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles