Skip to content

dominik-myszkowski/boilerplate-backend-express

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Good2Order Backend API - Production-Ready Boilerplate

A comprehensive, production-ready Express.js backend boilerplate with TypeScript, featuring JWT authentication, file storage, email services, background jobs, and more.

✨ Features

πŸ” Authentication & Security

  • JWT Authentication - Stateless authentication with access and refresh tokens
  • Role-Based Access Control - Flexible role system for authorization
  • Password Reset & Email Verification - Complete user authentication flow
  • Rate Limiting - Redis-backed rate limiting for API endpoints
  • Strict Auth Rate Limits - 5 login attempts per 15min, 3 password resets per hour
  • Input Sanitization - MongoDB injection and XSS protection
  • Security Headers - Helmet with custom CSP configuration

πŸ“ File Management

  • Dual Storage Modes - S3 or local disk storage
  • Signed URLs - S3 pre-signed URLs for secure file access
  • File Streaming - Direct file streaming for local storage
  • User-Owned Files - Files scoped to uploading user
  • File Validation - Type and size restrictions via environment config

πŸ“§ Email & Messaging

  • Nodemailer Integration - SMTP email sending
  • Email Templates - Password reset, verification, and welcome emails
  • Background Processing - Bull queue for async email sending
  • Retry Logic - Automatic retry on email failures

πŸ—„οΈ Database

  • MongoDB with Mongoose - Full ODM with schemas and validations
  • Zod Schema Validation - Request validation with type safety
  • Connection Management - Graceful connection handling
  • Indexes - Optimized queries with proper indexing

πŸ”„ Background Jobs

  • Bull Queues - Redis-backed job queuing
  • Email Worker - Async email processing
  • Job Retry - Exponential backoff retry strategy
  • Queue Monitoring - Job statistics and health checks

πŸ“ Logging

  • Pino Logger - High-performance JSON logging
  • Log Rotation - Daily rotation with 30-day retention
  • Request Logging - Automatic HTTP request/response logging
  • Error Tracking - Comprehensive error logging

πŸ“š API Documentation

  • OpenAPI 3.0 - Auto-generated from Zod schemas
  • Swagger UI - Interactive API documentation
  • Type-Safe Routes - Validated requests and responses

πŸ—οΈ Architecture

  • Modular Structure - Feature-based organization
  • Clean Architecture - Router β†’ Controller β†’ Service β†’ Repository layers
  • TypeScript - Full type safety throughout
  • Path Aliases - Clean imports with @/ prefix

πŸ› οΈ Tech Stack

  • Runtime: Node.js (LTS)
  • Framework: Express.js
  • Language: TypeScript
  • Database: MongoDB with Mongoose
  • Cache/Queue: Redis with ioredis & Bull
  • Authentication: JWT with jsonwebtoken
  • Validation: Zod
  • File Storage: AWS S3 SDK / Local filesystem
  • Email: Nodemailer
  • Logging: Pino with rotation
  • Testing: Vitest
  • Code Quality: Biome
  • Documentation: OpenAPI 3.0 / Swagger

πŸ“‹ Prerequisites

  • Node.js (LTS version)
  • MongoDB (local or cloud)
  • Redis (local or cloud)
  • SMTP server credentials (for email)
  • AWS S3 credentials (optional, for S3 storage)

πŸš€ Quick Start

1. Install Dependencies

npm install

2. Start Services with Docker Compose

docker compose up -d

This starts MongoDB and Redis containers.

3. Configure Environment

Copy .env.example to .env and configure:

cp .env.example .env

Required configurations:

  • MONGO_URL - MongoDB connection string
  • REDIS_URL - Redis connection string
  • JWT_SECRET - Secret key for JWT tokens
  • SMTP_* - SMTP server credentials

Optional configurations:

  • UPLOAD_STORAGE_TYPE - local or s3 (default: local)
  • AWS credentials (if using S3)
  • Email verification settings

4. Start Development Server

npm run dev

Server will start on http://localhost:5000

πŸ“– API Endpoints

Authentication (/api/v1/auth)

  • POST /register - Register new user
  • POST /login - Login and get tokens
  • POST /refresh - Refresh access token
  • POST /logout - Logout and revoke tokens
  • POST /forgot-password - Request password reset
  • POST /reset-password - Reset password with token
  • POST /verify-email - Verify email address
  • POST /send-verification - Resend verification email

Users (/api/v1/users)

  • GET / - Get all users (protected)
  • GET /:id - Get user by ID
  • PATCH /:id - Update user
  • DELETE /:id - Delete user

Files (/api/v1/files)

  • POST /upload - Upload file (protected)
  • GET / - Get user's files (protected)
  • GET /:id - Get file metadata
  • GET /:id/download - Download file (S3 URL or stream)
  • DELETE /:id - Delete file (protected, user-owned)

Todos (/api/v1/todos)

  • GET / - Get all todos
  • GET /:id - Get todo by ID
  • POST / - Create todo
  • PATCH /:id - Update todo
  • DELETE /:id - Delete todo

Health (/api/v1/health-check)

  • GET / - Health check endpoint

πŸ”§ Environment Variables

See .env.example for complete list. Key variables:

# Server
NODE_ENV=development
PORT=5000
CORS_ORIGIN=http://localhost:5000

# MongoDB
MONGO_URL=mongodb://localhost:27017
DB_NAME=good2order_dev

# Redis
REDIS_URL=redis://localhost:6379

# JWT
JWT_SECRET=your-secret-key
JWT_ACCESS_EXPIRATION=15m
JWT_REFRESH_EXPIRATION=7d

# Email (SMTP)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
EMAIL_FROM=Good2Order <noreply@good2order.com>

# File Upload
UPLOAD_STORAGE_TYPE=local
UPLOAD_MAX_FILE_SIZE=5242880
UPLOAD_LOCAL_PATH=./uploads

# AWS S3 (if using S3 storage)
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=your-key
AWS_SECRET_ACCESS_KEY=your-secret
AWS_S3_BUCKET=your-bucket

πŸ§ͺ Testing

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

πŸ—οΈ Building for Production

# Build
npm run build

# Start production server
npm start

πŸ“ Scripts

  • npm run dev - Start development server with hot reload
  • npm run build - Build for production
  • npm start - Run production server
  • npm test - Run tests
  • npm run lint - Check code quality
  • npm run lint:fix - Fix linting issues
  • npm run format - Format code with Biome

πŸ—οΈ Project Structure

backend/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ api/                     # API modules
β”‚   β”‚   β”œβ”€β”€ user/               # User & auth
β”‚   β”‚   β”‚   β”œβ”€β”€ userModel.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ userSchema.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ userRepository.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ userService.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ userController.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ userRouter.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ authService.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ authController.ts
β”‚   β”‚   β”‚   └── authRouter.ts
β”‚   β”‚   β”œβ”€β”€ files/              # File management
β”‚   β”‚   └── todo/               # Example CRUD
β”‚   β”œβ”€β”€ common/
β”‚   β”‚   β”œβ”€β”€ middleware/         # Express middleware
β”‚   β”‚   β”‚   β”œβ”€β”€ authentication.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ authRateLimiter.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ upload.ts
β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”œβ”€β”€ services/           # Shared services
β”‚   β”‚   β”‚   β”œβ”€β”€ email/
β”‚   β”‚   β”‚   β”œβ”€β”€ storage/
β”‚   β”‚   β”‚   └── queue/
β”‚   β”‚   └── utils/              # Utilities
β”‚   β”‚       β”œβ”€β”€ redis.ts
β”‚   β”‚       β”œβ”€β”€ db.ts
β”‚   β”‚       └── envConfig.ts
β”‚   β”œβ”€β”€ api-docs/               # OpenAPI docs
β”‚   β”œβ”€β”€ index.ts                # App entry point
β”‚   └── server.ts               # Express setup
β”œβ”€β”€ logs/                       # Log files (rotated daily)
β”œβ”€β”€ uploads/                    # Local file uploads
β”œβ”€β”€ docker-compose.yml          # MongoDB & Redis
β”œβ”€β”€ .env.example                # Environment template
└── package.json

πŸ”’ Security Best Practices

  1. JWT Tokens stored in Redis for revocation
  2. Password Hashing with bcrypt (10 rounds)
  3. Rate Limiting on all endpoints
  4. Input Validation with Zod schemas
  5. MongoDB Injection prevention with sanitization
  6. XSS Protection with input cleaning
  7. Security Headers with Helmet
  8. CORS configured for specific origins

🚒 Deployment

Docker

docker build -t good2order-backend .
docker run -p 5000:5000 --env-file .env good2order-backend

Environment

Ensure production environment variables are set:

  • Use strong JWT_SECRET
  • Configure proper CORS_ORIGIN
  • Set NODE_ENV=production
  • Use production MongoDB/Redis instances
  • Configure SMTP for emails

🎯 Use Cases

This boilerplate is perfect for:

  • SaaS applications
  • Mobile app backends
  • API-first applications
  • Multi-user platforms
  • Content management systems
  • E-commerce backends

πŸ“„ License

MIT

πŸŽ‰ Happy coding!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages