Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 42 ยท Getting Started

Project Structure and the CLI

Create a project with nest new, understand main.ts and app.module, learn Nest naming conventions, use nest generate schematics and organize code in feature folders.

A new Nest project is generated by a command-line tool, and its layout is the same on every team that uses Nest. That is one of the framework's quiet advantages: when you open an unfamiliar Nest codebase you already know where the entry point is, where modules live, and what a file called users.controller.ts contains.

In this lesson you will create a project with the Nest CLI, read what it generates, learn the naming conventions, and meet the schematics that write boilerplate for you. The CLI needs Node and npm, so its commands are read-only here. As stand-ins, you can run small programs that print the same file trees and generate the same names, so you can see exactly how the conventions work.

Creating a project

Install the CLI once, then create a project. The CLI asks which package manager you want.

Terminal
npm install -g @nestjs/cli
nest new todo-api
cd todo-api
npm run start:dev

start:dev runs the app in watch mode and restarts it when you save a file. Open http://localhost:3000 and you should see the starter response. You can also skip the global install with npx @nestjs/cli new todo-api.

What nest new generates

The files in src

main.ts Entry point that calls NestFactory.
app.module.ts The root module.
app.controller.ts One example route.
app.service.ts One example provider.
1 / 2

The exact set can differ a little between CLI versions, but a fresh project looks like this:

TEXT
todo-api/
  src/
    app.controller.ts
    app.controller.spec.ts
    app.module.ts
    app.service.ts
    main.ts
  test/
    app.e2e-spec.ts
    jest-e2e.json
  nest-cli.json
  package.json
  tsconfig.json
  tsconfig.build.json

The project also gets a linter config, a Prettier config and a .gitignore. Let us look at the most important pieces.

main.ts is the entry point you saw in How a Nest App Boots. It creates the app from the root module and listens on a port. This is the right place for global settings: prefixes, CORS, global pipes and shutdown hooks.

TypeScript
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

app.module.ts is the root module. It lists the controllers, providers and other modules the app uses. In the starter it simply declares AppController and AppService. As your app grows, the root module mostly becomes a list of feature modules.

*.spec.ts files are unit tests that sit next to the code they test. The test/ folder holds end-to-end tests, which start the whole app and make requests against it. Both are explained in Testing Nest Applications.

tsconfig.json turns on experimentalDecorators and emitDecoratorMetadata, which the framework needs, as described in the boot lesson. You normally do not touch these two options.

Here is a stand-in that prints a project tree from a plain description, so you can see how the structure fits together. Add a feature and run it again.

JS Print a Nest project tree

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Naming conventions

Nest projects follow a strict, predictable naming scheme, and the CLI generates names that way:

  • Files use lowercase kebab-case with a role suffix: users.controller.ts, users.service.ts, users.module.ts, create-user.dto.ts, auth.guard.ts, logging.interceptor.ts.
  • Classes use PascalCase with the same role as a suffix: UsersController, UsersService, UsersModule, CreateUserDto.
  • Folders are one per feature, named after the feature in plural or singular form, whichever your team picks and keeps.

The suffix is more than decoration. It tells you what a file is without opening it, and it makes searching easy ("find every guard" is a search for .guard.ts). The next stand-in turns a feature name into the files and class names that a Nest resource would use.

JS From feature name to file and class names

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Generating code with nest generate

The CLI can write the boilerplate for you. These commands are the real ones, read-only here:

Terminal
nest generate module users        # short: nest g mo users
nest generate controller users    # short: nest g co users
nest generate service users       # short: nest g s users
nest generate resource users      # short: nest g res users

The first three create one file each (plus a spec file) and, importantly, register the new class in the nearest module by editing the module's arrays. nest g resource users is the big one: it asks which kind of API you want (REST, GraphQL, microservice or WebSocket gateway) and whether to generate CRUD entry points, then creates a complete feature folder with a module, controller, service, DTO and entity files, and imports the new module in app.module.ts.

Useful flags:

  • --dry-run prints what would be created without writing anything. Try it first when unsure.
  • --no-spec skips the test file.
  • --flat puts files directly in the target folder instead of creating a subfolder.

Generating with the CLI saves time, but read what it produced. The generated code is a starting point: a CRUD resource contains placeholder methods that return strings like "This action returns all users" until you implement them.

Organizing by feature

Beginners often group files by type (all controllers in one folder, all services in another). Nest recommends the opposite: group by feature. Everything about users lives in src/users/, everything about orders in src/orders/.

TEXT
src/
  users/
    dto/
    entities/
    users.controller.ts
    users.module.ts
    users.service.ts
  orders/
    ...
  common/
    filters/
    guards/
    interceptors/
    pipes/
  config/
  app.module.ts
  main.ts

Feature folders match feature modules one to one, so you can see how pieces depend on each other, delete a feature by deleting a folder, and later extract a feature into its own package or microservice with little pain. Code used by several features, such as shared guards, filters and decorators, goes in a common/ folder.

Structuring projects by size

The feature-folder layout above works from the first day, but how much structure you add should follow how big the code base is. Too little structure makes a big app hard to navigate; too much makes a small app slow to change.

Flat (a handful of files). For a prototype, a script-sized API or a learning project, keep everything in src/ with one module and a few files. Do not create domain/, application/ and infrastructure/ folders for an app with three endpoints.

TEXT
src/
  app.module.ts
  app.controller.ts
  app.service.ts
  main.ts

Modular (most apps). Once you have several features, give each its own folder and module, as shown in the previous section. This is the layout the CLI generates, and it carries a team of several developers a long way. Rules of thumb: one module per feature, a common/ folder for guards, filters, pipes and decorators used by several features, and a config/ folder for configuration.

Layered or domain-driven (large systems). In very large or long-lived systems, teams often split each feature further, separating business rules from framework and database code:

TEXT
src/
  orders/
    domain/            plain classes and rules, no Nest imports
      order.ts
      order-policy.ts
    application/       use cases that orchestrate the domain
      place-order.use-case.ts
    infrastructure/    database, HTTP clients, queues
      typeorm-orders.repository.ts
    presentation/      controllers, DTOs, resolvers
      orders.controller.ts
    orders.module.ts

The payoff is that the domain code can be tested without Nest or a database and does not change when you swap the ORM. The cost is more files, more mapping between layers and more ceremony for simple changes. Adopt it for a module that has real business rules, not for every CRUD table.

A shared folder, with care. Code that several features need goes in common/ (or shared/). Keep it small and generic: guards, pipes, decorators, a pagination DTO. If common/ starts to contain UserHelper or OrderUtils, those belong in the feature that owns the concept, or in a module that exports a proper provider. A giant common/ folder is how feature boundaries quietly dissolve.

Moving up a level. Start flat, move to modular when a second feature appears, and add layers inside one module only when its logic becomes hard to test. For several apps that deploy separately, Nest's monorepo mode (nest generate app and nest generate library) puts apps and shared libraries in one repository without changing how modules work. Read Modules for how exports and imports keep these boundaries honest.

Useful npm scripts

The generated package.json contains scripts that you will use daily:

  • npm run start runs the app once, npm run start:dev runs it in watch mode, and npm run start:prod runs the compiled output from dist/.
  • npm run build compiles TypeScript to the dist/ folder.
  • npm run test runs unit tests, and npm run test:e2e runs end-to-end tests.
  • npm run lint and npm run format check and fix code style.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the Nest CLI-generated project call NestFactory.create()?

    main.ts is the entry point. It creates the application from the root module and starts listening.
  2. 2. Which file name follows Nest's naming convention for a service in the feature 'orders'?

    Files use lowercase kebab-case plus a role suffix, such as orders.service.ts, while the class inside is OrdersService.
  3. 3. What does the --dry-run flag do for nest generate?

    --dry-run is a safe preview: it lists the files and changes without touching the disk.
  4. 4. Why does Nest recommend feature folders over type folders?

    Feature folders keep related code together and line up with feature modules, so a feature can be changed, removed or extracted as one unit.

Summary

  • nest new creates a project with src/main.ts, a root module, an example controller and service, tests and configuration files.
  • main.ts bootstraps the app and is the place for global setup; app.module.ts is the root module.
  • Files use kebab-case with role suffixes (users.controller.ts), and classes use PascalCase with the same role (UsersController).
  • nest generate (g) schematics write modules, controllers, services and whole resources, and register them in the nearest module; --dry-run previews the result.
  • Organize by feature folders, with shared code in common/.
  • Our stand-ins print trees and names with plain JavaScript; the CLI itself is real but read-only here.

Next: Controllers and Routing