1.5.0 • Published 4 months ago

express-bootstrapi v1.5.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

express-bootstrap

express-bootstrap is a Node.js package that simplifies the process of setting up an Express.js server by automating repetitive configuration tasks. It helps developers quickly start their projects without having to manually configure things like logging, MongoDB connections, CORS, and static file serving.

Objective

The main goal of express-bootstrap is to help developers start their projects easily and quickly by reducing the amount of repeatable configurations and installed packages. With just a few lines of configuration, your project is ready to go.

Features

  • Automatic Database Connection: Connects to MongoDB using Mongoose with just a database name.
  • Customizable Logging: Integrates with morgan for logging requests with customizable formats and emoji-based status code coloring.
  • CORS Handling: Customizable CORS options to define allowed domains, IPs, Headers and methods.
  • Helmet Integration: Adds security middleware with Helmet, configurable and easy to enable or disable.
  • Static File Serving: Easily serve multiple static folders with different paths.
  • Error Handling: Built-in error handling middleware.
  • Quick and Easy Setup: All configurations are provided in one place.
  • API Limiter: Resilient rate limiting strategy for fault-tolerant API rate limiting.

Installation

npm install express-bootstrapi

or

yarn add express-bootstrapi

Usage

Here’s a quick guide on how to use the express-bootstrap package to set up your Express.js project.

Step 1: Create a Bootstrap File

Create a new file, for example bootstrap.ts, and import the express-bootstrap package. Then, provide the necessary options to initialize the app.

import appRoutes1 from "../app/routes1";
import appRoutes2 from "../app/routes2";
const bootstrap = require("express-bootstrapi");

bootstrap({
  // use one of this approaches to initialize app routes [routes OR routesPath]
  routes: [appRoutes1,appRoutes2],
  routesPath: [
    {
      path: "/api/v2/users",
      middleware: isUser,
      routes: appRoutes1,
    },
    {
      path: "/api/v2/shop",
      middleware: null,
      routes: appRoutes2,
    }
  ],
  staticFolders: [
    {
      path: "/",
      folder: "public",
    },
    {
      path: "/static",
      folder: "static",
    },
  ],
  db: { dbName: "myDatabase" },
  cors: {
    methods: "get,post,delete,patch,put",
    customHeaders: ["customer", "authorization"],
    requiredHeaders : [
      {
        "customer-required-header": "value1",
      }
      {
        "customer-required-header2": "value2",
      }
    ],
    allowedIPs: ["127.0.0.1"],
    allowedDomains: ["example.com", "localhost"],
    allowedRoutes?: ['/app'],
    callBack?: yourCallBackFunction()
  },
  urlencoded: {  extended: true,limit: "5mb"},
  compression: { level: -1 },
  helmet: {
    active: true,
  },
  limiter: {
    windowMs: 10 * 60 * 1000,
    limit: 150,
    standardHeaders: "draft-8",
    legacyHeaders: false,
  },
  errorsHandler: (errors) => console.log(errors),
  loggerFormat: ":remote-addr 🔗 :method ➡️ :url :status :status-color ⏱️ :response-time ms",
  port: 3000,
  host: "localhost"
});

Step 2: Define Your Routes

In your routes file (e.g., app/routes.ts), define your application routes.

import express from "express";
const router = express.Router();

router.get("/", (req, res) => {
  res.send("Hello, World!");
});

export default router;

Step 3: Run the App

You can now run your app and the server will start with the configurations provided.

CORS options

PropertyTypeDescriptionExample
methodsStringSpecifies the HTTP methods that are allowed for cross-origin requests."get,post,delete,patch,put"
customHeadersArrayCustom headers to be added to the CORS Allowed headers request.[ { "custom-token": "tokenHere" } ]
allowedIPsArrayA list of specific IPs that are allowed to make requests.[ "127.0.0.1" ]
allowedDomainsArrayA list of domains that are allowed to make requests.[ "example.com", "localhost" ]
allowedRoutesArrayA list of paths that are allowed to requests without cors restrictions.[ "/app", "/app2" ]
requiredHeadersArrayA list of required headers that restrct application respond without it.[{ "required-header1": "your-value",},{"required-header2": "your-value",},]
callBackFunctionA Function to handle extra application features at cors level.
customHandlerFunctionA Function to return app and db.

Static Folders Options

PropertyTypeDescriptionExample
pathStringThe URL path where the static folder will be served."/"
folderStringThe folder name in your project that contains the static files to serve."public"
staticFolders: [
  {
    path: "/",
    folder: "public",
  },
  {
    path: "/static",
    folder: "static",
  },
];

Database Connection Options

PropertyTypeDescriptionExample
uriStringThe full MongoDB connection URI string. If provided, it will override other connection properties."mongodb://localhost:27017/mydb"
userStringThe username for authenticating with MongoDB."dbUser"
passwordStringThe password for the MongoDB user."dbPassword"
hostStringThe MongoDB server hostname. Defaults to "127.0.0.1" if not provided."localhost"
portStringThe MongoDB server port. Defaults to "27017" if not provided."27017"
dbNameStringThe name of the MongoDB database."myDatabase"
optionsObjectAdditional Mongoose-specific connection options, such as autoIndex and autoCreate.{ useNewUrlParser: true }

Example Usage:

{
  db: {
    uri: "", // or leave empty to construct from user, password, host, and dbName
    user: "dbUser",
    password: "dbPassword",
    host: "localhost",
    port: "27017",
    dbName: "myDatabase",
    options: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }
  }
}

With no auth and localhost configuration

{
  db: {
    dbName: "myDatabase",
  }
}

Logger Status Color Codes

Status Code RangeColorDescription
401🟡Yellow icon for Unauthorized (401)
5xx🔴Red icon for Server errors (5xx)
402 - 499🟠Orange icon for Client errors (402-499)
200 - 299Green icon for Success (2xx)

urlencoded options

urlencoded options: as express.urlencoded props

compression options

compression options: as compress props

helmet options

helmet options: as helmet props

limiter options

limiter options: as limiter props

Real world exmaples

How to use package at simple express project

How to use bug tracker send by email template

How to cors handler to implement middleware approach

1.5.0

4 months ago

1.4.9

9 months ago

1.4.8

9 months ago

1.4.7

9 months ago

1.4.6

10 months ago

1.4.5

10 months ago

1.4.4

10 months ago

1.4.3

10 months ago

1.3.3

10 months ago

1.3.2

10 months ago

1.3.1

10 months ago

1.3.0

10 months ago

1.2.9

10 months ago

1.2.8

10 months ago

1.2.7

10 months ago

1.2.6

10 months ago

1.2.5

10 months ago

1.2.4

10 months ago

1.2.3

10 months ago

1.2.2

10 months ago

1.2.1

10 months ago

1.2.0

10 months ago

1.1.8

10 months ago

1.1.6

10 months ago

1.1.5

10 months ago

1.1.4

10 months ago

1.1.3

10 months ago

1.1.2

10 months ago

1.1.1

10 months ago

1.1.0

10 months ago

1.0.1

10 months ago