npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@keeex/boilerplate-express

v2.1.4

Published

Utility code to spin up an express server

Readme

@keeex/boilerplate-express

Bugs Code Smells Maintainability Rating Security Rating Vulnerabilities Technical Debt Coverage

This library contains a handful of utilities to perform common setup actions when running an express server. Express servers are commonly defined as an "app" object, which defines how the routes are handled, and is then started as a listening server. This library provides facilities to define the "app" and start he server.

Defining the "app"

An "app" can be created by calling the createPipeline() function:

import express from "express";
import {createPipeline} from "@keeex/boilerplate-express/lib/express.js";

export const app = express();
app.use(createPipeline({
  topLevels: [],
  routes: [],
  statics: [],
  postStatics: [],
  errorHandlers: [],
  options: {
    log: {},
    middleware: {
      urlencoded: false,
      text: false,
      raw: false,
      json: true,
    },
    defaultErrorHandler: true,
  }
});

Most options are optional. The most important properties are:

  • topLevels : middlewares and routes that go before anything else
  • routes : application routes
  • statics : serve static files from express (this will happen after routes)
  • postStatics : routes that are registered after statics
  • errorHandlers : custom express error handlers
  • options.middleware : enable some common middleware for populating body

More detailed info can be found in the TSDoc.

Defining routes

topLevels, routes and postStatics are arrays of handlers. Each handler can be either another Router (for route composition), a simple handler without route specification (a simple req, res, next function), or a complete route definition in the form of an object with the following properties:

  • route: the route to handle
  • handler: the route handler (or an array, or a Router)
  • method: the method this route should handle. Defaults to "get".

Defining error handlers

The errorHandlers property accept an array of functions that follow the express "error handler" kind of functions (four parameters: err, req, res and next). If provided, and if the default error handler is set, they will be called before it.

Providing statics

To serve static files, the statics property can be used. It's an array of either directly the path to a directory, in which case it will be served at the root of the service, or an object with the following properties:

  • root: The directory where the static files are
  • options: The options to pass to express static handler
  • route: The route under which the static files will be served

Logging and timeout

The logging system will log all routes as soon as they arrive, log their final output, and implement a timeout mechanism. The default configuration logs everything.

The options.log property allows some customization of the logging system; see the tsdoc.

Individual routes can prevent logging some properties from the body using bodyLogger().

router.post(
  "/login",
  bodyLogger(
    ["login"],
    req => ({
      passwordLength: req.body.password.length,
    }),
  ),
  processLogin,
);

In addition to excluding properties from the body of a request and adding custom properties, it can be useful to always identify a request coming from a logged-in user.

You can provide a authFromReq property to the options.log configuration. It should be a function that receive req as its argument and returns a string identifying the logged-in user.

If a request is expected to take longer than the configured timeout, use timeoutRefresh(). If your code use callback-based code that breaks the logging, you can wrap the callback function with logBind().

Server shutting down

A pending timeout can prevent a program from shutting down. An event can be sent on the Express application called "keeexRayCloseEvent" (there is a constant named rayCloseEvent in consts.js) to disarm all pending timeout.

If you use appStart(), the server closing will automatically emit this event. If you want to send the event manually, use:

app.emit(rayCloseEvent);

Also note that a pending request will prevent the server from triggering its own "close" event until the request completes. Meaning if a request is pending (no response sent and the request was not destroyed), the close event from the server will not trigger immediately. And since its that event that will kill all timeout, it is possible to end in a situation where a loose request still prevent the process from closing.

Make sure to either use appStart() or send the event as needed, and not have open requests.

Configuring global aspects of an Express App

Configuring the template engine

A helper is provided to setup a template engine on the whole Express application.

import {setViewEngine} from "@keeex/boilerplate-express/lib/express.js";

const app = express();
setViewEngine(app, "pug", "webres/views", {});

The last parameter is optional; if provided it will define values available to the template engine.

Running the server

Once the express application is defined, it need to be started to serve files and resources. A helper is provided to do so, using the appStart() function.

import {consoleLogger} from "@keeex/boilerplate-express/lib/winston.js";
import app from "./app.js";
import {appStart} from "@keeex/boilerplate-express/lib/express.js";

appStart({
  app,
  listenInterface: false,
  port: 3000,
  shutdownFunction: () => {;},
  logger: consoleLogger,
  noReady: false,
}).then(({port, server}) => {;});

The settings are:

  • listenInterface: listen only to localhost or not. Can also be used to specify the address of an interface to bind to.
  • port: port to listen to. Can be 0 to use a random available port
  • shutdownFunction: a function to call after the server stop listening
  • logger: a winston logger to log that the server started listening
  • noReady: if true, does not call process.send("ready"); (used by PM2)

The shutdown function can return a promise, and if it returns/resolve with true the process is left alive. Otherwise process.exit() is called after shutdownFunction() resolves/returns.

The appStart() function returns a promise that resolve with the actual port used for listening when the server is started.

The server is automatically registered using the autoclose part to stop when a SIGINT signal is received.

Extra middleware

singlepageapp

If you want to serve a statically built webapp based on a single html entrypoint, you can use the middleware provided in /lib/express/middlewares/singlepageapp.js.

Basic usage:

import express from "express";
import {singlePageApp} from "@keeex/boilerplate-express/lib/middlewares/singlepageapp.js";

const someRouter = express.Router();
someRouter.use("/app", singlePageApp({rootDir: "dist/webapp"});

Available config options are:

  • rootDir: mandatory, root directory containing the SPA
  • htmlFile: optional, name of the HTML file to serve (defaults to "index.html")
  • staticRootDirectories: optional, name of directories (in the above root directory) to serve as static files. Defaults to ["js", "css", "img"].

A convenience command is available as "serve_spa" to be called from the command line. It is possible to pass it some parameters; run it with --help for more informations.