ExpressJS VidLab API Skeleton

A modern, production-ready Express.js API skeleton with international standards, built-in validation, and comprehensive error handling.
🚀 Features
- ✅ Modern ES Modules - Full ESM support with clean imports
- ✅ Validation - Express-validator integration with standardized error responses
- ✅ Response Trait - Consistent API response formatting with comprehensive methods
- ✅ Security - Multi-layered security headers, sanitization, and protection middleware
- ✅ Error Handling - Comprehensive error handling with proper logging and graceful degradation
- ✅ Environment Config - Centralized configuration management with validation
- ✅ Graceful Shutdown - Proper server lifecycle management with cleanup
- ✅ Compression - Response compression for better performance
- ✅ Request Logging - Detailed request logging with configurable levels
- ✅ Health Monitoring - Multiple health check endpoints with system metrics
- ✅ Utility Functions - Comprehensive utility library for common operations
- ✅ Rate Limiting - Built-in rate limiting middleware (configurable)
- ✅ Request Sanitization - Input sanitization to prevent injection attacks
- ✅ Comprehensive Testing - High test coverage with multiple test suites
📋 Prerequisites
🛠️ Installation
📁 Project Structure
src/
├── config/ # Configuration management
│ └── index.js # Centralized config with validation
├── controllers/ # Request handlers
│ └── VersionController.js
├── middleware/ # Custom middleware
│ ├── logger.js # Request logging middleware
│ └── security.js # Security middleware collection
├── repositories/ # Data access layer
│ └── VersionRepository.js
├── routes/ # API routes
│ ├── index.js # Route aggregator
│ └── VersionRoute.js # Version-specific routes
├── traits/ # Reusable utilities
│ └── ResponseTrait.js # Standardized API responses
├── utils/ # Common utility functions
│ └── index.js # Helper functions and utilities
├── validators/ # Request validation
│ └── VersionValidator.js
├── index.js # Application configuration
└── server.js # Server startup and lifecycle
.vscode/ # VS Code workspace configuration
├── settings.json # Editor settings and preferences
├── tasks.json # Build and development tasks
├── launch.json # Debug configurations
├── extensions.json # Recommended extensions
├── keybindings.json # Custom keyboard shortcuts
├── api-schema.json # API request/response schemas
├── javascript.json # JavaScript-specific settings
└── expressjs-vidlab-skeleton.code-workspace # Workspace file
🔧 VS Code Integration
This project includes comprehensive VS Code configuration for optimal development experience:
Workspace Configuration
- Settings: Consistent formatting, linting, and editor behavior
- Tasks: Automated build, test, and development workflows
- Debug: Pre-configured debugging for server and tests
- Extensions: Recommended extensions for enhanced productivity
- Keybindings: Custom shortcuts for common development tasks
📝 Note: The .vscode/
folder is included in version control to ensure all team members have a consistent development environment. Personal settings can be overridden using .vscode/settings.local.json
(ignored by git).
Personal Settings Override
To customize VS Code settings without affecting the team configuration:
- Copy
.vscode/settings.local.example.json
to .vscode/settings.local.json
- Add your personal preferences to
settings.local.json
- Your local settings will override team settings (file is ignored by git)
Quick Start with VS Code
- Open the workspace file:
.vscode/expressjs-vidlab-skeleton.code-workspace
- Install recommended extensions when prompted
- Use
Ctrl+Shift+D
to start development server
- Use
Ctrl+Shift+T
to run tests
- Use
F5
to debug the application
Available Tasks (Ctrl+Shift+P → "Tasks: Run Task")
- Start Development Server - Launch with hot reload
- Run Tests - Execute test suite
- Run Tests with Coverage - Tests with coverage report
- Health Check - Verify server health
- Lint Code - Code quality analysis
- Format Code - Auto-format all files
Debug Configurations
- Launch Development Server - Debug the main application
- Debug Tests - Debug Jest test suites
- Debug Current Test File - Debug specific test file
- Debug Specific Test - Debug individual test cases
🔧 API Endpoints
Version Management & Health Check
POST /api/version
- Get version information for specific instance (also serves as health check)
GET /api/version/all
- Get version information for all instances
GET /api/version/health
- Comprehensive health check with system metrics
GET /api/version/ping
- Simple ping/pong endpoint for availability check
Root Endpoint
GET /
- API information and available endpoints
Example Request (POST /api/version):
POST /api/version
Content-Type: application/json
{
"instance": "production"
}
Example Response:
{
"success": true,
"status": 200,
"message": "Version retrieved successfully",
"data": {
"version": "1.0.0",
"instance": "production",
"timestamp": "2025-07-14T10:30:00.000Z",
"environment": "development"
},
"timestamp": "2025-07-14T10:30:00.000Z"
}
Health Check Response (GET /api/version/health):
{
"success": true,
"status": 200,
"message": "Application is healthy",
"data": {
"status": "healthy",
"version": "1.0.0",
"response_time_ms": 5,
"timestamp": "2025-07-14T10:30:00.000Z",
"environment": "development",
"uptime": 3600.123,
"memory_usage": {
"rss": 52428800,
"heapTotal": 20971520,
"heapUsed": 18874368,
"external": 1879048
}
},
"timestamp": "2025-07-14T10:30:00.000Z"
}
📝 Response Format
All API responses follow a consistent format:
Success Response
{
"success": true,
"status": 200,
"message": "Operation successful",
"data": { ... },
"timestamp": "2025-07-14T10:30:00.000Z"
}
Error Response
{
"success": false,
"status": 400,
"message": "Error description",
"errors": [
{
"field": "fieldName",
"message": "Error message",
"value": "invalid-value"
}
],
"timestamp": "2025-07-14T10:30:00.000Z"
}
🔒 Security Features
- Security Headers - XSS protection, content type options, frame options
- Input Validation - Comprehensive request validation
- Error Sanitization - Safe error messages in production
🌍 Environment Variables
Key environment variables (see .env
for complete list):
# Server Configuration
PORT=3000
NODE_ENV=development
🧪 Development
Available Scripts
yarn start
yarn dev
yarn test
yarn test:watch
yarn test:coverage
yarn test:ci
yarn health
yarn clean
yarn lint
yarn format
yarn security
yarn docs
Testing
This project includes comprehensive testing with Jest and Supertest.
Running Tests
yarn test
yarn test:watch
yarn test:coverage
yarn test:ci
Test Structure
test/
├── setup.js # Global test configuration
├── version.test.js # Original version endpoint tests
├── enhanced-version.test.js # Enhanced version endpoint tests
├── response-trait.test.js # ResponseTrait utility tests
├── config.test.js # Configuration management tests
└── utils.test.js # Utility functions tests
Test Coverage
The project maintains high test coverage with the following achievements:
- Statements: 93.18%
- Functions: 100%
- Lines: 95.12%
- Branches: 58%
Coverage Thresholds
The project enforces minimum coverage thresholds:
- Branches: 40%
- Functions: 40%
- Lines: 40%
- Statements: 40%
What's Tested
- ✅ Version Endpoint: All success and error scenarios with enhanced functionality
- ✅ Health Checks: Comprehensive health monitoring with system metrics
- ✅ Response Format: Consistent API response structure across all endpoints
- ✅ Validation: Request body validation with express-validator
- ✅ Error Handling: Malformed requests and server errors
- ✅ Performance: Response time validation and optimization
- ✅ 404 Handling: Unknown route responses
- ✅ Configuration: Environment configuration and validation
- ✅ Utilities: All utility functions with edge cases
- ✅ Security: Input sanitization and security headers
- ✅ Rate Limiting: Request throttling and limiting functionality
Test Examples
it('should return version information with valid instance', async () => {
const response = await request(app)
.post('/api/version')
.send({ instance: 'production' })
.expect(200);
expect(response.body).toHaveProperty('success', true);
expect(response.body.data).toHaveProperty('version');
});
CI/CD Integration
Tests are automatically run in CI/CD pipeline with:
- Multi-Node testing (Node 18.x, 20.x)
- Coverage reporting with Codecov
- Quality gates before deployment
- Automated testing on push/PR
Test Configuration
Jest is configured with:
- ES Modules support via Babel
- Supertest for HTTP endpoint testing
- Coverage collection from
src/
directory
- Setup/teardown handling for clean test runs
Adding New Routes
- Create Controller in
src/controllers/
- Create Repository in
src/repositories/
(if needed)
- Create Validator in
src/validators/
- Create Route in
src/routes/
- Register Route in
src/routes/index.js
Example Controller Pattern
import { ResponseTrait } from '../traits/ResponseTrait.js';
class ExampleController {
async getExample(req, res) {
try {
return ResponseTrait.success(res, data, 'Success message');
} catch (error) {
console.error('Error:', error);
return ResponseTrait.serverError(res, 'Error message');
}
}
}
export default ExampleController;
📊 Logging
The application includes comprehensive logging:
- Request Logging - All incoming requests with timestamps
- Error Logging - Detailed error information
- Graceful Shutdown - Server lifecycle events
🚀 Deployment
Production Checklist
🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
)
- Commit your changes (
git commit -m 'Add amazing feature'
)
- Push to the branch (
git push origin feature/amazing-feature
)
- Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
👥 Authors
- VidLab Team - Initial work
🙏 Acknowledgments
- Express.js community
- Node.js ecosystem
- All contributors
Built with ❤️ by VidLab Team