NestJS is a fantastic framework, but its flexibility can become a trap if strict rules are not followed.
In this article, we'll see how to structure a Node.js application capable of scaling from a few thousand to several million users.
The 3 Pillars
- Modularity: Each feature is an isolated module.
- Independence: The domain should not depend on the framework.
- Observability: Clear logs and distributed tracing.
1. Folder Structure
Instead of grouping by type (controllers, services), group by domain:
src/
modules/
auth/
dto/
entities/
auth.controller.ts
auth.service.ts
auth.module.ts
users/
payments/
2. Hexagonal Architecture
The idea is to separate your business core (the domain) from the infrastructure (database, external APIs).
The domain should never import anything from
@nestjs/common.
This is a golden rule to keep your code testable and sustainable.
Conclusion
A good architecture requires more effort at the start, but saves you months of maintenance later on.