1. Introduction & use cases
NestJS is a framework for building scalable server-side applications with TypeScript. Inspired by Angular, it organises code into modules, controllers (HTTP routes) and providers/services (business logic) connected through dependency injection.
Under the hood it uses Express (or Fastify), and it has first-class packages for configuration, validation, databases (TypeORM, Prisma, Mongoose), GraphQL, WebSockets, microservices, queues and OpenAPI docs. It suits teams that want a consistent architecture.
Where it is used
- Enterprise REST and GraphQL APIs
- Microservices with message brokers (RabbitMQ, Kafka, Redis)
- Real-time gateways with WebSockets
- Back-ends for large teams that need conventions
2. Prerequisites
| You need | Version / notes |
|---|---|
| Node.js | Current LTS release – check with node -v |
| Nest CLI | @nestjs/cli installed globally or run with npx |
| TypeScript basics | Classes, decorators, interfaces – see the TypeScript guide |
| Database (optional) | PostgreSQL, MySQL or MongoDB |
3. Local setup
1Install the Nest CLI
The CLI scaffolds projects and generates modules, controllers and services.
BASHnpm install -g @nestjs/cli nest --version2Create a project
Choose npm, yarn or pnpm when asked. Use
--strictfor strict TypeScript.BASHnest new my-nest-app --strict cd my-nest-app3Start in watch mode
Opens on http://localhost:3000 and recompiles on save.
BASHnpm run start:dev
4. Create & run a project
1Generate a CRUD resource
The generator creates a module, controller, service, DTOs and tests, and registers the module.
BASHnest g resource tasks # ? What transport layer do you use? REST API # ? Would you like to generate CRUD entry points? Yes2Implement the service
Services hold logic and are injected into controllers.
src/tasks/tasks.service.tsimport { Injectable, NotFoundException } from '@nestjs/common'; import { CreateTaskDto } from './dto/create-task.dto'; @Injectable() export class TasksService { private tasks: { id: number; title: string }[] = []; create(dto: CreateTaskDto) { const task = { id: this.tasks.length + 1, ...dto }; this.tasks.push(task); return task; } findAll() { return this.tasks; } findOne(id: number) { const t = this.tasks.find((x) => x.id === id); if (!t) throw new NotFoundException('Task not found'); return t; } }3Validate input with DTOs
Install the validation packages and enable a global
ValidationPipe.TSnpm install class-validator class-transformer // src/tasks/dto/create-task.dto.ts import { IsString, MinLength } from 'class-validator'; export class CreateTaskDto { @IsString() @MinLength(3) title: string; } // src/main.ts (inside bootstrap) app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));4Load configuration
Use
@nestjs/configto read.envand injectConfigService.TSnpm install @nestjs/config // src/app.module.ts import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ConfigModule.forRoot({ isGlobal: true }), TasksModule] }) export class AppModule {} // src/main.ts await app.listen(process.env.PORT ?? 3000);5Test the endpoints
POST invalid data to see automatic 400 responses.
BASHcurl -X POST localhost:3000/tasks -H "Content-Type: application/json" -d '{"title":"Write docs"}' curl localhost:3000/tasks
✅ When it works you should see output like Figure 1.
5. Development configuration
Environment variables
ConfigModule.forRoot() reads .env from the project root. Validate it with a schema (Joi or zod) via the validate option so the app refuses to start with missing settings.
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://nest:nest@localhost:5432/nest
JWT_SECRET=change-meKey dependencies
| Package / tool | Used for |
|---|---|
@nestjs/core, @nestjs/common | Framework core and decorators |
@nestjs/platform-express | HTTP adapter (or platform-fastify) |
@nestjs/config | .env and typed configuration |
class-validator, class-transformer | DTO validation |
@nestjs/swagger | OpenAPI docs at /api |
@nestjs/typeorm / prisma / @nestjs/mongoose | Database integration |
Folder structure
my-nest-app/
├── src/
│ ├── tasks/
│ │ ├── dto/
│ │ ├── tasks.controller.ts
│ │ ├── tasks.module.ts
│ │ └── tasks.service.ts
│ ├── app.module.ts
│ └── main.ts # bootstrap()
├── test/ # e2e tests
├── dist/ # compiled output
├── nest-cli.json
└── tsconfig.jsonEssential commands
| Command | What it does |
|---|---|
npm run start:dev | Watch mode |
nest g module|controller|service <name> | Generate building blocks |
nest g resource <name> | Full CRUD resource |
npm run build | Compile to dist/ |
npm run start:prod | Run node dist/main |
npm test / npm run test:e2e | Unit and end-to-end tests (Jest) |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu VPS, 1–2 GB RAM |
| Runtime | Node.js LTS |
| Build | npm run build (in CI or on the server) |
| Process manager | PM2 / systemd, or Docker |
| Reverse proxy + SSL | Nginx + Let’s Encrypt |
Deployment steps
1Prepare an Ubuntu server
Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.
BASHssh root@YOUR_SERVER_IP apt update && apt upgrade -y adduser deploy usermod -aG sudo deploy # copy your SSH key to the new user, then log in as deploy rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy exit ssh deploy@YOUR_SERVER_IP2Install Node.js on the server
Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.bashrc nvm install --lts node -v && npm -v3Get the code and build it
Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with
npm ciand build.BASHgit clone https://github.com/you/your-app.git /var/www/my-nest-app cd /var/www/my-nest-app npm ci npm run build npm prune --omit=dev4Keep the app running with PM2
PM2 restarts the app if it crashes and starts it again after a server reboot.
pm2 startupprints one command – run it with sudo, thenpm2 save.BASHsudo npm install -g pm2 pm2 start dist/main.js --name nest-api pm2 startup # run the command it prints pm2 save pm2 logs nest-api # live logs pm2 restart nest-api # after each deploy5Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:3000. Replaceexample.comwith your domain./etc/nginx/sites-available/example.comserver { listen 80; server_name example.com www.example.com; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }6Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx7Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor an online DNS checker.OUTPUT# Type Name Value TTL # A @ 203.0.113.10 3600 # A www 203.0.113.10 3600 dig +short example.com8Add free HTTPS with Let’s Encrypt
Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with
--dry-run.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run9Alternative: Docker image
A multi-stage build keeps the image small.
DockerfileFROM node:lts-alpine AS build WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build && npm prune --omit=dev FROM node:lts-alpine WORKDIR /app ENV NODE_ENV=production COPY --from=build /app/node_modules ./node_modules COPY --from=build /app/dist ./dist EXPOSE 3000 CMD ["node", "dist/main.js"]
🗺 The whole path from your code to the live site is drawn in the deployment diagram.
7. Images & screenshots
Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.
8. Common errors & solutions
Nest can't resolve dependencies of the XService (?)
The injected provider is not available in that module. Add it to the module’s providers, or import the module that exports it.
Validation decorators have no effect
Enable app.useGlobalPipes(new ValidationPipe()) and make sure the parameter type is a class (DTO), not an interface.
Cannot find module 'dist/main'
Run npm run build first; check sourceRoot/entryFile in nest-cli.json if you changed the structure.
Circular dependency between modules
Refactor shared logic into a third module, or use forwardRef(() => OtherModule) as a temporary fix.
.env values are undefined
Import ConfigModule.forRoot() in AppModule (with isGlobal: true) and read values through ConfigService after the module is initialised.
Best practices
- One feature = one module; keep controllers thin.
- Validate all input with DTOs and
whitelist: true. - Generate OpenAPI docs with
@nestjs/swagger. - Use
enableShutdownHooks()for graceful shutdown in containers. - Never commit
.envfiles or keys – add them to.gitignore, keep a.env.examplewith dummy values, and store real secrets in the server or CI secret store.