Skip to content

A production-ready NestJS authentication boilerplate featuring OAuth 2.0 social login (Google, Facebook, GitHub), JWT authentication, Prisma ORM with PostgreSQL, and enterprise-grade architecture following Domain-Driven Design (DDD) principles

Notifications You must be signed in to change notification settings

trae-op/nestjs-boilerplate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

26 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

NestJS Authentication Starter Boilerplate

CI Coverage

A production-ready NestJS authentication boilerplate featuring OAuth 2.0 social login (Google, Facebook, GitHub), JWT authentication, Prisma ORM with PostgreSQL, and enterprise-grade architecture following Domain-Driven Design (DDD) principles.

This repository also serves as the backend service for the Electron + React starter electron-modular-boilerplate β€” https://github.com/trae-op/electron-modular-boilerplate. That project with OAuth (Google, GitHub) and Tailwind CSS; use this NestJS service for authentication and data storage.

πŸš€ Features

Authentication & Authorization

  • βœ… OAuth 2.0 Social Authentication
    • Google OAuth 2.0
    • Facebook OAuth 2.0
    • GitHub OAuth 2.0
  • βœ… JWT Token-based Authentication
  • βœ… Passport.js Integration with custom strategies
  • βœ… Protected Routes with JWT Guards

Architecture & Code Quality

  • βœ… Domain-Driven Design (DDD) with layered architecture
  • βœ… CQRS Pattern Ready (Command Query Responsibility Segregation)
  • βœ… Clean Architecture with separation of concerns
  • βœ… TypeScript Best Practices with strict type safety
  • βœ… Comprehensive Unit Tests with Jest
  • βœ… Path Aliases for cleaner imports (@modules, @config, @database)

Database & ORM

  • βœ… Prisma ORM with PostgreSQL
  • βœ… Type-safe Database Queries
  • βœ… Migration System with Prisma Migrate
  • βœ… Prisma Studio for database visualization
  • βœ… Production-ready Schema with best practices

Developer Experience

  • βœ… Yarn Package Manager (strict enforcement)
  • βœ… Hot Reload for development
  • βœ… ESLint & Prettier configured

Docker & Containerization

  • βœ… Docker Support with multi-stage builds
  • βœ… Docker Compose for development and production
  • βœ… PostgreSQL Container with persistent volumes
  • βœ… Health Checks for container monitoring
  • βœ… Development Hot-Reload in containers
  • βœ… Debug Support in Docker (port 9229)
  • βœ… Optimized Production Images with Alpine Linux
  • βœ… Security Best Practices (non-root user, minimal attack surface)
  • βœ… Optional Redis Integration for caching (If using!)

Code style & Linting πŸ”§

  • Prettier

    • Version: prettier (devDependency) ^3.4.2
    • Command: yarn format runs prettier --write "src/**/*.ts" "test/**/*.ts"
    • Plugins: @trivago/prettier-plugin-sort-imports is installed to sort imports automatically.
    • Config: No dedicated .prettierrc or prettier field was found β€” Prettier defaults are used. To customize formatting, add a .prettierrc (or a prettier field in package.json) and/or a .prettierignore file.
  • ESLint

    • Version: eslint (devDependency) ^9.18.0
    • Config file: eslint.config.mjs (uses @eslint/js, typescript-eslint recommended configs and includes eslint-plugin-prettier/recommended). eslint-config-prettier is also installed to avoid rule conflicts with Prettier.
    • Command: yarn lint runs eslint "{src,apps,libs,test}/**/*.ts" --fix
    • Notes: No .eslintignore file was found; eslint.config.mjs explicitly ignores itself (ignores: ['eslint.config.mjs']). Edit eslint.config.mjs to change rules or add an ignore file to exclude paths.
  • Workflow

    • Run yarn format to auto-format files with Prettier.
    • Run yarn lint (or yarn lint --fix) to run ESLint and apply fixable rule fixes (Prettier is integrated via the ESLint Prettier plugin).
    • Recommended: enable ESLint & Prettier editor extensions (e.g., in VS Code) for real-time feedback. This repo does not include pre-commit hooks by default β€” consider adding Husky + lint-staged if you want automated checks on commit.
  • βœ… Environment-based Configuration

  • βœ… Comprehensive Documentation for AI agents and developers

Legal & Compliance

  • βœ… Privacy Policy endpoint
  • βœ… Data Deletion Instructions endpoint (GDPR/CCPA compliance)

πŸ“ Project Structure

src/
β”œβ”€β”€ config/                      # Application configuration
β”‚   β”œβ”€β”€ config.module.ts        # Config module setup
β”‚   β”œβ”€β”€ config.service.ts       # Centralized config service
β”‚   └── types.ts                # Configuration types
β”œβ”€β”€ database/
β”‚   └── prisma/                 # Prisma service and module
β”œβ”€β”€ modules/
β”‚   β”œβ”€β”€ auth/                   # Authentication modules
β”‚   β”‚   β”œβ”€β”€ facebook/          # Facebook OAuth implementation
β”‚   β”‚   β”œβ”€β”€ github/            # GitHub OAuth implementation
β”‚   β”‚   β”œβ”€β”€ google/            # Google OAuth implementation
β”‚   β”‚   └── jwt/               # JWT strategy and service
β”‚   β”œβ”€β”€ legal/                 # Legal compliance endpoints
β”‚   β”‚   β”œβ”€β”€ data-deletion-instructions/
β”‚   β”‚   └── privacy/
β”‚   └── users/                 # User management
β”‚       β”œβ”€β”€ application/       # Business logic layer
β”‚       β”œβ”€β”€ presentation/      # Controllers and DTOs
β”‚       └── types.ts          # User type definitions
β”œβ”€β”€ app.module.ts              # Root application module
└── main.ts                    # Application entry point

prisma/
β”œβ”€β”€ schema.prisma              # Database schema definition
└── migrations/                # Database migration files

docs/                          # Comprehensive documentation
β”œβ”€β”€ git-commit-instructions.md
β”œβ”€β”€ nestjs-architecture.md     # Architecture guide
β”œβ”€β”€ nestjs-typescript-guide.md # TypeScript best practices
β”œβ”€β”€ nestjs-unit-test-guide.md  # Testing guidelines
β”œβ”€β”€ nestjs-yarn-package-management-guide.md
└── prisma-best-practices.md   # Database schema guidelines

Architecture Layers (DDD Pattern)

Each module follows a clean architecture with these layers:

  • presentation/ - Controllers, DTOs, HTTP layer
  • application/ - Services, business logic orchestration
  • infrastructure/ - Strategies, Guards, external integrations
  • domain/ - Entities, Value Objects (when needed)

πŸ› οΈ Prerequisites

  • Node.js >= 18.x
  • Yarn >= 1.22.x (required, npm is not supported)
  • PostgreSQL >= 14.x
  • Docker >= 20.10+ (optional, for containerized development)
  • Docker Compose >= 2.0+ (optional, for orchestration)

βš™οΈ Installation & Setup

1. Clone the Repository

git clone <repository-url>
cd nest-auth3

2. Install Dependencies

yarn install

This will also run prisma generate automatically via the postinstall hook.

3. Environment Configuration

Create a .env file in the root directory:

# Database
DATABASE_URL="postgresql://user:password@localhost:5432/nestauth?schema=public"

# Server
PORT=4200

# Google OAuth
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_CALLBACK_URL=http://localhost:4200/api/auth/google/callback

# Facebook OAuth
FACEBOOK_APP_ID=your_facebook_app_id
FACEBOOK_APP_SECRET=your_facebook_app_secret
FACEBOOK_CALLBACK_URL=http://localhost:4200/api/auth/facebook/callback

# GitHub OAuth
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
GITHUB_CALLBACK_URL=http://localhost:4200/api/auth/github/callback

# JWT
JWT_SECRET=your_super_secret_jwt_key_change_in_production
JWT_EXPIRATION=7d

4. Database Setup

Push Schema to Database

yarn prisma:push

Run Migrations (Production)

yarn prisma migrate dev --name init

Open Prisma Studio (Optional)

yarn prisma:studio

5. Run the Application

Development Mode (with hot reload)

yarn start:dev

Production Mode

yarn build
yarn start:prod

The server will start on http://localhost:4200


οΏ½ Docker Setup

Why Use Docker?

Docker provides a consistent development environment across all machines and simplifies deployment. This project includes:

  • Multi-stage builds for optimized production images (50-70% smaller)
  • Separate configurations for development and production
  • Hot-reloading in development containers
  • PostgreSQL containerized with persistent data
  • Health checks for monitoring
  • Security hardening with non-root users

Quick Start with Docker

Development Mode

  1. Start all services (NestJS + PostgreSQL):
docker-compose up -d
  1. View logs:
docker-compose logs -f nestjs-app
  1. Access the application:

  2. Stop containers:

docker-compose down

Production Mode

  1. Create production environment file:
cp .env.example .env.production
  1. Update production variables with secure values

  2. Start production containers:

docker-compose -f docker-compose.prod.yml up -d

Docker Commands Reference

Container Management

# Start containers
docker-compose up -d

# Stop containers
docker-compose down

# Restart specific service
docker-compose restart nestjs-app

# View running containers
docker-compose ps

# Access container shell
docker-compose exec nestjs-app sh

# Rebuild containers
docker-compose up -d --build

# Stop and remove volumes (⚠️ deletes data)
docker-compose down -v

Database Management

# Access PostgreSQL
docker-compose exec postgres psql -U postgres -d nestjs_boilerplate

# Run Prisma migrations
docker-compose exec nestjs-app yarn prisma migrate dev --name migration_name

# Open Prisma Studio
docker-compose exec nestjs-app yarn prisma studio

# Backup database
docker-compose exec postgres pg_dump -U postgres nestjs_boilerplate > backup.sql

# Restore database
cat backup.sql | docker-compose exec -T postgres psql -U postgres -d nestjs_boilerplate

Logs & Debugging

# View logs for all services
docker-compose logs -f

# View logs for specific service
docker-compose logs -f nestjs-app

# View last 100 lines
docker-compose logs --tail 100 nestjs-app

# Monitor resource usage
docker stats

Debugging in Docker

The development setup includes debugging support on port 9229.

VS Code Configuration - Add to .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      "name": "Docker: Attach to Node",
      "port": 9229,
      "address": "localhost",
      "localRoot": "${workspaceFolder}",
      "remoteRoot": "/usr/src/app",
      "protocol": "inspector",
      "restart": true,
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}

Optional: Adding Redis

If using Redis! For caching, session management, or message queuing, add Redis to your stack:

# Already configured in docker-compose.yml
# Just uncomment the redis service section

Update your .env:

REDIS_HOST=redis
REDIS_PORT=6379

Docker Architecture

  • Development: Hot-reloading with volume mounts for instant code changes
  • Production: Optimized multi-stage builds with Alpine Linux (minimal image size)
  • Database: PostgreSQL 16 with named volumes for data persistence
  • Network: Isolated bridge network for secure service communication
  • Security: Non-root user, resource limits, health checks

Troubleshooting

Container won't start:

# Check logs
docker-compose logs

# Rebuild without cache
docker-compose build --no-cache
docker-compose up -d

Database connection issues:

# Verify postgres is healthy
docker-compose ps

# Check postgres logs
docker-compose logs postgres

Port already in use:

# Stop all containers
docker-compose down

# Change port in docker-compose.yml or kill the process using the port

Clean up everything:

# Remove all containers, images, and volumes
docker system prune -a
docker volume prune

For comprehensive Docker documentation, see:


οΏ½πŸ” OAuth Provider Setup

Google OAuth 2.0

  1. Go to Google Cloud Console
  2. Create a new project or select existing
  3. Navigate to APIs & Services β†’ Credentials
  4. Create OAuth 2.0 Client ID credentials
  5. Add authorized redirect URI: http://localhost:4200/api/auth/google/callback
  6. Copy Client ID and Client Secret to .env

Facebook OAuth 2.0

  1. Go to Facebook Developers
  2. Create a new app or select existing
  3. Navigate to Settings β†’ Basic
  4. Copy App ID and App Secret to .env
  5. Add Facebook Login product
  6. Configure Valid OAuth Redirect URIs: http://localhost:4200/api/auth/facebook/callback

GitHub OAuth 2.0

  1. Go to GitHub Developer Settings
  2. Click New OAuth App
  3. Set Authorization callback URL: http://localhost:4200/api/auth/github/callback
  4. Copy Client ID and Client Secret to .env

πŸ“‘ API Endpoints

Authentication Endpoints

Method Endpoint Description Auth Required
GET /api/auth/google Initiate Google OAuth No
GET /api/auth/google/callback Google OAuth callback No
GET /api/auth/facebook Initiate Facebook OAuth No
GET /api/auth/facebook/callback Facebook OAuth callback No
GET /api/auth/github Initiate GitHub OAuth No
GET /api/auth/github/callback GitHub OAuth callback No

User Endpoints

Method Endpoint Description Auth Required
GET /api/users/profile Get current user profile Yes (JWT)
PATCH /api/users/:id Update user profile Yes (JWT)

Legal Endpoints

Method Endpoint Description Auth Required
GET /privacy-policy Privacy policy page No
GET /data-deletion-instructions Data deletion instructions No

πŸ§ͺ Testing

Run All Tests

yarn test

Run Tests in Watch Mode

yarn test:watch

Run Tests with Coverage

yarn test:cov

Run E2E Tests

yarn test:e2e

Continuous Integration

The project uses GitHub Actions for automated testing and build verification on every push and pull request.

Workflow Features:

  • βœ… Multi-Node Testing: Tests run on Node.js 18.x and 20.x
  • βœ… Automated Linting: ESLint checks on every commit
  • βœ… Test Coverage: Generates and uploads coverage reports to Codecov
  • βœ… Build Verification: Ensures the application builds successfully
  • βœ… Artifact Storage: Coverage reports and build artifacts are saved

Setting Up Codecov (Optional)

To enable coverage badge and reporting:

  1. Sign up at Codecov.io
  2. Add your repository
  3. Add CODECOV_TOKEN to your GitHub repository secrets:
    • Go to Settings β†’ Secrets and variables β†’ Actions
    • Click New repository secret
    • Name: CODECOV_TOKEN
    • Value: Your Codecov token
  4. The workflow will automatically upload coverage on every push

Viewing CI Results

Check the Actions tab in your GitHub repository to view:

  • Test results across different Node.js versions
  • Code coverage reports
  • Build status
  • Download artifacts (coverage reports, build files)

πŸ—„οΈ Database Schema

The application uses a simple yet effective user schema:

model User {
  id          String     @id @default(uuid())
  email       String?    @unique
  provider    Providers?
  sourceId    String?    @map("source_id")
  displayName String?    @map("display_name")
  firstName   String?    @map("first_name")
  lastName    String?    @map("last_name")
  picture     String?
  createdAt   DateTime   @default(now()) @map("created_at")
  updatedAt   DateTime   @updatedAt @map("updated_at")

  @@unique([provider, sourceId])
  @@index([provider, sourceId])
  @@map("users")
}

enum Providers {
  google
  facebook
  github
}

Key Features:

  • UUID primary keys for distributed systems
  • Support for multiple OAuth providers
  • Composite unique constraint on provider + sourceId
  • Indexed for query performance
  • Snake_case database naming with camelCase Prisma fields

🎯 Key Design Decisions

Why Yarn?

This project strictly uses Yarn for package management to ensure consistent dependency resolution and lockfile format. All documentation and tooling is configured for Yarn.

Why Types over Interfaces?

Following TypeScript best practices, all types use the type keyword with the TNameFormat naming convention (T prefix + PascalCase) for consistency and better type composition.

Why DDD Architecture?

Domain-Driven Design provides:

  • Clear separation of concerns
  • Testable business logic
  • Scalable codebase structure
  • Easy to understand module boundaries
  • Framework-agnostic domain layer

Why Prisma?

Prisma offers:

  • Type-safe database queries
  • Excellent TypeScript integration
  • Migration system out of the box
  • Intuitive schema definition
  • Great developer experience with Prisma Studio

πŸ”§ Common Tasks

Generate New Module

yarn nest generate module modules/feature-name

Generate New Service

yarn nest generate service modules/feature-name/application/feature-name

Generate New Controller

yarn nest generate controller modules/feature-name/presentation/controllers/feature-name

Create Database Migration

yarn prisma migrate dev --name migration_name

Reset Database

yarn prisma migrate reset

πŸ“¦ Scripts Reference

Yarn Scripts

Script Description
yarn start Start application
yarn start:dev Start in development mode with hot reload
yarn start:prod Start in production mode
yarn build Build the application
yarn test Run unit tests
yarn test:watch Run tests in watch mode
yarn test:cov Run tests with coverage report
yarn test:e2e Run end-to-end tests
yarn lint Lint and fix code
yarn format Format code with Prettier
yarn prisma:push Push schema changes to database
yarn prisma:studio Open Prisma Studio

Docker Commands

Command Description
docker-compose up -d Start development containers
docker-compose down Stop containers
docker-compose logs -f View logs
docker-compose exec nestjs-app sh Access container shell
docker-compose restart nestjs-app Restart application container
docker-compose up -d --build Rebuild and start containers
docker-compose -f docker-compose.prod.yml up -d Start production containers
docker-compose exec postgres psql -U postgres Access PostgreSQL
docker-compose exec nestjs-app yarn prisma studio Open Prisma Studio in container
docker system prune -a Clean up Docker resources

πŸ”’ Security Best Practices

  • βœ… Environment variables for sensitive data
  • βœ… JWT tokens with configurable expiration
  • βœ… Password-less authentication via OAuth
  • βœ… Input validation with class-validator
  • βœ… Type-safe database queries
  • βœ… Helmet middleware ready (can be added)
  • βœ… Rate limiting ready (can be added)

🚧 Roadmap & Extensions

This boilerplate can be extended with:

  • Email/Password authentication
  • Two-factor authentication (2FA)
  • Refresh token mechanism
  • Role-based access control (RBAC)
  • Rate limiting
  • API documentation with Swagger
  • Logging system (Winston/Pino)
  • Redis caching (If using!)
  • WebSocket support
  • File upload functionality
  • Email service integration

🀝 Contributing

  1. Follow the coding guidelines in docs/
  2. Write tests for new features
  3. Use conventional commits (see docs/git-commit-instructions.md)
  4. Ensure all tests pass before submitting PR
  5. Update documentation as needed

πŸ“– Documentation

Comprehensive guides for development:

About

A production-ready NestJS authentication boilerplate featuring OAuth 2.0 social login (Google, Facebook, GitHub), JWT authentication, Prisma ORM with PostgreSQL, and enterprise-grade architecture following Domain-Driven Design (DDD) principles

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages