express-pack
v1.0.8
Published
express-pack is a powerful npm package designed to simplify setting up an Express.js application by integrating commonly used middleware like dotenv, winston, helmet, body-parser, and more. It eliminates the hassle of installing and configuring these esse
Maintainers
Keywords
Readme
express-pack
express-pack simplifies Express.js app creation by bundling common middleware and providing a straightforward configuration system. Perfect for new projects or rapid prototyping!
🚀 Features
- Pre-configured middleware:
- Environment management using
dotenv - Request logging with
winston - Security enhancements with
helmet - Body parsing with
body-parser
- Environment management using
- Simplified route management.
- Fully customizable via configuration files.
📦 Installation
Install the package using npm or yarn:
npm install express-pack
or
yarn add express-pack
🛠️ Usage
Project Setup Guide
⚙️ Easy Setup Instructions
After installation, when you run the setup, you will be prompted with configuration questions.
1️⃣ Enable Nodemon for Development
Do you want to use nodemon for development? (yes/no)
- **Yes** → Adds a dev script using nodemon.
- **No** → Uses node directly.
2️⃣ Generate Basic Express App Structure
Do you want to set up the basic Express app structure? (yes/no)
- **Yes** → Automatically creates a structured Express.js app with controllers, routes, and configuration files.
- **No** → Skips the setup and allows manual configuration.
📂 Project Structure
If you choose to set up the Express app, the following directory structure will be created:
/project-root
├── /src
│ ├── /featureName1
│ │ ├── /controllers
│ │ ├── /routes
│ │
│ ├── /featureName2
│ │ ├── /controllers
│ │ ├── /routes
├── /config
│ ├── appConfig.js
│ └── routeConfig.js
├── index.js
├── package.json
└── .env🚀 Running the Application
After setup, you can start the application using:
npm run dev # If nodemon is enabled
npm start # Runs the app with node🛠️ Configuration Files
- config/appConfig.js - Contains Express middleware configurations.
- config/routeConfig.js - Manages the routes for the application.
✨ Features
✅ Automatic project structure generation
✅ Support for nodemon for development
✅ Follows MVC architecture for clean code organization
✅ Quick setup with interactive prompts
Here’s how you can set up manualy and start using express-pack:
index.js / server.js
const { CreateApp, BindRoutes } = require("express-pack");
// routes arrays
const { routes } = require("./config/routeConfig");
// app config for express-pack
const { appConfig } = require("./config/appConfig");
// create app from express-pack
const app = CreateApp(appConfig);
// binding the routes with app
BindRoutes(routes);
app?.listen(3000, () => {
console.log("I am listening to 3000 port");
});Configuration
config/appConfig.js
Customize your application behavior with the appConfig object.
Example Configuration:
✅ Easily create a new Express app
✅ Automatically apply a pre-configured with standard default settings
✅ Set up essential middleware for CORS, logging, body parsing, and security
module.exports = {
appConfig: {
env: "development", // custom path for .env file
cors: {}, // CORS settings
logger: {}, // Logger configuration
bodyParser: {}, // Body parser settings
security: {}, // Security configurations
},
};📌 Configuration Options
Body Parser Configuration
Handles request body parsing.
| Option | Default Value | Description |
| ------------ | ------------------------------------------------------ | ------------------------- |
| json | { limit: "100kb" } | Limits JSON body size |
| urlencoded | { extended: true, limit: "100kb" } | Parses URL-encoded bodies |
| raw | { type: "application/octet-stream", limit: "100kb" } | Parses raw binary data |
| text | { type: "text/plain", limit: "100kb" } | Parses plain text |
Example Usage:
bodyParser: {
json: { limit: "1mb" },
urlencoded: { extended: true, limit: "500kb" },
},CORS Configuration
Manages cross-origin resource sharing.
| Option | Default Value | Description |
| ------------------- | --------------------------------------------------- | ------------------------------------ |
| methods | ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"] | Allowed HTTP methods |
| allowedHeaders | undefined | Headers allowed from requests |
| exposedHeaders | [] | Custom headers exposed to client |
| credentials | false | Allows sending cookies |
| maxAge | 86400 | Cache preflight requests |
| preflightContinue | false | Pass preflight responses to handlers |
Example Usage:
cors: {
methods: ["GET", "POST"],
credentials: true,
},Logger Configuration
Handles application logging using Winston.
| Option | Default Value | Description |
| ------------- | --------------------- | ------------------- |
| level | "info" | Logging level |
| format | timestamp + message | Log format |
| transports | [Console, File] | Output destinations |
| exitOnError | false | Exit on error |
Example Usage:
logger: {
level: "debug",
transports: [new transports.Console()],
},Security Configuration
Enhances security with Helmet.js settings.
| Option | Default Value | Description |
| ----------------------- | --------------- | ------------------------------ |
| contentSecurityPolicy | false | Enables CSP headers |
| dnsPrefetchControl | true | Controls DNS prefetching |
| frameguard | "sameorigin" | Prevents clickjacking |
| hsts | { maxAge: 0 } | HTTP Strict Transport Security |
| noSniff | false | Prevents MIME sniffing |
| xssFilter | true | Enables XSS protection |
Example Usage:
security: {
hsts: { maxAge: 31536000 },
xssFilter: false,
},Compression Configuration
Optimizes server performance by compressing HTTP responses.
| Option | Default Value | Description |
| ----------- | ------------- | --------------------------------------------------------------------------------- |
| level | 6 | Compression level (0-9) for Gzip. Higher values result in better compression. |
| threshold | 1024 | Only compress responses larger than 1KB. Smaller responses are sent uncompressed. |
| filter | Function | A function to determine whether to apply compression based on request/response. |
Example Usage:
compression: {
level: 9,
threshold: 2048,
filter: (req, res) => {
if (req.headers["x-no-compression"]) {
return false; // Skip compression if client requests no compression
}
return compression.filter(req, res); // Default compression filter
},
},Router configuration
config/routeConfig.js
Organize your routes easily with the routes array.
const TestRoute = require("../src/test/route");
module.exports = {
routes: [
{
path: "/route", // Define the URL path for this route
route: TestRoute, // Link to the corresponding route file
},
],
};Example Route (TestRoute)
Define and manage your endpoints with ease using Router.
const { Router } = require("express-pack");
const TestController = require("../controller/index");
// Define a GET endpoint for health checks or basic operations
Router.get("/health-check", TestController.testMethod);
// Define a POST endpoint for creating or processing data
Router.post("/submit-data", TestController.testPostMethod);
module.exports = Router;📖 Documentation
1. CreateApp(config)
Creates an Express application pre-configured with essential middleware.
- Parameters:
config(Object) – Your application configuration. - Returns:
An instance of an Express app.
2. BindRoutes(routes)
Binds an array of routes to the application.
Parameters:
routes(Array) – A list of route configurations.Example:
const routes = [{ path: "/api", route: ApiRoute }];
BindRoutes(routes);📂 Project Structure
my-project/
├── config/
│ ├── appConfig.js # Application configuration
│ └── routeConfig.js # Routes configuration
├── src/
│ └── test/ # Your route handlers
│ └── route.js # Example route handler
├── index.js # Main entry point of the application
🤝 Acknowledgments
Special thanks to the developers and contributors who make Express.js development easier every day!
