Skip to content

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/core in package.json and a nest-cli.json
  • Decorators such as @Module, @Controller, @Injectable, @Get
  • src/main.ts calling NestFactory.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

  1. main.ts, for global configuration
  2. app.module.ts, for the module graph
  3. The controller for the endpoint, then the services it injects

How a request moves through the code

  1. 1Middleware runs first (configured in a module's configure method).
  2. 2Guards decide whether the request may continue, typically for auth and roles.
  3. 3Interceptors run their before-logic.
  4. 4Pipes transform and validate parameters such as DTOs.
  5. 5The controller method runs and calls injected services.
  6. 6Interceptors 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.