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:
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;
Project Initialization
We’ll start a new Nest project by running the following command:
nest new nest-project
Then, install the necessary database dependencies, primarily typeorm and mysql2:
npm install --save @nestjs/typeorm typeorm mysql2
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 {}
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:
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;
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
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
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 {}
Run the initData service via a browser or Postman, and the data will populate the database.
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.
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!

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
