You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

expressjs-vidlab-skeleton

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

expressjs-vidlab-skeleton

A modern, production-ready Express.js API skeleton with international standards, built-in validation, and comprehensive error handling

1.0.1
latest
Source
npmnpm
Version published
Maintainers
1
Created
Source

ExpressJS VidLab API Skeleton

Node.js Express.js License: MIT

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

  • Node.js 18+
  • yarn

🛠️ Installation

  • Clone the repository

    git clone git@github.com:appvidlab/expressjs-vidlab-skeleton.git
    cd expressjs-vidlab-skeleton
    
  • Install dependencies

    yarn install
    
  • Configure environment

    cp .env.example .env
    # Edit .env with your configurations
    
  • Start the server

    # Development mode
    yarn dev
    
    # Production mode
    yarn start
    

📁 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         # Start production server
yarn dev           # Start development server with nodemon
yarn test          # Run tests once
yarn test:watch    # Run tests in watch mode
yarn test:coverage # Run tests with coverage report
yarn test:ci       # CI optimized test run
yarn health        # Check server health status
yarn clean         # Clean temporary files and logs
yarn lint          # Run code linting (configure ESLint)
yarn format        # Format code (configure Prettier)
yarn security      # Run security audit (configure tools)
yarn docs          # Generate documentation (configure JSDoc)

Testing

This project includes comprehensive testing with Jest and Supertest.

Running Tests

# Run all tests
yarn test

# Run tests in watch mode (for development)
yarn test:watch

# Run tests with coverage report
yarn test:coverage

# Run tests for CI/CD (with coverage and no watch)
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

// Example test case
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 {
      // Your logic here
      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

  • Set NODE_ENV=production
  • Configure database connections
  • Set up proper logging
  • Configure reverse proxy (nginx)
  • Set up SSL certificates
  • Configure monitoring

🤝 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

Keywords

expressjs

FAQs

Package last updated on 14 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts