Generating code: the nest CLI
NestJS files almost always start with the same lines: an import, a decorator, an empty class. The Nest CLI creates such skeletons with nest generate and immediately registers them in the right module, so you do not have to do it by hand.
One skeleton
Run the commands from the project root. The word generate can be shortened to g:
nest g module posts
nest g controller posts
nest g service postsA src/posts/ folder appears with posts.module.ts, posts.controller.ts and posts.service.ts. The CLI adds PostsModule to the imports of the root module, and the controller and service to PostsModule. The terminal shows which files were created (CREATE) and changed (UPDATE).
A whole resource
A resource is everything one API entity needs: a module, controller, service, DTOs and an entity class. For the blog, create posts:
nest g resource postsThe CLI asks two questions. For the transport layer choose REST API, and answer Y to generating CRUD entry points. The result:
src/posts/
├── dto/
│ ├── create-post.dto.ts
│ └── update-post.dto.ts
├── entities/
│ └── post.entity.ts
├── posts.controller.spec.ts
├── posts.controller.ts
├── posts.module.ts
├── posts.service.spec.ts
└── posts.service.tsCRUD stands for the four basic data actions: create, read, update and delete. The controller already has five routes: GET /posts, GET /posts/:id, POST /posts, PATCH /posts/:id and DELETE /posts/:id. Open http://localhost:3000/posts — you will see the string This action returns all posts. The generated service returns it; you will write the real code in the next lessons.
Useful flags
| Flag | What it does |
|---|---|
--dry-run or -d | Shows what would be created without creating files |
--no-spec | Do not create a .spec.ts test file |
--flat | Do not create a separate folder |
nest g controller comments --dry-runThe command prints the list of files, but nothing changes on disk — handy for checking yourself.
Available skeletons
| Command | What it creates |
|---|---|
nest g module | Module |
nest g controller | Controller |
nest g service | Service |
nest g resource | Module, controller, service, DTOs and entity |
nest g pipe | Pipe |
nest g guard | Guard |
nest g interceptor | Interceptor |
nest g middleware | Middleware |
nest g --help shows the full list.
Common mistake
If you create a controller file by hand and forget to list it in the module's controllers array, NestJS never learns about it: its routes answer 404 with no error at startup. Use nest g — it registers classes for you. If you do create a file by hand, add the class to the module right away.