How to understand a NestJS codebase
NestJS structures a Node backend into modules that declare controllers and providers, wired together by dependency injection. Cross-cutting behaviour is attached with decorators, so a lot of what happens to a request isn't visible in the handler itself.
How to tell it's NestJS
@nestjs/coreinpackage.jsonand anest-cli.json- Decorators such as
@Module,@Controller,@Injectable,@Get src/main.tscallingNestFactory.create(AppModule)
Where things usually live
- src/main.ts
- Bootstraps the app: global pipes, filters, prefixes, CORS.
- src/app.module.ts
- Root module importing feature modules.
- src/<feature>/<feature>.module.ts
- Declares a feature's controllers, providers, imports and exports.
- src/<feature>/<feature>.controller.ts
- HTTP routes as decorated methods.
- src/<feature>/<feature>.service.ts
- Business logic, injected into controllers.
- src/common/
- Shared guards, interceptors, pipes, filters and decorators.
- src/<feature>/dto/
- Request and response shapes, often validated with class-validator.
Conventions, not rules. Real projects rename and move things, so confirm against the repository.
Where to start reading
main.ts, for global configurationapp.module.ts, for the module graph- The controller for the endpoint, then the services it injects
How a request moves through the code
- Middleware runs first (configured in a module's
configuremethod). - Guards decide whether the request may continue, typically for auth and roles.
- Interceptors run their before-logic.
- Pipes transform and validate parameters such as DTOs.
- The controller method runs and calls injected services.
- Interceptors run their after-logic on the result; exception filters turn thrown errors into responses.
Questions to ask about the repository
- Which guards protect this controller, and what do they check?
- Draw the module graph and which providers each module exports.
- Which global pipes, interceptors and filters are registered in
main.ts? - Where does this service get its database connection?
What trips people up
- Decorators can be applied globally, per controller or per method, so check all three before concluding a guard isn't there.
- A provider must be exported by its module and that module imported where it's used; injection errors usually mean one is missing.
- Circular module imports are resolved with
forwardRef, which makes the dependency graph harder to read.