Skip to content

Introducing Espresso.JS, your ultimate Express configuration starting point and boilerplate. With its simplicity and lack of opinionation, EspressoJS offers plug-and-play configurations built on top of Express.

Notifications You must be signed in to change notification settings

misterzik/Espresso.js

Repository files navigation

Espresso

EspressoJS

A modern, production-ready Express.js boilerplate with built-in security, logging, and best practices.

npm version License: MIT

πŸš€ Features

  • ⚑ Quick Setup - Get your Express server running in seconds
  • πŸ”’ Security First - Helmet, rate limiting, and CORS pre-configured
  • πŸ“ Advanced Logging - Winston logger with file and console transports
  • πŸ›‘οΈ Error Handling - Centralized error handling middleware
  • πŸ”§ Configuration Management - JSON-based config with validation
  • πŸ’Ύ MongoDB Ready - Optional MongoDB integration with Mongoose
  • πŸ₯ Health Checks - Built-in health, readiness, and liveness endpoints
  • 🎯 CLI Tools - Powerful command-line interface for management
  • πŸ”„ Graceful Shutdown - Proper cleanup of resources on exit
  • πŸ“¦ Production Ready - Compression, caching, and optimization built-in

πŸ“‹ Requirements

  • Node.js >= 14.x
  • npm >= 6.x

πŸ“¦ Installation

npm install --save @misterzik/espressojs

🎯 Quick Start

1. Initialize Configuration

node cli init

This creates a config.json file with default settings:

{
  "instance": "development",
  "port": 8080,
  "hostname": "",
  "mongoDB": {
    "enabled": false,
    "port": null,
    "uri": "",
    "instance": "database"
  },
  "api": {
    "enabled": false,
    "uri": "",
    "url": "",
    "method": "GET",
    "headers": {
      "Content-Type": "application/json"
    }
  }
}

2. Create Environment File (Optional)

Create a .env file for sensitive data:

MONGO_USER=your_username
MONGO_TOKEN=your_password
API_TOKEN=your_api_token
NODE_ENV=development

3. Create Your Main File

Create index.js or espresso.js:

require("@misterzik/espressojs");

4. Create CLI File

Create cli.js:

require('@misterzik/espressojs/cli');

5. Run Your Server

Method 1: Using CLI (Recommended)

# Using the CLI
node cli run

# Or using npm scripts
npm start

Method 2: Direct Execution

node index.js

Method 3: Programmatic Usage (v3.3.6+)

If you're requiring EspressoJS as a module in your own code:

// Option A: Use built-in startServer (recommended)
const { startServer } = require('@misterzik/espressojs');
startServer();

// Option B: Manual control
const app = require('@misterzik/espressojs');
const config = require('@misterzik/espressojs/server');
app.listen(config.port, () => {
  console.log(`Server running on port ${config.port}`);
});

Note: If you're using EspressoJS programmatically (requiring it as a module), the server won't auto-start. You must either call startServer() or manually use app.listen(). See Usage Patterns Guide for details.

πŸ› οΈ CLI Commands

EspressoJS comes with a powerful CLI for managing your application:

# Show current configuration
node cli show

# Run the server
node cli run

# Run with auto-restart (development)
npm run start:watch

# Update environment settings
node cli env --instance=production --port=3000

# Validate configuration
node cli validate

# Initialize new config
node cli init

# Validate configuration
node cli validate

# Show version information
node cli version

# Get help
node cli --help

npm Scripts

EspressoJS provides convenient npm scripts for common tasks:

# Start server
npm start                    # Start with current config
npm run start:watch          # Start with auto-restart (nodemon)

# Development
npm run dev                  # Start in development mode
npm run dev:watch            # Dev mode with auto-restart

# Production
npm run prod                 # Start in production mode

# Configuration
npm run show                 # Display current config
npm run validate             # Validate config.json

Process Management:

The CLI uses a parent-child process model to keep your server running:

  • Parent process (CLI) manages the server lifecycle
  • Child process runs the Express application
  • process.stdin.resume() keeps the event loop active
  • Press CTRL+C for graceful shutdown

For more details, see CLI Usage Documentation.

πŸ“ Project Structure

your-project/
β”œβ”€β”€ config.json              # Configuration file
β”œβ”€β”€ .env                     # Environment variables
β”œβ”€β”€ index.js                 # Main application file
β”œβ”€β”€ cli.js                   # CLI entry point
β”œβ”€β”€ public/                  # Static files
β”‚   β”œβ”€β”€ index.html
β”‚   └── favicon.ico
β”œβ”€β”€ routes/                  # Custom routes
β”‚   β”œβ”€β”€ api.js
β”‚   └── db.js
└── logs/                    # Application logs (auto-created)
    β”œβ”€β”€ combined.log
    β”œβ”€β”€ error.log
    β”œβ”€β”€ exceptions.log
    └── rejections.log

πŸ”§ Configuration

Environment Instances

EspressoJS supports three pre-configured environments:

  • development - Development mode with debug logging
  • production - Production mode with optimized settings
  • global - Global/staging environment

Configuration Options

Option Type Description Default
instance string Environment instance development
port number Server port 8080
hostname string Server hostname ""
publicDirectory string Public files directory "/public"
mongoDB.enabled boolean Enable MongoDB false
mongoDB.uri string MongoDB URI ""
mongoDB.port number MongoDB port null
mongoDB.instance string Database name database
api.enabled boolean Enable API routes false
api.uri string External API URI ""
api.method string HTTP method GET
api.headers object Request headers {"Content-Type": "application/json"}
api.timeout number Request timeout (ms) 30000
api.retries number Retry attempts (0-5) 0

Multiple API Endpoints

EspressoJS supports multiple API configurations using the pattern api, api2, api3, etc.:

{
  "api": {
    "enabled": true,
    "uri": "https://api.example.com/v1/",
    "method": "GET",
    "headers": {
      "Content-Type": "application/json"
    }
  },
  "api2": {
    "uri": "https://api.example.com/v1/news",
    "method": "GET",
    "headers": {
      "Content-Type": "application/json",
      "Authorization": "Bearer TOKEN"
    }
  },
  "api3": {
    "enabled": true,
    "uri": "https://api.example.com/api",
    "method": "POST"
  }
}

Using Multiple APIs in Your Code:

const { apiManager } = require('./index');

// Request from specific API
const data = await apiManager.request('api2', '/endpoint');

// Parallel requests
const [data1, data2] = await Promise.all([
  apiManager.request('api', '/users'),
  apiManager.request('api2', '/news')
]);

// Check if API exists
if (apiManager.hasAPI('api3')) {
  const data = await apiManager.request('api3', '/data');
}

πŸ“– Full Multiple APIs Guide

πŸ₯ Health Check Endpoints

EspressoJS includes built-in health check endpoints:

  • GET /health - Comprehensive health check with system metrics
  • GET /ready - Readiness probe for orchestration
  • GET /alive - Liveness probe for monitoring

Example response from /health:

{
  "status": "OK",
  "timestamp": "2024-01-01T00:00:00.000Z",
  "uptime": 123.456,
  "environment": "development",
  "memory": {
    "total": 16777216000,
    "free": 8388608000,
    "usage": {...}
  },
  "cpu": {
    "cores": 8,
    "loadAverage": [1.5, 1.3, 1.2]
  },
  "database": {
    "status": "connected",
    "name": "myDatabase"
  }
}

πŸ”’ Security Features

EspressoJS includes enterprise-grade security features:

  • Helmet.js - Sets secure HTTP headers
  • Rate Limiting - Prevents abuse and DDoS attacks
  • CORS - Configurable cross-origin resource sharing
  • Input Validation - Express-validator integration
  • XSS Protection - Cross-site scripting prevention
  • Content Security Policy - CSP headers configured

πŸ“ Logging

Winston-based logging with multiple transports:

const logger = require('./server/utils/logger');

logger.info('Information message');
logger.warn('Warning message');
logger.error('Error message');
logger.debug('Debug message');
logger.http('HTTP request');

Logs are automatically written to:

  • Console (formatted with colors)
  • logs/combined.log (all logs)
  • logs/error.log (errors only)
  • logs/exceptions.log (uncaught exceptions)
  • logs/rejections.log (unhandled rejections)

πŸ”Œ MongoDB Integration

Enable MongoDB in your config.json:

{
  "mongoDB": {
    "enabled": true,
    "uri": "cluster0.mongodb.net",
    "port": null,
    "instance": "myDatabase"
  }
}

Set credentials in .env:

MONGO_USER=your_username
MONGO_TOKEN=your_password

πŸ›£οΈ Custom Routes

Create custom routes in the routes/ directory:

routes/api.js:

const express = require('express');
const router = express.Router();

router.get('/users', (req, res) => {
  res.json({ users: [] });
});

module.exports = router;

πŸš€ Deployment

Production Mode

# Set production environment
node cli env --instance=production --port=80

# Run in production
npm run prod

Environment Variables

Set these in production:

NODE_ENV=production
PORT=80
MONGO_USER=prod_user
MONGO_TOKEN=prod_password

πŸ“Š NPM Scripts

{
  "scripts": {
    "start": "node cli run",
    "dev": "node cli env --instance=development --port=8080 && node cli run",
    "prod": "node cli env --instance=production --port=80 && node cli run",
    "show": "node cli show"
  }
}

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“„ License

MIT Β© MisterZik

πŸ”— Links

πŸ’‘ Support

If you find EspressoJS helpful, please consider giving it a ⭐ on GitHub!

About

Introducing Espresso.JS, your ultimate Express configuration starting point and boilerplate. With its simplicity and lack of opinionation, EspressoJS offers plug-and-play configurations built on top of Express.

Topics

Resources

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors 2

  •  
  •