Skip to content

hodela/express_ts

Repository files navigation

Express TypeScript API Boilerplate

Mα»™t boilerplate Express.js API hoΓ n chỉnh sα»­ dα»₯ng TypeScript, PostgreSQL, Prisma ORM, JWT authentication, vΓ  Swagger documentation.

πŸš€ TΓ­nh nΔƒng

  • TypeScript - Type safety vΓ  developer experience tα»‘t hΖ‘n
  • Express.js - Web framework nhanh vΓ  linh hoαΊ‘t
  • PostgreSQL + Prisma - Database vΓ  ORM hiện Δ‘αΊ‘i
  • JWT Authentication - Secure authentication vα»›i access/refresh tokens
  • Redis - Caching vΓ  session storage
  • Swagger/OpenAPI - API documentation tα»± Δ‘α»™ng
  • Rate Limiting - BαΊ£o vệ API khỏi abuse
  • Input Validation - Validation vα»›i express-validator
  • Error Handling - Centralized error handling
  • Logging - Structured logging vα»›i Pino
  • Testing - Unit vΓ  integration tests vα»›i Jest
  • Docker - Containerization cho development vΓ  production
  • Security - Helmet, CORS, vΓ  cΓ‘c security best practices
  • Email Service - Email integration vα»›i Resend

πŸ“‹ YΓͺu cαΊ§u

  • Node.js 18+
  • PostgreSQL 13+
  • Redis 6+
  • Docker & Docker Compose (optional)

πŸ› οΈ CΓ i Δ‘αΊ·t

1. Clone repository

git clone <repository-url>
cd express-ts-api

2. CΓ i Δ‘αΊ·t dependencies

npm install

3. CαΊ₯u hΓ¬nh environment variables

cp .env.example .env

Chỉnh sα»­a file .env vα»›i thΓ΄ng tin cα»§a bαΊ‘n:

NODE_ENV=development
PORT=3000

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/express_ts
TEST_DATABASE_URL=postgresql://user:password@localhost:5432/express_ts_test

# Redis
REDIS_URL=redis://localhost:6379

# JWT
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRE=7d

# Email
RESEND_API_KEY=your-resend-api-key
RESEND_FROM_EMAIL=your-email@gmail.com
RESEND_FROM_NAME=your-name

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100

# Logging
LOG_LEVEL=info

# File Upload
UPLOAD_ENGINE=local
UPLOAD_MAX_FILE_SIZE=5242880
UPLOAD_ALLOWED_EXTENSIONS=jpg,jpeg,png,gif,webp
UPLOAD_PATH=src/assets/upload
UPLOAD_URL_PREFIX=/uploads

4. Setup database

# Generate Prisma client
npx prisma generate

# Run migrations
npx prisma migrate dev

# Seed database (optional)
npm run seed

5. ChαΊ‘y α»©ng dα»₯ng

# Development
npm run dev

# Production
npm run build
npm start

🐳 Docker

Development vα»›i Docker Compose

# ChαΊ‘y tαΊ₯t cαΊ£ services
docker-compose up -d

# Chỉ chαΊ‘y database vΓ  Redis
docker-compose up -d postgres redis

# Xem logs
docker-compose logs -f app

# Truy cαΊ­p Adminer (database management)
# http://localhost:8080

Services được include:

  • app: Express API server
  • postgres: PostgreSQL database
  • redis: Redis cache
  • adminer: Database management UI (port 8080)

Production vα»›i Docker

# Build image
docker build -t express-ts-api .

# Run container
docker run -p 3000:3000 --env-file .env express-ts-api

πŸ“š API Documentation

Sau khi chαΊ‘y server, truy cαΊ­p:

πŸ” Authentication & APIs

Authentication Endpoints

  • POST /api/auth/register - Đăng kΓ½ tΓ i khoαΊ£n mα»›i
  • POST /api/auth/login - Đăng nhαΊ­p
  • POST /api/auth/refresh - LΓ m mα»›i access token
  • POST /api/auth/logout - Đăng xuαΊ₯t
  • POST /api/auth/forgot-password - QuΓͺn mαΊ­t khαΊ©u
  • POST /api/auth/reset-password - Đặt lαΊ‘i mαΊ­t khαΊ©u
  • POST /api/auth/verify-email - XΓ‘c thα»±c email
  • POST /api/auth/resend-verification - Gα»­i lαΊ‘i email xΓ‘c thα»±c

User Management Endpoints

  • GET /api/users/me - LαΊ₯y thΓ΄ng tin người dΓΉng hiện tαΊ‘i
  • PUT /api/users/me - CαΊ­p nhαΊ­t thΓ΄ng tin người dΓΉng hiện tαΊ‘i
  • PUT /api/users/change-password - Đổi mαΊ­t khαΊ©u
  • POST /api/users/upload-avatar - Upload avatar
  • DELETE /api/users/avatar - XΓ³a avatar
  • PATCH /api/users/theme - CαΊ­p nhαΊ­t chα»§ đề giao diện
  • PATCH /api/users/language - CαΊ­p nhαΊ­t ngΓ΄n ngα»―
  • DELETE /api/users/delete-account - XΓ³a tΓ i khoαΊ£n

Example Usage

Register

POST /api/auth/register
{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "password": "password123",
  "confirmPassword": "password123"
}

Login

POST /api/auth/login
{
  "email": "john.doe@example.com",
  "password": "password123"
}

Protected Routes

ThΓͺm header Authorization:

Authorization: Bearer <access_token>

πŸ§ͺ Testing

# Setup test database
npm run test:db:setup

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

# Run unit tests
npm run test:unit

# Run integration tests
npm run test:integration

πŸ“ CαΊ₯u trΓΊc Project

express_ts/
β”œβ”€β”€ .env.example               # Environment variables template
β”œβ”€β”€ .env                       # Environment variables (local)
β”œβ”€β”€ .gitignore                 # Git ignore rules
β”œβ”€β”€ .dockerignore              # Docker ignore rules
β”œβ”€β”€ .eslintrc.json             # ESLint configuration
β”œβ”€β”€ .prettierrc                # Prettier configuration
β”œβ”€β”€ .cursorrules               # Cursor IDE rules
β”œβ”€β”€ .cursorignore              # Cursor ignore rules
β”œβ”€β”€ package.json               # Dependencies and scripts
β”œβ”€β”€ package-lock.json          # Lock file for dependencies
β”œβ”€β”€ tsconfig.json              # TypeScript configuration
β”œβ”€β”€ jest.config.js             # Jest testing configuration
β”œβ”€β”€ Dockerfile                 # Docker container configuration
β”œβ”€β”€ docker-compose.yml         # Docker services configuration
β”œβ”€β”€ README.md                  # Project documentation
β”œβ”€β”€ SWAGGER.md                 # API documentation guide
β”œβ”€β”€ TESTING.md                 # Testing guide
β”œβ”€β”€ TASKS.md                   # Development tasks and features
β”œβ”€β”€ coverage/                  # Test coverage reports
β”œβ”€β”€ dist/                      # Compiled JavaScript files
β”œβ”€β”€ logs/                      # Application logs
β”œβ”€β”€ node_modules/              # Node.js dependencies
β”œβ”€β”€ src/                       # Source code
β”‚   β”œβ”€β”€ app.ts                 # Express app setup
β”‚   β”œβ”€β”€ server.ts              # Server entry point
β”‚   β”œβ”€β”€ config/                # Configuration files
β”‚   β”‚   β”œβ”€β”€ database.ts        # Prisma configuration
β”‚   β”‚   β”œβ”€β”€ redis.ts           # Redis configuration
β”‚   β”‚   β”œβ”€β”€ resend.ts          # Resend configuration
β”‚   β”‚   β”œβ”€β”€ logger.ts          # Pino logger setup
β”‚   β”‚   β”œβ”€β”€ upload.config.ts   # File upload configuration
β”‚   β”‚   └── swagger.ts         # Swagger configuration
β”‚   β”œβ”€β”€ controllers/           # Route controllers
β”‚   β”‚   β”œβ”€β”€ auth.controller.ts # Authentication controller
β”‚   β”‚   └── user.controller.ts # User management controller
β”‚   β”œβ”€β”€ middlewares/           # Express middlewares
β”‚   β”‚   β”œβ”€β”€ auth.middleware.ts        # JWT authentication
β”‚   β”‚   β”œβ”€β”€ error.middleware.ts       # Global error handler
β”‚   β”‚   β”œβ”€β”€ logging.middleware.ts     # Request logging
β”‚   β”‚   β”œβ”€β”€ notFound.middleware.ts    # 404 handler
β”‚   β”‚   β”œβ”€β”€ rateLimiter.middleware.ts # Rate limiting
β”‚   β”‚   β”œβ”€β”€ upload.middleware.ts      # File upload middleware
β”‚   β”‚   └── validation.middleware.ts  # Input validation
β”‚   β”œβ”€β”€ routes/                # Route definitions
β”‚   β”‚   β”œβ”€β”€ index.ts           # Main routes file
β”‚   β”‚   β”œβ”€β”€ auth.routes.ts     # Authentication routes
β”‚   β”‚   └── user.routes.ts     # User management routes
β”‚   β”œβ”€β”€ services/              # Business logic layer
β”‚   β”‚   β”œβ”€β”€ auth.service.ts    # Authentication service
β”‚   β”‚   β”œβ”€β”€ user.service.ts    # User management service
β”‚   β”‚   └── email.service.ts   # Email service (Resend)
β”‚   β”œβ”€β”€ services/upload/       # File upload services
β”‚   β”‚   β”œβ”€β”€ local-upload.service.ts # Local file upload service
β”‚   β”‚   └── upload.service.ts    # Upload service interface
β”‚   β”œβ”€β”€ utils/                 # Utility functions
β”‚   β”‚   β”œβ”€β”€ constants.ts       # Application constants
β”‚   β”‚   β”œβ”€β”€ helpers.ts         # Helper functions
β”‚   β”‚   └── validators.ts      # Custom validators
β”‚   β”œβ”€β”€ assets/                # Static assets
β”‚   β”‚   └── upload/            # Upload directory
β”‚   β”œβ”€β”€ templates/             # Email templates
β”‚   β”‚   β”œβ”€β”€ emails/            # Email templates
β”‚   β”‚   β”‚   β”œβ”€β”€ BaseEmailTemplate.tsx # Base email template
β”‚   β”‚   β”‚   β”œβ”€β”€ WelcomeEmail.tsx # Welcome email template
β”‚   β”‚   β”‚   β”œβ”€β”€ EmailVerificationEmail.tsx # Email verification email template
β”‚   β”‚   β”‚   └── PasswordResetEmail.tsx # Password reset email template
β”‚   β”œβ”€β”€ locales/               # Language files
β”‚   β”‚   β”œβ”€β”€ en.json            # English language file
β”‚   β”‚   └── vi.json            # Vietnamese language file
β”‚   └── types/                 # TypeScript type definitions
β”‚       β”œβ”€β”€ express.d.ts       # Express type extensions
β”‚       β”œβ”€β”€ upload.d.ts        # Upload type extensions
β”‚       └── index.ts           # Global type definitions
β”œβ”€β”€ tests/                     # Test files
β”‚   β”œβ”€β”€ setup.ts               # Test setup configuration
β”‚   β”œβ”€β”€ setup-integration.ts   # Integration test setup
β”‚   β”œβ”€β”€ jest-global.d.ts       # Jest global types
β”‚   β”œβ”€β”€ helpers/               # Test helper functions
β”‚   β”‚   β”œβ”€β”€ database.ts        # Database test helpers
β”‚   β”‚   └── mocks.ts           # Mock functions
β”‚   β”œβ”€β”€ unit/                  # Unit tests
β”‚   β”‚   β”œβ”€β”€ auth.service.test.ts   # Auth service tests
β”‚   β”‚   β”œβ”€β”€ user.service.test.ts   # User service tests
β”‚   β”‚   β”œβ”€β”€ email.service.test.ts  # Email service tests
β”‚   β”‚   └── helpers.test.ts        # Helper functions tests
β”‚   └── integration/           # Integration tests
β”‚       β”œβ”€β”€ auth.test.ts       # Authentication API tests
β”‚       └── user.test.ts       # User management API tests
β”œβ”€β”€ scripts/                   # Build and utility scripts
β”‚   β”œβ”€β”€ setup-test-db.ts       # Test database setup
β”‚   β”œβ”€β”€ migrate.ts             # Database migration script
β”‚   β”œβ”€β”€ seed.ts                # Database seeding script
β”‚   └── init-db.sql            # Database initialization SQL
└── prisma/                    # Prisma ORM files
    β”œβ”€β”€ schema.prisma          # Database schema definition
    └── migrations/            # Database migrations
        β”œβ”€β”€ migration_lock.toml     # Migration lock file
        β”œβ”€β”€ 20250608033536_init/    # Initial migration
        └── 20250608034053_update_user_schema/  # User schema update

πŸ”§ Scripts

npm run dev              # Start development server
npm run build            # Build for production
npm start                # Start production server
npm test                 # Run tests
npm run test:watch       # Run tests in watch mode
npm run test:coverage    # Run tests with coverage
npm run test:unit        # Run unit tests only
npm run test:integration # Run integration tests only
npm run test:db:setup    # Setup test database
npm run lint             # Run ESLint
npm run lint:fix         # Fix ESLint errors
npm run format           # Format code with Prettier
npm run migrate          # Run database migrations
npm run seed             # Seed database

πŸš€ Deployment

Environment Variables cho Production

NODE_ENV=production
PORT=3000
DATABASE_URL=postgresql://user:password@host:5432/database
REDIS_URL=redis://host:6379
JWT_SECRET=your-super-secure-secret-key
RESEND_API_KEY=your-production-resend-api-key
RESEND_FROM_EMAIL=noreply@yourdomain.com
RESEND_FROM_NAME=Your App Name
ALLOWED_ORIGINS=https://yourdomain.com

Build vΓ  Deploy

# Build application
npm run build

# Start production server
npm start

πŸ”’ Security Features

  • Helmet.js - Security headers
  • CORS - Cross-origin resource sharing
  • Rate Limiting - Request rate limiting
  • Input Validation - Request validation vα»›i express-validator
  • JWT Authentication - Secure token-based auth vα»›i refresh tokens
  • Password Hashing - bcrypt password hashing
  • SQL Injection Protection - Prisma ORM protection

πŸ“Š Monitoring & Logging

  • Health Check Endpoint - /health
  • Structured Logging - Pino logger vα»›i pretty printing
  • Error Tracking - Centralized error handling
  • Request Logging - Morgan HTTP logger
  • Performance Monitoring - Request timing logs

πŸ—„οΈ Database Schema

User Model

{
  id: string (CUID)
  name: string
  email: string (unique)
  password: string (hashed)
  avatar?: string
  theme: "light" | "dark" (default: "light")
  language: "vi" | "en" (default: "en")
  role: "user" | "admin" (default: "user")
  isVerified: boolean (default: false)
  verificationToken?: string
  verificationTokenExpiresAt?: DateTime
  resetPasswordToken?: string
  resetPasswordTokenExpiresAt?: DateTime
  lastLoginAt?: DateTime
  createdAt: DateTime
  updatedAt: DateTime
}

RefreshToken Model

{
  id: string(CUID);
  token: string(unique);
  userId: string;
  expiresAt: DateTime;
  createdAt: DateTime;
}

🀝 Contributing

  1. Fork repository
  2. TαΊ‘o feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. TαΊ‘o Pull Request

πŸ“ License

MIT License - xem file LICENSE để biαΊΏt thΓͺm chi tiαΊΏt.

πŸ†˜ Support

NαΊΏu bαΊ‘n gαΊ·p vαΊ₯n đề hoαΊ·c cΓ³ cΓ’u hỏi, vui lΓ²ng tαΊ‘o issue trΓͺn GitHub.


Happy Coding! πŸŽ‰

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors