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.
- β
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
- β 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)
- β Prisma ORM with PostgreSQL
- β Type-safe Database Queries
- β Migration System with Prisma Migrate
- β Prisma Studio for database visualization
- β Production-ready Schema with best practices
- β Yarn Package Manager (strict enforcement)
- β Hot Reload for development
- β ESLint & Prettier configured
- β 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!)
-
Prettier
- Version:
prettier(devDependency) ^3.4.2 - Command:
yarn formatrunsprettier --write "src/**/*.ts" "test/**/*.ts" - Plugins:
@trivago/prettier-plugin-sort-importsis installed to sort imports automatically. - Config: No dedicated
.prettierrcorprettierfield was found β Prettier defaults are used. To customize formatting, add a.prettierrc(or aprettierfield inpackage.json) and/or a.prettierignorefile.
- Version:
-
ESLint
- Version:
eslint(devDependency) ^9.18.0 - Config file:
eslint.config.mjs(uses@eslint/js,typescript-eslintrecommended configs and includeseslint-plugin-prettier/recommended).eslint-config-prettieris also installed to avoid rule conflicts with Prettier. - Command:
yarn lintrunseslint "{src,apps,libs,test}/**/*.ts" --fix - Notes: No
.eslintignorefile was found;eslint.config.mjsexplicitly ignores itself (ignores: ['eslint.config.mjs']). Editeslint.config.mjsto change rules or add an ignore file to exclude paths.
- Version:
-
Workflow
- Run
yarn formatto auto-format files with Prettier. - Run
yarn lint(oryarn 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.
- Run
-
β Environment-based Configuration
-
β Comprehensive Documentation for AI agents and developers
- β Privacy Policy endpoint
- β Data Deletion Instructions endpoint (GDPR/CCPA compliance)
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
Each module follows a clean architecture with these layers:
presentation/- Controllers, DTOs, HTTP layerapplication/- Services, business logic orchestrationinfrastructure/- Strategies, Guards, external integrationsdomain/- Entities, Value Objects (when needed)
- 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)
git clone <repository-url>
cd nest-auth3yarn installThis will also run prisma generate automatically via the postinstall hook.
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=7dyarn prisma:pushyarn prisma migrate dev --name inityarn prisma:studioyarn start:devyarn build
yarn start:prodThe server will start on http://localhost:4200
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
- Start all services (NestJS + PostgreSQL):
docker-compose up -d- View logs:
docker-compose logs -f nestjs-app-
Access the application:
- API: http://localhost:4200/api
- Database: localhost:5432
-
Stop containers:
docker-compose down- Create production environment file:
cp .env.example .env.production-
Update production variables with secure values
-
Start production containers:
docker-compose -f docker-compose.prod.yml up -d# 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# 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# 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 statsThe 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>/**"]
}
]
}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 sectionUpdate your .env:
REDIS_HOST=redis
REDIS_PORT=6379- 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
Container won't start:
# Check logs
docker-compose logs
# Rebuild without cache
docker-compose build --no-cache
docker-compose up -dDatabase connection issues:
# Verify postgres is healthy
docker-compose ps
# Check postgres logs
docker-compose logs postgresPort already in use:
# Stop all containers
docker-compose down
# Change port in docker-compose.yml or kill the process using the portClean up everything:
# Remove all containers, images, and volumes
docker system prune -a
docker volume pruneFor comprehensive Docker documentation, see:
- docs/docker-setup.md - Quick start guide
- docs/docker-nestjs.md - Best practices and advanced configurations
- Go to Google Cloud Console
- Create a new project or select existing
- Navigate to APIs & Services β Credentials
- Create OAuth 2.0 Client ID credentials
- Add authorized redirect URI:
http://localhost:4200/api/auth/google/callback - Copy Client ID and Client Secret to
.env
- Go to Facebook Developers
- Create a new app or select existing
- Navigate to Settings β Basic
- Copy App ID and App Secret to
.env - Add Facebook Login product
- Configure Valid OAuth Redirect URIs:
http://localhost:4200/api/auth/facebook/callback
- Go to GitHub Developer Settings
- Click New OAuth App
- Set Authorization callback URL:
http://localhost:4200/api/auth/github/callback - Copy Client ID and Client Secret to
.env
| 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 |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /api/users/profile |
Get current user profile | Yes (JWT) |
| PATCH | /api/users/:id |
Update user profile | Yes (JWT) |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /privacy-policy |
Privacy policy page | No |
| GET | /data-deletion-instructions |
Data deletion instructions | No |
yarn testyarn test:watchyarn test:covyarn test:e2eThe project uses GitHub Actions for automated testing and build verification on every push and pull request.
- β 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
To enable coverage badge and reporting:
- Sign up at Codecov.io
- Add your repository
- Add
CODECOV_TOKENto your GitHub repository secrets:- Go to Settings β Secrets and variables β Actions
- Click New repository secret
- Name:
CODECOV_TOKEN - Value: Your Codecov token
- The workflow will automatically upload coverage on every push
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)
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
}- 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
This project strictly uses Yarn for package management to ensure consistent dependency resolution and lockfile format. All documentation and tooling is configured for Yarn.
Following TypeScript best practices, all types use the type keyword with the TNameFormat naming convention (T prefix + PascalCase) for consistency and better type composition.
Domain-Driven Design provides:
- Clear separation of concerns
- Testable business logic
- Scalable codebase structure
- Easy to understand module boundaries
- Framework-agnostic domain layer
Prisma offers:
- Type-safe database queries
- Excellent TypeScript integration
- Migration system out of the box
- Intuitive schema definition
- Great developer experience with Prisma Studio
yarn nest generate module modules/feature-nameyarn nest generate service modules/feature-name/application/feature-nameyarn nest generate controller modules/feature-name/presentation/controllers/feature-nameyarn prisma migrate dev --name migration_nameyarn prisma migrate reset| 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 |
| 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 |
- β 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)
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
- Follow the coding guidelines in
docs/ - Write tests for new features
- Use conventional commits (see
docs/git-commit-instructions.md) - Ensure all tests pass before submitting PR
- Update documentation as needed
Comprehensive guides for development:
docs/git-commit-instructions.md- Git commit conventionsdocs/architecture.md- Architecture and design patternsdocs/typescript.md- TypeScript best practicesdocs/testing.md- Testing guidelinesdocs/yarn-package-management.md- Package managementdocs/prisma-best-practices.md- Database schema guidelinesdocs/github-actions-ci-cd.md- Detailed CI/CD documentationdocs/docker-setup.md- Docker quick start guidedocs/docker-nestjs.md- Docker best practices and advanced configurations