Mα»t boilerplate Express.js API hoΓ n chα»nh sα» dα»₯ng TypeScript, PostgreSQL, Prisma ORM, JWT authentication, vΓ Swagger documentation.
- 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
- Node.js 18+
- PostgreSQL 13+
- Redis 6+
- Docker & Docker Compose (optional)
git clone <repository-url>
cd express-ts-apinpm installcp .env.example .envChα»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# Generate Prisma client
npx prisma generate
# Run migrations
npx prisma migrate dev
# Seed database (optional)
npm run seed# Development
npm run dev
# Production
npm run build
npm start# 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:8080Services Δược include:
- app: Express API server
- postgres: PostgreSQL database
- redis: Redis cache
- adminer: Database management UI (port 8080)
# Build image
docker build -t express-ts-api .
# Run container
docker run -p 3000:3000 --env-file .env express-ts-apiSau khi chαΊ‘y server, truy cαΊp:
- API Documentation: http://localhost:3000/api-docs
- Health Check: http://localhost:3000/health
- API Base URL: http://localhost:3000/api
POST /api/auth/register- ΔΔng kΓ½ tΓ i khoαΊ£n mα»iPOST /api/auth/login- ΔΔng nhαΊpPOST /api/auth/refresh- LΓ m mα»i access tokenPOST /api/auth/logout- ΔΔng xuαΊ₯tPOST /api/auth/forgot-password- QuΓͺn mαΊt khαΊ©uPOST /api/auth/reset-password- ΔαΊ·t lαΊ‘i mαΊt khαΊ©uPOST /api/auth/verify-email- XΓ‘c thα»±c emailPOST /api/auth/resend-verification- Gα»i lαΊ‘i email xΓ‘c thα»±c
GET /api/users/me- LαΊ₯y thΓ΄ng tin ngΖ°α»i dΓΉng hiα»n tαΊ‘iPUT /api/users/me- CαΊp nhαΊt thΓ΄ng tin ngΖ°α»i dΓΉng hiα»n tαΊ‘iPUT /api/users/change-password- Δα»i mαΊt khαΊ©uPOST /api/users/upload-avatar- Upload avatarDELETE /api/users/avatar- XΓ³a avatarPATCH /api/users/theme- CαΊp nhαΊt chα»§ Δα» giao diα»nPATCH /api/users/language- CαΊp nhαΊt ngΓ΄n ngα»―DELETE /api/users/delete-account- XΓ³a tΓ i khoαΊ£n
POST /api/auth/register
{
"name": "John Doe",
"email": "john.doe@example.com",
"password": "password123",
"confirmPassword": "password123"
}POST /api/auth/login
{
"email": "john.doe@example.com",
"password": "password123"
}ThΓͺm header Authorization:
Authorization: Bearer <access_token># 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:integrationexpress_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
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 databaseNODE_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 application
npm run build
# Start production server
npm start- 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
- 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
{
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
}{
id: string(CUID);
token: string(unique);
userId: string;
expiresAt: DateTime;
createdAt: DateTime;
}- Fork repository
- TαΊ‘o feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - TαΊ‘o Pull Request
MIT License - xem file LICENSE Δα» biαΊΏt thΓͺm chi tiαΊΏt.
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! π