A robust, scalable Express.js API with TypeScript, featuring a clean module-based architecture, user CRUD operations, and comprehensive authentication with validation.
- β Module-Based Architecture - Clean, scalable, feature-based code organization
- β User CRUD Operations - Create, Read, Update, Delete users
- β JWT Authentication - Secure token-based authentication
- β Password Hashing - Bcrypt for secure password storage
- β Input Validation - Express-validator for request validation
- β Error Handling - Centralized error handling middleware
- β Role-Based Access Control - User and Admin roles
- β Rate Limiting - Protection against brute force attacks
- β Security Headers - Helmet.js for security
- β MongoDB Integration - Mongoose ODM
- β TypeScript - Full type safety
- β Vercel Ready - Serverless function deployment
express-api/
ββ api/
β ββ index.ts # Vercel serverless entry point
ββ src/
β ββ modules/ # Feature modules (self-contained)
β β ββ auth/ # Authentication module
β β β ββ auth.controller.ts # Auth request handlers
β β β ββ auth.service.ts # Auth business logic
β β β ββ auth.routes.ts # Auth route definitions
β β β ββ auth.types.ts # Auth-specific types/DTOs
β β β ββ auth.validations.ts # Auth validation rules
β β β ββ index.ts # Module exports
β β β
β β ββ user/ # User management module
β β ββ user.controller.ts # User request handlers
β β ββ user.service.ts # User business logic
β β ββ user.routes.ts # User route definitions
β β ββ user.types.ts # User-specific types/DTOs
β β ββ user.validations.ts # User validation rules
β β ββ index.ts # Module exports
β β
β ββ services/ # Shared services
β β ββ jwt.service.ts # JWT token operations
β β
β ββ middleware/ # Express middleware
β β ββ auth.middleware.ts # JWT authentication middleware
β β ββ error.middleware.ts # Error handling middleware
β β ββ validation.middleware.ts # Request validation middleware
β β
β ββ models/ # Database models
β β ββ User.ts # User model/schema
β β
β ββ config/ # Configuration files
β β ββ db.ts # Database configuration
β β
β ββ shared/ # Shared utilities & constants
β β ββ constants/
β β β ββ index.ts # All constants (HTTP status, errors, etc.)
β β ββ types/
β β β ββ index.ts # Shared TypeScript types
β β ββ helpers/
β β β ββ response.helper.ts # API response helpers
β β β ββ pagination.helper.ts # Pagination utilities
β β ββ utils/
β β ββ logger.ts # Logging utility
β β
β ββ views/ # HTML views
β β ββ index.html # API documentation page
β β
β ββ app.ts # Express app setup
ββ scripts/
β ββ copy-views.js # Build script for copying views
ββ vercel.json # Vercel configuration
ββ package.json
The project follows a module-based architecture where each feature is self-contained in its own module. Each module includes:
- Controller - Handles HTTP requests and responses
- Service - Contains business logic
- Routes - Defines API endpoints
- Types - Module-specific TypeScript interfaces and DTOs
- Validations - Request validation rules
- Index - Centralized exports for clean imports
- π― Scalability - Easy to add new features without affecting existing code
- π§ Maintainability - Related code is grouped together
- π§ͺ Testability - Modules can be tested independently
- π¦ Reusability - Modules can be easily extracted or moved
- π¨ Clean Code - Clear separation of concerns
- Create a new folder in
src/modules/[module-name]/ - Add the required files:
[module].controller.ts[module].service.ts[module].routes.ts[module].types.ts[module].validations.tsindex.ts
- Import and use in
app.ts:import { moduleRoutes } from "./modules/[module-name]"; app.use("/api/[module]", moduleRoutes);
- Node.js 18+
- Yarn (recommended package manager)
- MongoDB (local or cloud instance)
Install Yarn globally if you haven't already:
npm install -g yarn
# or
corepack enable- Clone the repository
- Install dependencies:
yarn install- Create a
.envfile based on.env.example:
cp .env.example .env- Update the
.envfile with your configuration:- Set
MONGODB_URIto your MongoDB connection string - Set
JWT_SECRETto a strong random string - Configure other environment variables as needed
- Set
Run the development server:
yarn devThe server will start on http://localhost:8080 (or the port specified in .env).
Visit http://localhost:8080/ to see the beautiful API documentation page.
POST /api/auth/register- Register a new userPOST /api/auth/login- Login userGET /api/auth/me- Get current user (requires authentication)
GET /api/users- Get all users (paginated)- Query params:
?page=1&limit=10
- Query params:
GET /api/users/:id- Get user by IDPOST /api/users- Create user (admin only)PUT /api/users/:id- Update userDELETE /api/users/:id- Delete user (admin only, soft delete)
GET /health- Server health checkGET /- API documentation page (HTML)
Request:
POST /api/auth/register
{
"name": "John Doe",
"email": "john@example.com",
"password": "Password123",
"role": "user"
}Response:
{
"success": true,
"data": {
"user": {
"id": "...",
"name": "John Doe",
"email": "john@example.com",
"role": "user"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}Request:
POST /api/auth/login
{
"email": "john@example.com",
"password": "Password123"
}Response:
{
"success": true,
"data": {
"user": {
"id": "...",
"name": "John Doe",
"email": "john@example.com",
"role": "user"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}Request:
GET /api/users?page=1&limit=10
Headers: Authorization: Bearer <token>Response:
{
"success": true,
"data": {
"users": [...],
"pagination": {
"page": 1,
"limit": 10,
"total": 50,
"pages": 5
}
}
}All protected routes require a JWT token in the Authorization header:
Authorization: Bearer <your-jwt-token>
- Minimum 6 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one number
- Must be a valid email format
- Automatically normalized (lowercase, trimmed)
- 2-50 characters
- Trimmed
All errors follow a consistent format:
{
"success": false,
"error": {
"message": "Error message here"
}
}Validation errors include field-specific information:
{
"success": false,
"error": {
"message": "Validation failed"
},
"data": {
"errors": [
{
"field": "email",
"message": "Please provide a valid email address"
}
]
}
}- Install Vercel CLI:
yarn global add vercel
# or
npm i -g vercel- Deploy:
vercel- Set environment variables in Vercel dashboard:
MONGODB_URIJWT_SECRETCORS_ORIGINJWT_EXPIRES_IN
yarn dev- Start development serveryarn build- Build for production (compiles TypeScript and copies views)yarn start- Start production serveryarn vercel-build- Build for Vercel deploymentyarn vercel-dev- Run Vercel development serveryarn lint- Run ESLintyarn type-check- Type check without building
This project uses Yarn as the package manager for several advantages:
- β‘ Fast & Reliable - Deterministic installs with lockfile
- π Secure - Better security auditing and vulnerability detection
- π¦ Workspaces - Excellent monorepo support
- π― Mature - Stable and widely adopted in production environments
- π Offline Mode - Can work offline with cached packages
The shared/ folder contains reusable utilities:
- constants/ - HTTP status codes, error messages, default values
- types/ - Shared TypeScript interfaces and types
- helpers/ - Response helpers, pagination utilities
- utils/ - Logging and other utilities
The services/ folder contains shared services used across modules:
jwt.service.ts- JWT token generation and verification
The middleware/ folder contains Express middleware:
auth.middleware.ts- JWT authenticationerror.middleware.ts- Centralized error handlingvalidation.middleware.ts- Request validation
- Password hashing with bcrypt
- JWT token authentication
- Rate limiting (100 requests per 15 minutes per IP)
- Helmet.js security headers
- CORS configuration
- Input validation and sanitization
- Role-based access control
- Soft delete for users
- Runtime: Node.js
- Framework: Express.js
- Language: TypeScript
- Database: MongoDB with Mongoose
- Authentication: JWT (jsonwebtoken)
- Validation: express-validator
- Security: Helmet, bcryptjs, express-rate-limit
- Deployment: Vercel (Serverless)
ISC