1.0.8 β€’ Published 6 months ago

express-pack v1.0.8

Weekly downloads
-
License
ISC
Repository
github
Last release
6 months ago

express-pack

Express-Pack Logo

npm version License Downloads

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
  • 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.

OptionDefault ValueDescription
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.

OptionDefault ValueDescription
methods["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"]Allowed HTTP methods
allowedHeadersundefinedHeaders allowed from requests
exposedHeaders[]Custom headers exposed to client
credentialsfalseAllows sending cookies
maxAge86400Cache preflight requests
preflightContinuefalsePass preflight responses to handlers

Example Usage:

cors: {
  methods: ["GET", "POST"],
  credentials: true,
},

Logger Configuration

Handles application logging using Winston.

OptionDefault ValueDescription
level"info"Logging level
formattimestamp + messageLog format
transports[Console, File]Output destinations
exitOnErrorfalseExit on error

Example Usage:

logger: {
  level: "debug",
  transports: [new transports.Console()],
},

Security Configuration

Enhances security with Helmet.js settings.

OptionDefault ValueDescription
contentSecurityPolicyfalseEnables CSP headers
dnsPrefetchControltrueControls DNS prefetching
frameguard"sameorigin"Prevents clickjacking
hsts{ maxAge: 0 }HTTP Strict Transport Security
noSnifffalsePrevents MIME sniffing
xssFiltertrueEnables XSS protection

Example Usage:

security: {
  hsts: { maxAge: 31536000 },
  xssFilter: false,
},

Compression Configuration

Optimizes server performance by compressing HTTP responses.

OptionDefault ValueDescription
level6Compression level (0-9) for Gzip. Higher values result in better compression.
threshold1024Only compress responses larger than 1KB. Smaller responses are sent uncompressed.
filterFunctionA 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!