krakenjs / kraken-js

An express-based Node.js web application bootstrapping module.
Other
4.95k stars 459 forks source link
expressjs javascript krakenjs middleware

kraken-js

kraken.js

Build Status Greenkeeper badge

Kraken builds upon express and enables environment-aware, dynamic configuration, advanced middleware capabilities, security, and app lifecycle events. For more information and examples check out krakenjs.com

Table of Contents

Basic Usage

'use strict';

var express = require('express'),
    kraken = require('kraken-js');

var app = express();
app.use(kraken());
app.listen(8000);

API

kraken([options])

kraken-js is used just like any normal middleware, however it does more than just return a function; it configures a complete express 4 application. See below for a list of features, but to get started just use it like middleware.

app.use(kraken());
// or to specify a mountpath for your application:
// app.use('/mypath', kraken());

// Note: mountpaths can also be configured using the
// `express:mountpath` config setting, but that setting
// will be overridden if specified in code.

Options

Pass the following options to kraken via a config object such as this:

var options = {
    onconfig: function (config, callback) {
        // do stuff
        callback(null, config);
    }
};

// ...

app.use(kraken(options));

Note: All kraken-js configuration settings are optional.

basedir (String, optional)

The working directory for kraken to use. kraken loads configuration files, routes, and registers middleware so this directory is the path against all relative paths are resolved. The default value is the directory of the file that uses kraken, which is generally index.js (or server.js).

onconfig (Function, optional)

Provides an asynchronous hook for loading additional configuration. When invoked, a confit configuration object containing all loaded configuration value passed as the first argument, and a callback as the second. The signature of this handler is function (config, callback) and the callback is a standard error-back which accepts an error as the first argument and the config object as the second, e.g. callback(null, config).

protocols (Object, optional)

Protocol handler implementations for use when processing configuration. For more information on protocols see shortstop and shortstop-handlers. By default, kraken comes with a set of shortstop protocols which are described in the "Config Protocols" section below, but you can add your own by providing an object with the protocol names as the keys and their implementations as properties, for example:

var options = {
    protocols: {
        file: function file(value, callback) {
            fs.readFile(value, 'utf8', callback);
        }
    }
};

onKrakenMount (Function, optional)

Provides a synchronous hook which executes once kraken mounts. It takes an express app instance as the first argument, and options as the second. The signature of this handler is function (app, options).

uncaughtException (Function, optional)

Handler for uncaughtException errors outside of the middleware chain. See the endgame module for defaults.

For uncaught errors in the middleware chain, see shutdown middleware instead.

confit (Object, optional)

In rare cases, it may be useful to pass options directly to the confit module used within lib/config.js. For example, if confit/shortstop is conflicting with environment variables, you can explicitly ignore those environment variables:

var options = {
    confit: {
        envignore: ['troublesome_environment_variable']
    }
};

Config Protocols

kraken comes with the following shortstop protocol handlers by default:

import:

Merge the contents of the specified file into configuration under a given key.

{
    "foo": "import:./myjsonfile"
}

config:

Replace with the value at a given key. Note that the keys in this case are dot (.) delimited.

{
    "foo": {
        "bar": true
    },
    "foobar": "config:foo.bar"
}

path:

The path handler is documented in the shortstop-handlers repo.

file:

The file handler is documented in the shortstop-handlers repo.

base64:

The base64 handler is documented in the shortstop-handlers repo.

env:

The env handler is documented in the shortstop-handlers repo.

require:

The require handler is documented in the shortstop-handlers repo.

exec:

The exec handler is documented in the shortstop-handlers repo.

glob:

The glob handler is documented in the shortstop-handlers repo.

resolve:

The resolve handler is documented in the shortstop-resolve repo.

Features

Configuration

Environment-aware

Using environment suffixes, configuration files are applied and overridden according to the current environment as set by NODE_ENV. The application looks for a ./config directory relative to the basedir and looks for config.json as the baseline config specification. JSON files matching the current env are processed and loaded. Additionally, JSON configuration files may contain comments.

Valid NODE_ENV values are undefined or dev[elopment] (uses development.json), test[ing] (uses test.json), stag[e|ing] (uses staging.json), prod[uction] (uses config.json). Simply add a config file with the name, to have it read only in that environment, e.g. config/development.json.

Middleware

Much like configuration, you shouldn't need to write a lot of code to determine what's in your middleware chain. meddleware is used internally to read, resolve, and register middleware with your express application. You can either specify the middleware in your config.json or {environment}.json, (or) import it from a separate json file using the import protocol mentioned above.

Included Middleware

Kraken comes with common middleware already included in its config.json file. The following is a list of the included middleware and their default configurations which can be overridden in your app's configuration:

Additional notes:

// include this in your own config.json and this will merge with the Kraken defaults
// NB: if you use kraken-devtools you must re-route that as well in development.json!
{
    "static": {
        "route": "/static"
    }
}

Extending Default Middleware

In any non-trivial Kraken deployment you will likely need to extend the included middleware. Common middleware which need extension include cookie parsing and session handling. In those particular cases, the secrets used should be updated:

{
    // include this in your own config.json and this will merge with the Kraken defaults
    "middleware": {

        "cookieParser": {
            "module": {
                "arguments": [ "your better secret value" ]
            }
        },

        "session": {
            "module": {
                // NB: arrays like 'arguments' are not merged but rather replaced, so you must
                //     include all required configuration options here.
                "arguments": [
                    {
                        "secret": "a much better secret",
                        "cookie": {
                            "path": "/",
                            "httpOnly": true,
                            "maxAge": null
                        },
                        "resave": true,
                        "saveUninitialized": true,
                        "proxy": null
                    }
                ]
            }
        }

    }
}

Another common update is to pass options to middleware which is configured only with the defaults, such as the compression middleware:

{
    "middleware": {
        "compress": {
            "enabled": true,    // response compression is disabled by default
            "module": {
                "arguments": [
                    {
                        // 512 byte minimum before compressing output
                        "threshold": 512
                    }
                ]
            }
        }
    }
}

More complicated examples include configuring the session middleware to use a shared resource, such as connect-redis. This requires a few extra steps, most notably creating your own middleware to handle the registration (see totherik/redis-example for a complete example):

  1. Overlay the existing session middleware in your configuration:

    {
      // in your config.json
      "middleware": {
          "session": {
              "module": {
                  // use your own module instead
                  "name": "path:./lib/middleware/redis-session",
                  "arguments": [
                      // express-session configuration
                      {
                          "secret": "a much better secret",
                          "cookie": {
                              "path": "/",
                              "httpOnly": true,
                              "maxAge": null
                          },
                          "resave": true,
                          "saveUninitialized": true,
                          "store": null    // NB: this will be overlaid in our module
                      },
                      // connect-redis configuration
                      {
                          "host": "localhost",
                          "port": 6379,
                          "prefix": "session:"
                      }
                  ]
              }
          }
      }
    }
  2. Add your custom middleware for Kraken to configure:

    // ./lib/middleware/redis-session.js
    'use strict';
    
    var session = require('express-session'),
      RedisStore = require('connect-redis')(session);
    
    /** Creates a REDIS-backed session store.
    *
    * @param {Object} [sessionConfig] Configuration options for express-session
    * @param {Object} [redisConfig] Configuration options for connect-redis
    * @returns {Object} Returns a session middleware which is backed by REDIS
    */
    module.exports = function (sessionConfig, redisConfig) {
    
      // add the 'store' property to our session configuration
      sessionConfig.store = new RedisStore(redisConfig);
    
      // create the actual middleware
      return session(sessionConfig);
    };

Application Security

Kraken uses lusca to secure your applications, so that you don't need to think about it. Techniques like CSRF, XFRAMES, and CSP are enabled automatically while others can be opted into. All are customizable through configuration.

Lifecycle Events

Kraken adds support for additional events to your express app instance:

Configuration-based express Settings

Since express instances are themselves config objects, the convention is to set values on the app instance for use by express internally as well as other code across the application. kraken-js allows you to configure express via JSON. Any properties are supported, but kraken-js defaults include:

{
    "express": {
        "env": "", // NOTE: `env` is managed by the framework. This value will be overwritten.
        "x-powered-by": false,
        "trust proxy": false,
        "jsonp callback name": null,
        "json replacer": null,
        "json spaces": 0,
        "case sensitive routing": false,
        "strict routing": false,
        "view cache": true,
        "view engine": null,
        "views": "path:./views",
        "route": "/"
    }
}

Additional notes:

For example:

{
    "express": {
        "view": "path:./lib/MyCustomViewResolver"
    }
}

View Engine Configuration

kraken-js looks to the view engines config property to understand how to load and initialize renderers. The value of the view engines property is an object mapping the desired file extension to engine config settings. For example:

{
    "view engines": {
        "jade": {
            "module": "consolidate"
        },
        "html": {
            "name": "ejs",
            "module": "ejs",
            "renderer": "renderFile"
        },
        "dust": {
            "module": "adaro",
            "renderer": {
                "method": "dust",
                "arguments": [{
                    "cache": false,
                    "helpers": ["dust-helpers-whatevermodule"]
                }]
            }
        },
        "js": {
            "module": "adaro",
            "renderer": {
                "method": "js",
                "arguments": [{ "cache": false }]
            }
        }
    }
}

The available engine configuration options are:

Tests

$ npm test

Coverage

$ npm run-script cover && open coverage/lcov-report/index.html

Reading app configs from within the kraken app

There are two different ways. You can