Express utitlities for automatic https redirects, slash forcing, logging, error handling and Handlebars templating
npm install prg-expressUsefull tools for:
- starting express app in one line
- handling errors within Express.js with app.use(errorMiddleware())
- throwing nice JSON errors with res.throw(401);
- measuring request duration and logging with app.use(requestLogger())
- cache some static data in templates using hbsStaticHelpers
- having nice new AppError('Missing attribute', 400, 4596)
- forcing slashes in url with configurator
- redirecting to https with configurator
- enabling trust proxy with configurator
- enabling compression with configurator
-----------------
ObjectSimpifies starting an Express.js server
errorMiddleware~errorReturn error processing middleware
throwMiddleware~throwMidCreates middleware, which allows simple logging and error responding in API
requestLogger~loggerCreates express middleware for logging duration of requests
ExpressHandlebarsAttaches compiler helpers which makes some static data compiled once
| Param | Type |
| --- | --- |
| error | string |
| status | number |
| code | number |
ObjectKind: global function
Returns: Object - description
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| app | any | | server listener |
| [port] | number | string | 3000 | listening port, default 3000 |
| [log] | console | | |
| [proc] | process | | for testing purposes |
Example
``javascript
const express = ('express');
const { createWebserver } = require('prg-express');
const app = express();
createWebserver(app).start();
`
| Param | Type | Description |
| --- | --- | --- |
| app | Express | application |
| httpConfig | object | the configuration |
| [httpConfig.zlib] | object | boolean | compression configuration |
| [httpConfig.forceSlashes] | boolean | null | forcing slashes |
| [httpConfig.trustProxy] | boolean | enables proxytrust |
| [httpConfig.isUsingSsl] | boolean | forces https |
| [httpConfig.excludeRedirectPaths] | array | forces https |
| [compressionMiddleware] | func | |
Example
`javascript
// theese are default values
const { configurator } = require('prg-express');
configurator(app, {
zlib: { threshold: 1024 },// true=enable with default params, false=dont attach zlib
forceSlashes: false, // true=with slashes, false=without slashes, null=dont redirect
trustProxy: true,
isUsingSsl: false, // redirect to https
redirectWww: true, // redirect from www to base domain
excludeRedirectPaths: [] // exlude from forcing slashes
});
`
errorMiddleware~errorKind: global function
Returns: errorMiddleware~error - - the middleware
| Param | Type | Description |
| --- | --- | --- |
| [options] | Object | |
| log | console | the logger |
Example
`javascript
const { errorMiddleware } = require('prg-express');
app.use(errorMiddleware({
errorView: '500', // error template name
attachStackTraces: false,
logLevel: 'error', // which method will be called on log object
mute: false // mutes error logging for testing purposes
}));
`
throwMiddleware~throwMidKind: global function
Returns: throwMiddleware~throwMid - - the middleware
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| logger | console | | where to log |
| muteLogs | boolean | false | use true for tests |
Example
`javascript
const express = require('express');
const app = express();
app.use(throwMiddleware());
app.get('/', (req, res) => {
res.throw(401, 'Unauthorized'); // log as info
// responds with { code: 401, error: 'Unauthorized' }
res.throw(403); // log as info with default message
res.throw(401, true); // log as error
const err = new Error('Failed');
err.code = 345; // will be used in response json
err.status = 400; // will be used as http status
res.throw(err);
const err = new Error('Failed');
err.code = 457; // will be used in response json
res.throw(err); // status will be set regarding to first digit of code
});
`
requestLogger~loggerKind: global function
Returns: requestLogger~logger - - returns the middleware
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| callback | func | | called, when request is finnished |
| [muteLogs] | boolean | false | mutes logs for testing |
Example
`javascript`
app.use(requestLogger((data) => {
const {
message,
url,
method,
responseTime,
status,
referrer,
remoteAddr
} = data;
}));
ExpressHandlebarsKind: global function
| Param | Type | Description |
| --- | --- | --- |
| expressHbs | ExpressHandlebars | Express Handlebars |
| helpers | Object | map of helpers |
| [data] | Object | static data |
| [hbs] | Handlebars | handlebars library |
Example
`javascript
const { hbsStaticHelpers } = require('prg-express');
// setup templating
const hbs = expressHandlebars.create({
defaultLayout: 'index',
extname: '.hbs',
layoutsDir: LAYOUTS_PATH,
partialsDir: VIEWS_PATH,
helpers
});
// setup template caching
if (!config.debugEnabled) {
app.enable('view cache');
}
// setup compile-time helpers {{$xkf kdkd}}
hbsStaticHelpers(hbs, helpers, app.locals);
// attach template engine
app.set('views', VIEWS_PATH);
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
// will be staticly executed in compilation time
{{$staticHelper 'param'}}
// will be staticly loaded from data
{{$dataParam}}
``