Skip to content

A production-ready NestJS backend template with authentication, RBAC, TypeORM, PostgreSQL, and comprehensive tooling.

License

Notifications You must be signed in to change notification settings

LTPPPP/template-nestjs

Repository files navigation

NestJS Backend Template

A production-ready NestJS backend template with authentication, RBAC, TypeORM, PostgreSQL, and comprehensive tooling.

🚀 Features

  • Authentication & Authorization

    • JWT-based authentication (Access + Refresh tokens)
    • Role-Based Access Control (RBAC)
    • Password hashing with bcrypt
    • Custom decorators: @Public(), @Roles(), @CurrentUser()
  • Database

    • TypeORM with PostgreSQL
    • Migration and seeding support
    • Base entity with soft delete
    • UUID primary keys
  • Security

    • Helmet.js for security headers
    • CORS configuration
    • Rate limiting (Throttler)
    • Request validation
  • API Documentation

    • Swagger/OpenAPI at /api/docs
    • Full endpoint documentation
    • Bearer token authentication
  • Logging

    • Winston logger integration
    • Console and file transports
    • Daily log rotation
  • DevOps

    • Docker and Docker Compose
    • Health check endpoints
    • Production-ready Dockerfile

📁 Project Structure

src/
├── common/
│   ├── decorators/        # @Public, @Roles, @CurrentUser
│   ├── filters/           # Exception filters
│   ├── guards/            # JwtAuthGuard, RolesGuard
│   ├── interceptors/      # Response, Logging interceptors
│   ├── pipes/             # Validation pipes
│   ├── interfaces/        # Response, Pagination interfaces
│   └── constants/         # Roles enum
├── config/                # Configuration files
├── database/
│   ├── entities/          # TypeORM entities
│   ├── migrations/        # Database migrations
│   └── seeds/             # Database seeders
├── logger/                # Winston logger
├── modules/
│   ├── auth/              # Authentication
│   ├── users/             # User management
│   ├── health/            # Health checks
│   └── products/          # Sample CRUD module
└── main.ts                # Application entry

🛠️ Installation

Prerequisites

  • Node.js 18+
  • PostgreSQL 15+
  • npm or yarn

Setup

  1. Clone and install dependencies

    cd template-nestjs
    npm install
  2. Configure environment

    cp .env.example .env
    # Edit .env with your settings
  3. Start PostgreSQL (or use Docker)

    docker-compose up -d postgres redis
  4. Run database seed (optional)

    npm run seed
  5. Start development server

    npm run start:dev

📝 Environment Variables

Variable Description Default
NODE_ENV Environment development
PORT Server port 3000
API_PREFIX API route prefix api
DB_HOST Database host localhost
DB_PORT Database port 5432
DB_USERNAME Database user postgres
DB_PASSWORD Database password postgres
DB_DATABASE Database name nestjs_template
JWT_ACCESS_SECRET Access token secret -
JWT_ACCESS_EXPIRATION Access token TTL 15m
JWT_REFRESH_SECRET Refresh token secret -
JWT_REFRESH_EXPIRATION Refresh token TTL 7d
THROTTLE_TTL Rate limit window (seconds) 60
THROTTLE_LIMIT Max requests per window 100

🔧 Available Scripts

# Development
npm run start:dev         # Start with watch mode
npm run start:debug       # Start with debug mode

# Production
npm run build             # Build application
npm run start:prod        # Start production server

# Database
npm run migration:generate # Generate migration
npm run migration:run      # Run migrations
npm run seed              # Seed database

# Testing
npm run test              # Unit tests
npm run test:watch        # Watch mode
npm run test:cov          # Coverage report
npm run test:e2e          # E2E tests

# Code Quality
npm run lint              # ESLint
npm run format            # Prettier

📚 API Endpoints

Authentication

Method Endpoint Description
POST /api/auth/register Register new user
POST /api/auth/login Login user
POST /api/auth/refresh Refresh tokens
POST /api/auth/logout Logout user

Users (Admin only)

Method Endpoint Description
GET /api/users/me Get current user
GET /api/users List all users
GET /api/users/:id Get user by ID
POST /api/users Create user
PATCH /api/users/:id Update user
DELETE /api/users/:id Delete user

Products

Method Endpoint Description
GET /api/products List products (public)
GET /api/products/:id Get product (public)
POST /api/products Create product
PATCH /api/products/:id Update product
DELETE /api/products/:id Delete product

Health

Method Endpoint Description
GET /api/health Basic health check
GET /api/health/ready Readiness check
GET /api/health/live Liveness check

🐳 Docker

Development

# Start all services
docker-compose up -d

# Start with pgAdmin
docker-compose --profile dev up -d

# View logs
docker-compose logs -f app

Production

# Build image
docker build -t nestjs-app .

# Run container
docker run -p 3000:3000 --env-file .env nestjs-app

🧪 Testing

# Unit tests
npm run test

# E2E tests (requires database)
npm run test:e2e

# Coverage
npm run test:cov

📖 Swagger Documentation

Access API documentation at: http://localhost:3000/api/docs

🔒 Default Users (After Seeding)

Email Password Role
admin@example.com admin123 Admin
user@example.com user123 User

📄 License

MIT

About

A production-ready NestJS backend template with authentication, RBAC, TypeORM, PostgreSQL, and comprehensive tooling.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published