Preface
Recently I spent time learning NestJS, going from a state of "heard of it but never touched it" to being able to build a complete backend project. This article serves as a learning record, documenting my understanding, the pitfalls I encountered, and my insights into the framework. It's also a summary of this period.
My Understanding of NestJS
When I first started, the most intuitive feeling was: It's quite different from traditional Node.js frameworks.
Previously, when writing Express, it was all about "add whatever you need," which was very flexible but also easy to become messy. NestJS gave me the feeling that it sets the rules. How modules are organized, where code goes, how requests flow—there's a clear set of standards.
At first, it felt a bit restrictive, but after writing more, I realized that this constraint is actually a form of liberation. The project structure doesn't decay as the codebase grows, and when I look back at my own code, the logic is clear.
Project Structure: Modularity is Key
The first thing to understand when learning NestJS is modularity. Each feature is a module, containing controllers, services, and data entities, each with its own responsibility:
src/
├── main.ts # Application entry point
├── app.module.ts # Root module, assembling all submodules
├── user/ # User module
├── auth/ # Authentication module
├── roles/ # Roles module
├── logs/ # Logging module
├── guards/ # Custom guards
├── filters/ # Exception filters
├── interceptors/ # Interceptors
├── decorators/ # Custom decorators
├── enum/ # Constant enums
└── utils/ # Utility functions
Each module is like a small box with its own responsibilities, and they can communicate with other modules. This organization ensures that no matter how large the project grows, the structure remains predictable.
If a module needs to be reused by multiple other modules, it can be made global (@Global()) or explicitly exposed via exports. This explicit dependency declaration is much healthier than implicit global variables.
Key Takeaways
1. Dependency Injection (DI)
NestJS's dependency injection is one of the most elegant designs I've encountered. You don't need to instantiate objects yourself; just declare what you need in the constructor, and the framework injects it automatically:
With just one line, the UserService instance is available. If UserService itself depends on other things, the framework recursively resolves everything for you.
The benefit of this mechanism is: low coupling between modules and easier testing—you can easily replace dependencies with mock objects during testing.
2. Decorator-Driven Programming
NestJS makes heavy use of decorators. At first, it feels like "there are @ symbols everywhere," but once you get used to it, you realize it's one of its most convenient features.
Routing, parameter extraction, validation, authorization—all handled by decorators. A route handler's decorators from top to bottom serve as its complete "manual":
At a glance, you can see: this is a GET request, requires authentication, validates parameters, and extracts the id from the path.
Besides using built-in decorators, you can also create custom decorators to encapsulate repetitive logic. For example, I wrote a @Serialize(Dto) decorator to control which fields are returned by the API, hiding sensitive fields from the frontend with a single decorator.
3. Request Lifecycle (Complete Pipeline)
NestJS's request processing is a complete pipeline that goes through stages in order:
Middleware → Guard → Interceptor → Pipe → Controller → Service → Interceptor → Filter (on exception)
Each stage has its own role:
- Middleware: The foremost processing, can handle common logic like request logging or timing
- Guard: Determines if access is allowed; handles permission checks like login status or operation permissions
- Interceptor: Does something before entering or after leaving, such as logging, caching, or serializing response data
- Pipe: Validates incoming data; handles parameter validation and type conversion
- Filter: Determines how errors are returned; standardizes exception response format
Understanding this pipeline helps you decide where to place specific logic and quickly locate bugs.
4. Database Operations with TypeORM
For the database, I used TypeORM. The biggest takeaway: operating the database feels as natural as manipulating objects.
The most common relationships:
- One-to-One: User ↔ Profile (one user has one profile page)
- One-to-Many: User ↔ Logs (one user has multiple operation records)
- Many-to-Many: User ↔ Roles (one user can have multiple roles, and one role can have multiple users, linked via a junction table)
Basic CRUD operations use Repository methods directly. For complex queries, QueryBuilder is used, which feels similar to writing SQL but is safer (parameterized queries) and supports grouping, sorting, pagination, and other advanced operations.
5. Data Validation and Transformation
Validation: Previously, when writing APIs, parameter validation often involved messy if-else statements. NestJS, combined with class-validator, uses decorators to declare rules, making it much cleaner:
With a globally registered ValidationPipe, incoming requests are automatically validated; invalid ones return a 400 error, and the data in the Controller is guaranteed to be valid.
Transformation: Using class-transformer with interceptors, you can control the structure of API responses. For example, transforming a User entity into a UserDto, exposing only the fields needed by the frontend, and automatically filtering out sensitive fields like passwords and encryption salts. This is very practical when writing APIs.
6. Authentication and Authorization (JWT)
User authentication uses JWT (JSON Web Token). The flow is roughly:
- User logs in; the server verifies the username and password
- Upon successful verification, an encrypted token is generated and returned to the frontend
- Subsequent requests from the frontend include this token
- The server validates the token via Guards to determine the user's identity
Passwords are not stored in plain text; I used a third-party package (bcrypt) for salted hashing, so even if the database is compromised, passwords remain secure.
For authorization, I also learned about the CASL library, which allows defining fine-grained permission rules, such as "regular users can only view their own articles, while admins can delete any article," implemented with custom guards.
7. Environment Configuration Management
Using @nestjs/config with .env files for environment configuration. Different environments use different files:
.env.development # Development environment
.env.production # Production environment
.env.test # Test environment
.env # Common default configuration
Database connection info, JWT secrets, port numbers—all stored in environment variables, not hardcoded. I also used Joi for configuration validation; if required configuration items are missing at startup, the program will throw an error, preventing deployment with incorrect settings.
8. Logging System
Using nestjs-pino for logging, configured with dual output:
- Console: Colorful formatted output, clear during development
- File: Rotated daily, with size limits per file, automatically archived
Logs record each request's path, method, parameters, duration, etc., which is very helpful for troubleshooting in production.
9. Testing (Jest)
I wrote unit tests and end-to-end (e2e) tests.
Unit tests: Test Services and Controllers individually, replacing database operations with mocks, running quickly. Mainly test business logic correctness.
End-to-end tests: Simulate real HTTP requests, verifying the full chain from routing to database, ensuring overall API functionality.
Using Jest + Supertest, writing tests does take extra time, but having tests as a safety net when modifying code gives much more confidence.
10. Exception Filters
Without exception filters, each API endpoint might return errors in different formats, making frontend integration painful.
NestJS's exception filters centralize exception handling, providing a unified response format:
Whether it's parameter validation failure, database error, or business logic exception, the response format is consistent. The frontend can handle it uniformly.
Final Thoughts
NestJS is not a framework you learn just to show off. It's more of a disciplined framework that provides a complete methodology for writing backend applications. Looking back at my previous Express projects, if I had used NestJS, the structure would have been much clearer.
I learned a lot this time: modular architecture, dependency injection, TypeORM data operations, JWT authentication, data validation and transformation, logging system, unit tests and e2e tests, custom decorators and guards, exception filters, environment configuration management... Each of these is very practical in production.
A framework is just a tool, but a good tool can indeed help you write cleaner code. However, the biggest takeaway from this learning experience is not how many APIs I memorized, but understanding this architectural mindset. This way of thinking is universal for any future backend project.
(Actually, the learning process was quite tough. There aren't many good introductory NestJS courses online. The one I followed was not suitable for beginners—it was convoluted and outdated, though the instructor was highly skilled. Fortunately, I gritted my teeth and finished it, but to be honest, I may not remember all the common APIs because I haven't written enough code. However, I'm sure there will be times when I need to use NestJS, and I'll improve then.)
One step at a time is more important than anything else.
Comments
No comments yet. Say something?