A modern, production-ready Express.js boilerplate with built-in security, logging, and best practices.
- β‘ 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
- Node.js >= 14.x
- npm >= 6.x
npm install --save @misterzik/espressojsnode cli initThis 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"
}
}
}Create a .env file for sensitive data:
MONGO_USER=your_username
MONGO_TOKEN=your_password
API_TOKEN=your_api_token
NODE_ENV=developmentCreate index.js or espresso.js:
require("@misterzik/espressojs");Create cli.js:
require('@misterzik/espressojs/cli');Method 1: Using CLI (Recommended)
# Using the CLI
node cli run
# Or using npm scripts
npm startMethod 2: Direct Execution
node index.jsMethod 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 useapp.listen(). See Usage Patterns Guide for details.
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 --helpEspressoJS 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.jsonProcess 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+Cfor graceful shutdown
For more details, see CLI Usage Documentation.
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
EspressoJS supports three pre-configured environments:
- development - Development mode with debug logging
- production - Production mode with optimized settings
- global - Global/staging environment
| 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 |
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');
}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"
}
}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
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)
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_passwordCreate 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;# Set production environment
node cli env --instance=production --port=80
# Run in production
npm run prodSet these in production:
NODE_ENV=production
PORT=80
MONGO_USER=prod_user
MONGO_TOKEN=prod_password{
"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"
}
}Contributions are welcome! Please feel free to submit a Pull Request.
MIT Β© MisterZik
If you find EspressoJS helpful, please consider giving it a β on GitHub!
