Skip to content

supercode221/nestjs-api-tutorials

Repository files navigation

NestJS API Tutorial

A comprehensive NestJS backend application demonstrating best practices with authentication, database management, and modern architectural patterns.

πŸ—οΈ Project Structure

nestjs-api-tutorial/
β”œβ”€β”€ dist/                 # Compiled output
β”œβ”€β”€ generated/            # Generated files
β”œβ”€β”€ node_modules/         # Dependencies
β”œβ”€β”€ prisma/               # Prisma schema and migrations
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ auth/            # Authentication module
β”‚   β”œβ”€β”€ bookmark/        # Bookmark module
β”‚   β”œβ”€β”€ prisma/          # Prisma service
β”‚   β”œβ”€β”€ user/            # User module
β”‚   β”œβ”€β”€ app.module.ts    # Main application module
β”‚   └── main.ts          # Application entry point
β”œβ”€β”€ test/                # Test files
β”œβ”€β”€ .env                 # Environment variables
β”œβ”€β”€ .gitignore          # Git ignore rules
β”œβ”€β”€ .prettierrc          # Prettier config
β”œβ”€β”€ docker-compose.yml  # Docker Compose configuration
β”œβ”€β”€ eslint.config.mjs   # ESLint configuration
β”œβ”€β”€ nest-cli.json       # NestJS CLI config
β”œβ”€β”€ package-lock.json   # Dependency lock file
β”œβ”€β”€ package.json        # Project dependencies
β”œβ”€β”€ prisma.config.ts    # Prisma configuration
β”œβ”€β”€ README.md           # This file
β”œβ”€β”€ tsconfig.build.json # TypeScript build config
β”œβ”€β”€ tsconfig.json       # TypeScript configuration
└── tsconfig.test.json  # TypeScript test config

πŸ› οΈ Tech Stack

  • Framework: NestJS (Node.js framework with TypeScript)
  • Database: PostgreSQL with Prisma ORM
  • Authentication: JWT with Passport.js
  • Containerization: Docker Compose
  • Validation: DTOs with Pipes
  • Configuration: NestJS Config Module

πŸ“¦ Core Dependencies

Framework & Core

  • @nestjs/common (^11.0.1) - Core NestJS framework
  • @nestjs/core (^11.0.1) - NestJS core module
  • @nestjs/platform-express (^11.0.1) - Express platform for NestJS

Authentication & Security

  • @nestjs/jwt (^11.0.1) - JWT token handling
  • @nestjs/passport (^11.0.5) - Passport.js integration
  • passport (^0.7.0) - Passport authentication middleware
  • passport-jwt (^4.0.1) - JWT authentication strategy
  • passport-local (^1.0.0) - Local authentication strategy
  • argon2 (^0.44.0) - Password hashing library

Database & ORM

  • @prisma/client (^6.19.0) - Prisma ORM client
  • prisma (^6.19.0) - Prisma CLI and schema tools

Configuration & Validation

  • @nestjs/config (^4.0.2) - Configuration management
  • class-validator (^0.14.2) - DTO validation decorators
  • class-transformer (^0.5.1) - Class transformation utilities
  • dotenv (^17.2.3) - Environment variable management

Utilities

  • reflect-metadata (^0.2.2) - Reflection metadata support
  • rxjs (^7.8.1) - Reactive programming library

πŸš€ Key Features

Authentication & Authorization

  • JWT-based authentication using Passport.js
  • Custom authentication guards with strategy pattern
  • Custom decorators for route protection
  • Role-based access control implementation

Database Management

  • Prisma ORM for type-safe database operations
  • PostgreSQL as primary database
  • Automatic schema migrations
  • Database seeding capabilities

Input Validation

  • DTOs (Data Transfer Objects) for request validation
  • Custom pipes for data transformation and validation
  • Automatic error handling and response formatting

Architecture Patterns

  • Decorator Pattern: Custom decorators for authentication and metadata
  • Guard Pattern: Custom guards for authorization with strategy implementation
  • Service Layer: Business logic separation
  • Module Pattern: Feature-based modular architecture

πŸ”§ Setup & Installation

Prerequisites

  • Node.js (v18 or higher)
  • Docker and Docker Compose
  • PostgreSQL (or use Docker Compose)

Installation Steps

  1. Clone the repository

    git clone <repository-url>
    cd nestjs-api-tutorial
  2. Install dependencies

    npm install
  3. Setup environment variables

    cp .env.example .env
    # Edit .env with your configuration
    # Required: DATABASE_URL, JWT_SECRET
  4. Start PostgreSQL with Docker Compose

    npm run db:dev:up
  5. Run Prisma migrations and start development

    npm run start:dev

    Or to manually deploy migrations:

    npm run prisma:dev:deploy
    npm run start:dev
  6. (Optional) Restart database

    npm run db:dev:restart

    This removes, recreates, and deploys all migrations.

The application will be available at http://localhost:3000

πŸ—„οΈ Database Setup

Docker Compose

The docker-compose.yml file defines a PostgreSQL service for local development.

Start the database:

npm run db:dev:up

Restart the database (removes all data and reruns migrations):

npm run db:dev:restart

Stop the database:

npm run db:dev:rm

Prisma Configuration

Prisma configuration is defined in prisma.config.ts. The database URL should be set in your .env file:

DATABASE_URL="postgresql://user:password@localhost:5432/nestjs_db"

Running Migrations

# Deploy existing migrations
npm run prisma:dev:deploy

# View database in Prisma Studio
npx prisma studio

πŸ” Authentication

The project implements JWT-based authentication using Passport.js:

Custom Guards

  • Implement authorization logic with strategy pattern
  • Protect routes from unauthorized access
  • Automatic token validation and extraction

Custom Decorators

  • @Public() - Mark routes as publicly accessible
  • @GetUser() - Extract user information from request
  • Create domain-specific decorators for your needs

JWT Strategy

Configured in the auth module with:

  • Token signing and verification
  • Configurable expiration times
  • Secret key management via environment variables

βš™οΈ Configuration Management

Configuration is managed through NestJS Config Module with environment variables:

// Access configuration in services
constructor(private configService: ConfigService) {}

const jwtSecret = this.configService.get<string>('JWT_SECRET');

⚠️ Important Notes

ESM & CommonJS Module Conflict

Critical: Prisma client is generated as CommonJS, while NestJS projects typically use ES Modules (ESM). This repository includes a working solution to resolve this conflict. If you encounter module resolution issues in other projects, refer to the implementation here.

To verify module configuration:

  • Check package.json for "type": "module"
  • Verify tsconfig.json for module settings
  • Ensure Prisma generation aligns with your module system

πŸ§ͺ Testing

Run tests with:

# Unit tests
npm run test

# Test coverage
npm run test:cov

# Watch mode
npm run test:watch

πŸ“ Available Scripts

Database Management

npm run db:dev:up           # Start PostgreSQL container
npm run db:dev:rm           # Remove PostgreSQL container
npm run db:dev:restart      # Restart database and apply migrations
npm run prisma:dev:deploy   # Deploy Prisma migrations

Development

npm run start:dev           # Start with watch mode
npm run start               # Start application
npm run start:debug         # Start with debugging enabled
npm run start:prod          # Start production build
npm run build               # Build for production

Testing

npm run test                # Run unit tests
npm run test:watch          # Run tests in watch mode
npm run test:cov            # Run tests with coverage report
npm run test:debug          # Debug tests
npm run test:e2e            # Run end-to-end tests

Code Quality

npm run lint                # Run ESLint with auto-fix
npm run format              # Format code with Prettier

🎯 Best Practices Demonstrated

  • Modular Architecture: Feature-based module organization
  • Type Safety: Full TypeScript usage with strict mode
  • Validation: DTO and Pipe-based input validation
  • Security: JWT authentication with secure token handling
  • Error Handling: Centralized exception filters
  • Configuration: Environment-based configuration management
  • Database: Type-safe ORM with Prisma
  • Code Quality: ESLint and Prettier integration

πŸ“š Learning Resources

🀝 Contributing

Feel free to contribute by submitting pull requests or opening issues for bugs and feature requests.

πŸ“„ License

This project is licensed under the MIT License.

About

This is my self-learn repo of nestjs

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published