# NestJS + PostgreSQL

> Progressive Node.js framework with TypeORM and PostgreSQL.

- Category: Full Web Stacks
- Difficulty: intermediate
- Components: nestjs, postgres
- Tags: nestjs, nodejs, postgres, typeorm
- Source: https://docker.recipes/full-stacks/nestjs-postgres

## Overview

NestJS is a progressive Node.js framework built with TypeScript that leverages decorators and dependency injection to create scalable server-side applications. Inspired by Angular's architecture, NestJS was created by Kamil Myśliwiec in 2017 to bring enterprise-grade structure to Node.js development. The framework combines elements of object-oriented programming, functional programming, and reactive programming, making it particularly attractive for developers familiar with Angular or Spring Boot who want similar architectural patterns in their backend services.

This stack pairs NestJS with PostgreSQL through TypeORM, creating a type-safe development environment where database schemas are defined as TypeScript entities and queries are validated at compile time. PostgreSQL's advanced features like JSONB columns, full-text search, and complex query capabilities complement NestJS's modular architecture perfectly. The combination provides ACID compliance for critical business logic while maintaining the flexibility to handle both relational and document-style data within the same application.

This configuration is ideal for teams building enterprise applications, SaaS platforms, or complex APIs that require strict type safety, comprehensive testing capabilities, and robust data integrity. The stack excels in scenarios where business logic is complex, data relationships are intricate, and long-term maintainability is crucial. Development teams familiar with Angular will find the learning curve minimal, while the TypeScript foundation ensures excellent IDE support and refactoring capabilities across the entire application stack.

## Features

- Decorator-based routing and dependency injection system with Guards, Interceptors, and Pipes for request lifecycle management
- TypeORM integration with Entity definitions, Repository patterns, and automatic migration generation from TypeScript classes
- Built-in Swagger documentation generation through decorators that automatically create OpenAPI specifications
- PostgreSQL JSONB column support for hybrid relational-document data models with full TypeScript type inference
- Class-validator integration for automatic DTO validation with custom validation decorators and error formatting
- Modular architecture with lazy-loaded modules, circular dependency resolution, and dynamic module configuration
- Built-in testing utilities with dependency mocking, e2e testing support, and database transaction rollback for tests
- Exception filters and custom error handling with PostgreSQL-specific error code interpretation

## Use cases

- Enterprise SaaS platforms requiring multi-tenant architecture with complex user permissions and data isolation
- E-commerce backends with inventory management, order processing, and payment integration requiring ACID transactions
- Content management systems with complex taxonomies, full-text search, and media asset relationships
- Financial applications requiring audit trails, transaction integrity, and compliance with regulatory reporting
- Real-time collaboration platforms with WebSocket support, event sourcing, and conflict resolution
- API-first applications serving mobile apps and SPAs with comprehensive authentication and rate limiting
- Data analytics dashboards requiring complex PostgreSQL queries with window functions and aggregations

## Prerequisites

- Docker and Docker Compose installed with minimum 2GB RAM available for PostgreSQL operations
- Node.js 18+ knowledge and TypeScript familiarity for understanding decorators and advanced types
- Basic SQL knowledge for writing TypeORM queries and understanding PostgreSQL-specific features
- Understanding of dependency injection patterns and object-oriented programming concepts
- Port 3000 available for NestJS application and port 5432 free for PostgreSQL connections
- Environment variables configured: DB_USER, DB_PASSWORD, and DB_NAME in .env file

## docker-compose.yml

```yaml
services:
  nestjs:
    build: .
    container_name: nestjs
    environment:
      DB_HOST: postgres
      DB_PORT: 5432
      DB_USER: ${DB_USER}
      DB_PASSWORD: ${DB_PASSWORD}
      DB_NAME: ${DB_NAME}
    ports:
      - "3000:3000"
    depends_on:
      - postgres
    networks:
      - nest-network

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: ${DB_NAME}
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - nest-network

volumes:
  postgres_data:

networks:
  nest-network:
    driver: bridge
```

## .env

```bash
DB_NAME=nestjs
DB_USER=nestjs
DB_PASSWORD=changeme
```

## Usage notes

- Docs: https://docs.nestjs.com/
- Access at http://localhost:3000
- Modular architecture with providers and modules
- TypeORM or Prisma for database access
- Swagger docs: @nestjs/swagger with /api endpoint
- Built-in validation with class-validator

## Troubleshooting

- TypeORM synchronize: true causing data loss: Set synchronize: false in production and use proper migrations with npm run migration:generate
- Cannot connect to PostgreSQL from NestJS: Ensure DB_HOST uses service name 'postgres' not 'localhost' in Docker network
- Class-validator not working on DTOs: Add @UsePipes(ValidationPipe) decorator to controllers and install class-transformer
- PostgreSQL connection pool exhausted: Configure TypeORM with proper connection limits using extra.max and extra.min pool settings
- Circular dependency detected in modules: Use forwardRef() wrapper or restructure modules to eliminate circular imports
- TypeORM entity changes not reflected: Run npm run build to compile TypeScript changes and restart containers with fresh database connection

