Backend & Languages

NestJS Setup & Deployment Guide

Structured, TypeScript-first Node.js framework – modules, controllers, services and dependency injection, from CLI to production.

Updated Official documentation ↗

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 needVersion / notes
Node.jsCurrent LTS release – check with node -v
Nest CLI@nestjs/cli installed globally or run with npx
TypeScript basicsClasses, decorators, interfaces – see the TypeScript guide
Database (optional)PostgreSQL, MySQL or MongoDB

3. Local setup

  1. 1Install the Nest CLI

    The CLI scaffolds projects and generates modules, controllers and services.

    BASH
    npm install -g @nestjs/cli
    nest --version
  2. 2Create a project

    Choose npm, yarn or pnpm when asked. Use --strict for strict TypeScript.

    BASH
    nest new my-nest-app --strict
    cd my-nest-app
  3. 3Start in watch mode

    Opens on http://localhost:3000 and recompiles on save.

    BASH
    npm run start:dev

4. Create & run a project

  1. 1Generate a CRUD resource

    The generator creates a module, controller, service, DTOs and tests, and registers the module.

    BASH
    nest g resource tasks
    # ? What transport layer do you use? REST API
    # ? Would you like to generate CRUD entry points? Yes
  2. 2Implement the service

    Services hold logic and are injected into controllers.

    src/tasks/tasks.service.ts
    import { 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;
      }
    }
  3. 3Validate input with DTOs

    Install the validation packages and enable a global ValidationPipe.

    TS
    npm 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 }));
  4. 4Load configuration

    Use @nestjs/config to read .env and inject ConfigService.

    TS
    npm 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);
  5. 5Test the endpoints

    POST invalid data to see automatic 400 responses.

    BASH
    curl -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.

.env
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://nest:nest@localhost:5432/nest
JWT_SECRET=change-me

Key dependencies

Package / toolUsed for
@nestjs/core, @nestjs/commonFramework core and decorators
@nestjs/platform-expressHTTP adapter (or platform-fastify)
@nestjs/config.env and typed configuration
class-validator, class-transformerDTO validation
@nestjs/swaggerOpenAPI docs at /api
@nestjs/typeorm / prisma / @nestjs/mongooseDatabase integration

Folder structure

project 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.json

Essential commands

CommandWhat it does
npm run start:devWatch mode
nest g module|controller|service <name>Generate building blocks
nest g resource <name>Full CRUD resource
npm run buildCompile to dist/
npm run start:prodRun node dist/main
npm test / npm run test:e2eUnit and end-to-end tests (Jest)

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerUbuntu VPS, 1–2 GB RAM
RuntimeNode.js LTS
Buildnpm run build (in CI or on the server)
Process managerPM2 / systemd, or Docker
Reverse proxy + SSLNginx + Let’s Encrypt

Deployment steps

  1. 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.

    BASH
    ssh 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_IP
  2. 2Install 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.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    source ~/.bashrc
    nvm install --lts
    node -v && npm -v
  3. 3Get the code and build it

    Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with npm ci and build.

    BASH
    git 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=dev
  4. 4Keep the app running with PM2

    PM2 restarts the app if it crashes and starts it again after a server reboot. pm2 startup prints one command – run it with sudo, then pm2 save.

    BASH
    sudo 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 deploy
  5. 5Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:3000. Replace example.com with your domain.

    /etc/nginx/sites-available/example.com
    server {
        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";
        }
    }
  6. 6Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  7. 7Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or 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.com
  8. 8Add 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.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  9. 9Alternative: Docker image

    A multi-stage build keeps the image small.

    Dockerfile
    FROM 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.

terminal$ npm run start:dev[Nest] 4120 - LOG [NestFactory] Starting Nest application...[Nest] 4120 - LOG [InstanceLoader] AppModule dependencies initialized[Nest] 4120 - LOG [InstanceLoader] TasksModule dependencies initialized[Nest] 4120 - LOG [RoutesResolver] TasksController {/tasks}:[Nest] 4120 - LOG [RouterExplorer] Mapped {/tasks, POST} route[Nest] 4120 - LOG [RouterExplorer] Mapped {/tasks, GET} route[Nest] 4120 - LOG [NestApplication] Nest application successfully started
Figure 1: terminal output of the sample NestJS project (section 4).
1Modules + services2npm run build →dist/3PM2 or Docker4Nginx :4435Live API
Figure 2: production deployment flow (section 6).
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.json
Figure 3: project folder structure (section 5).

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 .env files or keys – add them to .gitignore, keep a .env.example with dummy values, and store real secrets in the server or CI secret store.