roosevelt
Version:
🧸 MVC web framework for Node.js designed to make Express easier to use.
844 lines (693 loc) • 45.9 kB
Markdown
## App name
Roosevelt will determine your app's name by examining `"name"` in `package.json`. If none is provided, it will use `Roosevelt Express` instead.
## The `rooseveltConfig` API
Roosevelt is highly configurable and you can configure it from the following hierarchy of sources in increasing order of precedence:
- A `rooseveltConfig` section in your package.json.
- A `roosevelt.config.json` file.
- A `rooseveltConfig.json` file.
- Constructor parameters.
- Environment variables.
- Command line flags.
What "increasing order of precedence" means is that command line flags will override environment variables, environment variables will override constructor parameters, constructor parameters will override config files, etc.
### File path options
- `appDir` *[String]*: Root directory of your application. Default: The directory where your app's `package.json` is located.
- `buildFolder` *[String]*: Where build artifacts will be placed such as the output from preprocessed views, preprocessed statics, the views bundler feature, or the controllers bundler feature. Default: `".build"`.
- You should `.gitignore` this folder.
- Not all build artifacts will go into this folder. Some notable exceptions include:
- `.npm-cache`: Generated by npm.
- `node_modules`: Generated by npm.
- `package-lock.json`: Generated by npm.
- `public`: This is a separate folder for files generated by Roosevelt that should be exposed publicly as static files. The name of this folder is configurable with the `publicFolder` param.
- `secrets`: Directory that stores certs, keys, and secrets. The name of this folder is configurable with the `secretsPath` param.
- `controllersPath` *[String]*: Relative path on filesystem to where your controller files are located. Default: `"mvc/controllers"`.
- `errorPages` *[Object]*: Relative path on filesystem to where your various error page controller files are located. If you do not supply them, Roosevelt will use its default ones instead:
- `forbidden` *[String]*: Your [403 Forbidden](https://en.wikipedia.org/wiki/HTTP_403) error page. Default: `"403.js"`.
- `notFound` *[String]*: Your [404 Not Found](https://en.wikipedia.org/wiki/HTTP_404) error page. Default: `"404.js"`.
- `internalServerError` *[String]*: Your [5xx Internal Server Error](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_errors) error page. Default: `"5xx.js"`.
- `serviceUnavailable` *[String]*: Your [503 Service Unavailable](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_errors) error page. Default: `"503.js"`.
- `modelsPath` *[String]*: Relative path on filesystem to where your model files are located. Default: `"mvc/models"`.
- `preprocessedStaticsPath` *[String]*: Relative path on filesystem to where your preprocessed static files will be written to. Preprocessed static files are static files that have been preprocessed by the [minify-html-attributes](https://rooseveltframework.org/docs/minify-html-attributes) module, if you have `minifyHtmlAttributes` enabled. This feature will only be active if `minifyHtmlAttributes` is enabled. Default: `".build/preprocessed_statics"`.
- `preprocessedViewsPath` *[String]*: Relative path on filesystem to where your preprocessed view files will be written to. Preprocessed view files are view files that have had their uses of web components progressively enhanced using the [progressively-enhance-web-components](https://rooseveltframework.org/docs/progressively-enhance-web-components) module. To disable this feature, set the value to false. Default: `".build/preprocessed_views"`.
- `publicFolder` *[String]*: All files and folders in this directory will be exposed as static files in development mode or when `hostPublic` is enabled. You should .gitignore this folder. Default: `"public"`.
- `secretsPath` *[String]*: Directory that stores certs, keys, and secrets. You should .gitignore this folder. Default: `secrets`.
- `staticsRoot` *[String]*: Relative path on filesystem to where your source static assets are located. By default this folder will not be made public, but is instead meant to store unprocessed or uncompressed source assets that will later be preprocessed and exposed in `public`. Default: `"statics"`.
- `viewsPath` *[String]*: Relative path on filesystem to where your view files are located. Default: `"mvc/views"`.
### Development mode options
These features are only available in development mode.
- `frontendReload` *[Object]*: Settings to use for the browser reload feature which automatically reloads your browser when your frontend code changes.
- Options:
- `enable` *[Boolean]*: Whether or not to enable this feature.
- `exceptionRoutes` *[Array of Strings]*: List of routes to exclude from this feature.
- `expressBrowserReloadParams` *[Object]*: Params to pass to [express-browser-reload](https://rooseveltframework.org/docs/express-browser-reload). This feature will only be active on pages with a `<body>` tag.
Default: *[Object]*
```json
{
"enable": true,
"exceptionRoutes": [],
"expressBrowserReloadParams": {
"skipDeletingConnections": true
}
}
```
- `htmlValidator` *[Object]*: Parameters to send to [express-html-validator](https://rooseveltframework.org/docs/express-html-validator).
- `enable` *[Boolean]*: Enables or disables the built-in HTML validator.
- `exceptions` *[Object]*: A set of params that can be used to prevent validation in certain scenarios.
- `header` *[String]*: A custom header that when set will disable the validator on a per request basis.
- `modelValue` *[String]*: An entry in your data model passed along with a `res.render` that when set will disable validation on the rendered HTML.
- `validatorConfig` *[Object]*: [html-validate configuration](https://html-validate.org/usage/#configuration) that determines what errors the validator looks for.
- The full list of available validator rules can be found [here](https://html-validate.org/rules/).
- This configuration can also be set by a `.htmlValidate.json` file placed in your app root directory.
- `mode` *[String]*: Decides whether your app starts in production mode or development mode by default. Default: `production`.
Default: *[Object]*
```json
{
"enable": true,
"exceptions": {
"requestHeader": "Partial",
"modelValue": "_disableValidator"
},
"validatorConfig": {}
}
```
### HTTP options
- `http` *[Object]*: Parameters for configuring the HTTP server.
- `enable` *[Boolean]*: Enable HTTP server.
- `port` *[Number]*: The HTTP port your app will run on.
Default when an app is created manually: *[Object]*
```json
{
"enable": true,
"port": 43763
}
```
Default when an app is created with the app generator: *[Object]*
```json
{
"enable": false,
"port": 43763
}
```
- `https` *[Object]*: Parameters for configuring the HTTPS server.
- `enable` *[Boolean]*: Enable HTTPS server.
- `port` *[Number]*: The port your app will run the HTTPS server on.
- `autoCert` *[Boolean]*: Will create self-signed HTTPS certificates in development mode as long as they don't already exist.
- `options` *[Object]*: Configuration that gets passed directly to the HTTPS server instance. Accepts [all native settings](https://nodejs.org/api/tls.html#tlscreatesecurecontextoptions). For convenience, the `ca`, `cert`, `key`, and `pfx` params can take file path strings or arrays of file path strings relative to your `secretsPath` in addition to the native strings and buffers.
Default when an app is created manually: *[Object]*
```json
{
"enable": false,
"port": 43711,
"autoCert": true,
"options": {}
}
```
Default when an app is created with the app generator: *[Object]*
```json
{
"enable": true,
"port": 43711,
"autoCert": true,
"options": {
"cert": "cert.pem",
"key": "key.pem"
}
}
```
### App behavior options
- `deprecationChecks`: *[String]* or *[Boolean]*: Whether or not to run the deprecation checker in Roosevelt. The deprecation checker is a script that runs when your app starts to determine if you have code targeting an older version of Roosevelt that needs to be refactored. Default: `'developmemnt-mode'` which will run the checks in development mode only. Set to `false` to disable it entirely.
- `expressVersion`: *[Number]*: Which version of [Express](https://expressjs.com) to use. Choose between either `4` or `5`. This option exists because there are [significant differences](https://expressjs.com/en/guide/migrating-5.html) between Express 4 and Express 5. Default: `5`.
- `bodyParser` *[Object]*: Parameters to supply to the [body-parser](https://github.com/expressjs/body-parser) module which handles POST requests.
- `urlEncoded` *[Object]*: Parameters to supply to [body-parser.urlencoded](https://github.com/expressjs/body-parser#bodyparserurlencodedoptions).
- `json` *[Object]*: Parameters to supply to [body-parser.json](https://github.com/expressjs/body-parser#bodyparserjsonoptions).
Default: *[Object]*
```json
{
"urlEncoded": {
"extended": true
},
"json": {}
}
```
- `csrfProtection` *[Boolean or Object]*: Whether to enable [Cross-Site Request Forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery) protection. Default: `true`.
- Requires `expressSession` to be enabled.
- To disable the feature, set it to false. To exempt certain routes from protection, supply an object as your config with an array of exemptions.
- See the [CSRF Protection](#csrf-protection) section for more information.
Example of exemptions list: *[Object]*
```json
{
"exemptions": [
"/foo",
"/bar",
"/baz"
]
}
```
- `expressSession` *[Boolean or Object]*: Parameters to pass to the [express-session](https://github.com/expressjs/session) module. Default: `true`.
Default if `expressSession` is set to `true`: *[Object]*
```json
{
"secret": [an auto-generated secret],
"resave": false, // usually a bad idea to set to true
"saveUninitialized": false, // usually a bad idea to set to true
"cookie": {
"secure": false, // will automatically be set to true if https is enabled
"sameSite": "strict", // adds same site enforcement
"maxAge": 347126472000 // sets expiration very far in the future (~11 years) to basically never expire
}
"store": [the expressSessionStore.instance Roosevelt param]
}
```
- `expressSessionStore` *[Object]*: Define a custom session store to use with `express-session` instead of the default one provided by Roosevelt. This is recommended if you plan to shard your app across multiple separate processes or scale it to multiple servers.
- `filename` *[String]*: Name of the session file.
- `instance`: *[Object]* A store instance. See [this list](https://expressjs.com/en/resources/middleware/session.html#compatible-session-stores) for compatible stores.
- `preset` *[String]*: Available presets provided by Roosevelt. Only used if `instance` is not provided.
- Available options:
- `"default"`: Use Roosevelt's default session store, which is [better-sqlite3-session-store](https://www.npmjs.com/package/better-sqlite3-session-store).
- `"express-session-default"`: Use `express-session`'s default session store (not recommended).
- `presetOptions` *[Object]*: Options to pass to the preset session store if one is selected. Only used if `instance` is not provided.
- `checkPeriod` *[Number]*: How long, in milliseconds, the memory store will check for expired items.
- `ttl` *[Number]*: How long, in milliseconds, before a session is expired. If not set, it will default to the value of `checkPeriod`.
- `max` *[Number]*: The maximum size of the cache, checked by applying the length function to all values in the cache. If not set, there will be no maximum.
- Either `instance` or `preset` must be set for this param to work properly.
Default: *[Object]*
```json
{
"filename": "sessions.sqlite",
"instance": null,
"preset": "default",
"presetOptions": {
"checkPeriod": 86400000, // one day
"ttl": null,
"max": null
}
}
```
- `formidable`: Parameters to pass to [formidable](https://github.com/felixge/node-formidable) using [formidable's API](https://github.com/felixge/node-formidable#api) for multipart form processing (file uploads). Access files uploaded in your controllers by examining the `req.files` object. Roosevelt will remove any files uploaded to the upload directory when the request ends automatically. To keep any, be sure to move them before the request ends.
Default: *[Object]*
```json
{
"multiples": true // enables multiple files to be uploaded simultaneously
}
```
To disable multipart forms entirely, set `formidable` to `false`.
- `helmet` *[Object]*: Parameters to pass to the [helmet](https://github.com/helmetjs/helmet) module. This module helps secure Express apps by setting HTTP response headers.
- The default options are specified in the [helmet docs](https://helmetjs.github.io/), with the following exceptions that Roosevelt makes to the default `Content-Security-Policy` settings:
- The `upgrade-insecure-requests` directive has been removed. This change prevents [this bug](https://github.com/rooseveltframework/roosevelt/issues/964).
- The `script-src` directive has been set to `"unsafe-inline"`. This makes it possible to use inline scripts.
- The `form-action` directive has been set to `null`. This makes it possible to submit forms to other domains.
- You can reverse any of these changes by configuring helmet yourself.
- To disable helmet entirely, set the param to `false`.
- `logging`: Parameters to pass to [roosevelt-logger](https://rooseveltframework.org/docs/roosevelt-logger). See [roosevelt-logger parameters documentation](https://rooseveltframework.org/docs/roosevelt-logger/latest/configuration.html) for configuration options.
Default: *[Object]*
```json
{
"methods": {
"http": true,
"info": true,
"warn": true,
"error": true,
"verbose": false
}
}
```
- `makeBuildArtifacts` *[Boolean or String]*: When enabled Roosevelt will generate user-specified directories, CSS/JS bundles, etc.
- Defaults to `false` for apps created manually.
- Will be set to `true` in apps generated with the app generator.
- Can also accept a value of `"staticsOnly"` which will allow Roosevelt to create static files but skip the creation of the MVC directories.
- `routePrefix` *[String]*: A prefix prepended to your application's routes. Applies to all routes and static files. Default: `null`.
- Example: When set to `"foo"` a route bound to `/` will be instead be bound to `/foo/`.
- This prefix is exposed via the `routePrefix` Express variable which should be used for resolving the absolute paths to statics programmatically.
- Example: An image located at `/images/teddy.jpg` can be resolved in a prefix-agnostic way via `${app.get('routePrefix')/images/teddy.jpg}`.
- `viewEngine` *[String]*: What templating engine to use, formatted as `"fileExtension: nodeModule"`.
- Defaults to `"none"` for apps created manually.
- Will be set to `"html: teddy"` in apps generated with the app generator.
- Also by default when using the app generator, the [teddy](https://rooseveltframework.org/docs/teddy) module is marked as a dependency in `package.json`.
- To use multiple templating systems, supply an array of engines to use in the same string format. Each engine you use must also be marked as a dependency in your app's `package.json`. Whichever engine you supply first with this parameter will be considered the default.
Example configuration using multiple templating systems: *[Object]*
```json
{
"viewEngine": [
"html: teddy",
"php: php",
"ejs: ejs"
]
}
```
### Isomorphic (single page app) options
- `clientControllers` *[Object]*: Allows you to expose controller (route) file code to frontend JS for client-side routing.
- `enable` *[Boolean]*: Whether or not to bundle controller files.
- `exposeAll` *[Boolean]*: Option to expose all templates.
- `blocklist` *[Array of Strings]*: List of files or folders to exclude when `exposeAll` is enabled.
- Can also be set declaratively by putting a `// roosevelt-blocklist` comment at the top of any controller file.
- `allowlist` *[Object of Arrays]*: List of JS files to create mapped to which controller files to expose.
- Example: `{ "mainPages.js": ["index.js", "about.js"] }`
- Can also be set declaratively by putting a `// roosevelt-allowlist file_path` comment at the top of any controller file.
- `defaultBundle` *[String]*: File name for the default JS controller bundle.
- `output` *[String]*: Subdirectory within `buildFolder` to write JS controller bundles to.
Default: *[Object]*
```json
"clientControllers": {
"enable": false,
"exposeAll": false,
"blocklist": [],
"allowlist": {},
"defaultBundle": "controllers.js",
"output": "js"
}
```
- `clientViews` *[Object]*: Allows you to expose view (template) file code to frontend JS for client-side templating.
- `enable` *[Boolean]*: Whether or not to bundle view files.
- `exposeAll` *[Boolean]*: Option to expose all templates.
- `blocklist` *[Array of Strings]*: List of files or folders to exclude when `exposeAll` is enabled.
- Can also be set declaratively by putting a `<!-- roosevelt-blocklist -->` tag at the top of any template.
- `allowlist` *[Object of Arrays]*: List of JS files to create mapped to which view files to expose.
- Example: `{ "mainPages.js": ["baseLayout.html", "footer.html"] }`
- Can also be set declaratively by putting a `<!-- roosevelt-allowlist file_path -->` tag at the top of any template.
- `defaultBundle` *[String]*: File name for the default JS view bundle.
- `output` *[String]*: Subdirectory within `buildFolder` to write JS view bundles to.
- `minify` *[Boolean]*: Option to minify templates that are exposed via this feature.
- Be careful with this feature because it can break your templates depending on which templating system you use, and as such it is off by default. You may need to make liberal use of the `minifyOptions` param to make it work right with your templating system.
- `minifyOptions` *[Object]*: Parameters to supply to [html-minifier](https://github.com/terser/html-minifier-terser#options-quick-reference)'s API.
- Uses the params you set in `html.minifier.options` if empty.
Default: *[Object]*
```json
"clientViews": {
"enable": false,
"exposeAll": false,
"blocklist": [],
"allowlist": {},
"defaultBundle": "views.js",
"output": "js",
"minify": false,
"minifyOptions": {}
}
```
### Static file options
- `copy` *[Array of Objects]*: Declare one or more files or folders to copy at runtime. Default: `[]`.
- `source` *[String]*: Path to be copied from.
- Roosevelt will not attempt to copy files or folders that do not exist.
- `dest` *[String]*: Path to place the copy.
- If this destination path already exists **it will be overwritten**.
- `html` *[Object]*: Generate static HTML pages:
- `sourcePath` *[String]*: Subdirectory within `staticsRoot` where your static HTML files are located. By default this folder will not be made public, but is instead meant to store unminified / unprocessed HTML template source files which will be rendered by your templating system, minified, and written to the `public` folder when the app is started.
- `allowlist`: *[Array of Strings]* List of templates to render, minify, and write to the `public` folder when the app is started. If the list is empty, all templates in your `sourcePath` will be sourced. Supports wildcard matching, e.g. `dir/*`.
- `blocklist`: *[Array of Strings]* List of templates in your `sourcePath` to skip. Supports wildcard matching, e.g. `dir/*`.
- You can also block a file from being exposed by adding a comment on the first line of the file with the string `roosevelt-blocklist` anywhere on the line.
- `models` *[Object]*: Data to pass to templates by file path / file name.
- Example: `{ "index.html": { "some": "data" } }`
- You can also pass a global model using a `*` catch-all character: `{ "*": { "some": "data" } }`
- If this data is not supplied by configuration, Roosevelt will try to automatically load a model from a JS file with the same name alongside the template if it exists instead. For example if an index.js file exists next to index.html and the model is not defined by configuration like in the example above, then the index.js file will be used to set the model so long as it exports either an object or a function that returns an object.
- `output` *[String]*: Subdirectory within `publicFolder` where parsed and minified HTML files will be written to.
- `folderPerPage` *[Boolean or String]*: Make a folder for each page and place the page within it.
- Example values:
- `true`: Given a page called example.html, this feature will create a folder called "example" in the public folder and place "example.html" within it.
- `"index.html"`: Given a page called example.html, this feature will create a folder called "example" in the public folder and place "index.html" within it. This is useful for creating "pretty URLs" with static sites.
- `false`: Disables the feature.
- `minifier` *[Object]*: How you want Roosevelt to minify your HTML:
- `enable` *[Boolean]*: Whether or not to minify HTML.
- Can also be disabled by the `minify` param.
- Minification is automatically disabled in development mode.
- `exceptionRoutes` *[Array of Strings]*: List of controller routes that will skip minification entirely. Set to `false` to minify all URLs.
- `options` *[Object]*: Parameters to supply to [html-minifier](https://github.com/kangax/html-minifier#options-quick-reference)'s API.
Default: *[Object]*
```json
{
"sourcePath": "pages",
"allowlist": null,
"blocklist": null,
"models": {},
"output": "",
"folderPerPage": false,
"minifier": {
"enable": true,
"exceptionRoutes": false,
"options": {
"removeComments": true,
"collapseWhitespace": true,
"collapseBooleanAttributes": true,
"removeAttributeQuotes": true,
"removeEmptyAttributes": true
}
}
}
```
- `css` *[Object]*: How you want Roosevelt to configure your CSS preprocessor:
- `sourcePath` *[String]*: Subdirectory within `staticsRoot` where your CSS files are located. By default this folder will not be made public, but is instead meant to store unminified CSS source files which will be minified and written to the `public` folder when the app is started.
- `compiler` *[Object]*: Which CSS preprocessor (if any) to use.
- `enable` *[Boolean]*: Whether or not to use a preprocessor.
- `module` *[String]*: Node module name of the CSS preprocessor you wish to use.
- Currently [less](http://lesscss.org/), [sass](https://sass-lang.com/), and [stylus](http://stylus-lang.com/) are supported.
- Your chosen CSS preprocessor module must also be marked as a dependency in your app's `package.json`.
- `options` *[Object]*: Parameters to send to the CSS preprocessor if it accepts any.
- `minifier` *[Object]*: Params pertaining to CSS minifcation.
- `enable` *[Boolean]*: Whether or not to minify CSS. Can also be disabled by the `minify` param.
- `options` *[Object]*: Parameters to pass to the CSS minifier [clean-css](https://www.npmjs.com/package/clean-css), a list of which can be found in the [clean-css docs](https://github.com/jakubpawlowicz/clean-css#constructor-options).
- `allowlist` *[Array of Strings]*: List of CSS files to allow for compiling. Leave undefined to compile all files. Supply a `:` character after each file name to delimit an alternate file path and/or file name for the minified file.
- Example array member: `"example.less:example.min.css"` compiles `example.less` into `example.min.css`.
- `output` *[String]*: Subdirectory within `publicFolder` where compiled CSS files will be written to.
- `versionFile` *[Object]*: If enabled, Roosevelt will create a CSS file which declares a CSS variable containing your app's version number from `package.json`. Enable this option by supplying an object with the member variables `fileName` and `varName`. Versioning your static files is useful for resetting your users' browser cache when you release a new version of your app.
- Example usage (with SASS): `{ "fileName": "_version.scss", "varName": "appVersion" }`
- Assuming the default Roosevelt configuration otherwise, this will result in a file `statics/css/_version.scss` with the following content: `/* do not edit; generated automatically by Roosevelt */ $appVersion: '0.1.0';`
- Some things to note:
- If there is already a file there with that name, this will overwrite it, so be careful!
- It's generally a good idea to add this file to .gitignore, since it is a build artifact.
Default: *[Object]*
```json
{
"sourcePath": "css",
"compiler": {
"enable" : false,
"module": "less",
"options": {}
},
"minifier": {
"enable": true,
"options": {}
},
"allowlist": null,
"output": "css",
"versionFile": null
}
```
- `cssCompiler` *[Function]*: Use this param to supply a custom CSS preprocessor function.
- To do so, supply a function which accepts argument `app`, which is a reference to the [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
- The function should return an object with the following members:
- `versionCode(app)` *[Function]*: Function to return the version of your app. This is needed to support the `versionFile` feature of Roosevelt's CSS preprocessor API.
- `app` *[Object]*: The [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
- `parse(app, fileName)` *[Function]*: Function to preprocess CSS.
- `app` *[Object]*: The [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
- `filePath` *[String]*: The path to the file being preprocessed.
- When a custom preprocessor is defined in this way it will override the selected preprocessor specified in `css.compiler.module`.
This param can only set via Roosevelt's constructor, like this:
```js
(async () => {
await require('roosevelt')({
cssCompiler: app => {
return {
versionCode: app => {
// write code to return the version of your app here
// generally you should return a css variable with your app version
},
parse: (app, filePath) => {
// write code to preprocess CSS here
return {
css: 'write code to output css here',
sourceMap: 'write code to output source map here (optional)'
}
}
}
}
}).startServer()
})()
```
- `favicon` *[String]*: Location of your [favicon](https://en.wikipedia.org/wiki/Favicon) file. Default: `"none"`.
- Will be set to `"images/favicon.ico"` in apps generated with the app generator.
- `js` *[Object]*: How you want Roosevelt to handle module bundling and minifying your frontend JS:
- `sourcePath` *[String]*: Subdirectory within `staticsRoot` where your JS files are located. By default this folder will not be made public, but is instead meant to store unminified JS source files which will be minified and written to the `public` folder when the app is started.
- `[bundler name]` *[String]*: Parameters related to bundling JS the specified bundler module:
- Values you can supply to `[bundler name]`:
- `webpack`: See [Webpack site](https://webpack.js.org/) for more details about [Webpack configuration](https://webpack.js.org/configuration/).
- `customBundler`: Allows you to define your own custom bundler.
- Params you can pass to your chosen bundler:
- `enable` *[Boolean]*: Enable the bundler.
- `bundles`: *[Array of Objects]* Declare one or more JavaScript bundle files.
- `env`: *[String]* Bundle only in development or production mode.
- Accepted values:
- `"development"`: Development mode.
- `"production"`: Production mode.
- If no value is set, it will bundle in both modes.
- `config`: *[Object or String]* The config to send to the module bundler. Can also be a path to a config file relative to the app directory.
- `customBundlerFunction`: *[Function]* A custom async function to execute for this bundler instead of executing the default one supplied by Roosevelt. This param is required if your bundler is set to `customBundler`.
- Arguments provided:
- `bundle`: The bundle object supplied by Roosevelt.
- `config`: The config object after it has been postprocessed by Roosevelt.
- `app`: The Roosevelt app.
- `verbose` *[String]*: Enable verbose error handling.
- Accepted values:
- `true`: Will print verbose logs to the console.
- `"file"`: Will print verbose logs to the console and write them to a file for debugging.
Default when an app is created manually: *[Object]*
```json
{
"sourcePath": "js",
"webpack": {
"enable": false,
"bundles": [],
"customBundlerFunction": null
},
"customBundler": {
"enable": false,
"bundles": [],
"customBundlerFunction": null
},
"verbose": false
}
```
Default when an app is created with the app generator: *[Object]*
```json
{
"sourcePath": "js",
"webpack": {
"enable": true,
"bundles": [
{
"config": {
"entry": "${js.sourcePath}/main.js",
"devtool": "source-map",
"output": {
"path": "${publicFolder}/js"
},
"resolve": {
"alias": {
"fs": false,
"path": false
},
"modules": ["${js.sourcePath}", "${publicFolder}/js", "${appDir}", "node_modules"]
}
}
}
],
"customBundlerFunction": null
},
"customBundler": {
"enable": false,
"bundles": [],
"customBundlerFunction": null
},
"verbose": false
}
```
If you're using webpack, Roosevelt will also postprocess your webpack config to do the following things:
- If your config does not set `mode`, then Roosevelt will set `mode` to `development` if Roosevelt is in development mode.
- If your config does not set `devtool`, then Roosevelt will set `devtool` to `source-map` if Roosevelt is in development mode.
- If Roosevelt's `prodSourceMaps` feature is enabled, then Roosevelt will set `devtool` to `source-map` if Roosevelt is in production mode.
- If your config does not set `optimization`, then Roosevelt will set `optimization` to the following:
```javascript
optimization = {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: false // disable LICENSE.txt file generation
})
]
}
```
- `minify` *[Boolean]*: Enables HTML and CSS minification. This feature is automatically disabled during development mode. Minification for JS files is handled by the `js` params above. Default: `true`.
- `minifyHtmlAttributes` *[Object]*: Settings to pass to [minify-html-attributes](https://rooseveltframework.org/docs/minify-html-attributes).
- `enable` *[Boolean or String]*: Whether or not to enable `minify-html-attributes`.
- Available options:
- `"production"`: Enable only in production mode.
- `"development"`: Enable in all modes.
- `true`: Will be taken to mean `"production"`.
- `minifyHtmlAttributesParams`: Params to pass to `minify-html-attributes`.
- Note: Roosevelt will always override 3 params from `minify-html-attributes`:
- `htmlDir` will always be set to Roosevelt's `preprocessedViewsPath`.
- `cssDir` will always be set to Roosevelt's `preprocessedStaticsPath`.
- `jsDir` will always be set to Roosevelt's `preprocessedStaticsPath`.
Default: *[Object]*
```json
{
"enable": false,
"minifyHtmlAttributesParams": {}
}
```
- `prodSourceMaps` *[Boolean]*: Enables source maps for minified CSS and JS files in production mode. Default: `false`.
- `symlinks` *[Array of Objects]*: Declare one or more symlinks to be generated at runtime. Default: `[]`.
- `source` *[String]*: Path to be linked to.
- Roosevelt will not attempt to generate a symlink to a source path that does not exist.
- `dest` *[String]*: Path to place symlink.
- If this destination path already exists it will not be overwritten.
Will be set to the following in apps generated with the app generator:
```json
[
{
"source": "${staticsRoot}/images",
"dest": "${publicFolder}/images"
}
]
```
- `versionedPublic` *[Boolean]*: If set to true, Roosevelt will prepend your app's version number from `package.json` to your public folder. Versioning your public folder is useful for resetting your users' browser cache when you release a new version. Default: `false`.
### Deployment options
- `hostPublic` *[Boolean]*: Whether or not to allow Roosevelt to host the public folder. By default in `production-proxy` mode Roosevelt will not expose the public folder. It's recommended instead that you host the public folder through another web server, such as Apache or nginx that is better optimized for hosting static files. Default: `false`.
- `localhostOnly` *[Boolean]*: Listen only to requests coming from localhost in production mode. This is useful in environments where it is expected that HTTP requests to your app will be proxied through a more traditional web server like Apache or nginx. This setting is ignored in development mode. Default: `true`.
- `shutdownTimeout` *[Number]*: Maximum amount of time in milliseconds given to Roosevelt to gracefully shut itself down when sent the kill signal. Default: `30000` (30 seconds).
### Template literals in `rooseveltConfig` values
All config values support [template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) style variable syntax that you can use to refer to other Roosevelt parameters. For example:
```json
{
"css": {
"sourcePath": "css",
"output": ".build/${css.sourcePath}"
}
}
```
Resolves to:
```json
{
"css": {
"sourcePath": "css",
"output": ".build/css"
}
}
```
### Events
Roosevelt provides a series of events you can attach code to by passing a function to the desired event as a parameter to Roosevelt's constructor like so:
```js
(async () => {
await require('roosevelt')({
onServerStart: (app) => { /* do something */ }
}).startServer()
})()
```
#### Event list
These are sorted in order of when they are executed during the lifecycle of a Roosevelt app.
- `onBeforeMiddleware(app)`: Fired when the app begins initializing, prior to any middleware being loaded into the app.
- `app`: The [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
- `onBeforeControllers(app)`: Fired during initialization, prior to any routes being loaded.
- `app`: The [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
- `onBeforeStatics(app)`: Fired during initialization, prior to any statics being written.
- `app`: The [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
- `onClientViewsProcess(template)`: Fired to preprocess templates before being exposed to the client.
- `template`: A string containing a template written in any JS-based templating engine (e.g. Teddy, Pug, ejs, etc).
- `onServerInit(app)`: Fired when the server is fully initialized and all middleware has been loaded but before the server has started.
- `app`: The [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
- `onServerStart(app)`: Fired when the server starts.
- `app`: The [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
- `onAppExit(app)`: Fired when the app recieves a kill signal.
- `app`: The [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
### Express variables exposed by Roosevelt
Roosevelt supplies several variables to Express that you may find handy. Access them using `app.get('variableName')`.
- `appDir`: The directory the main module is in.
- `appName`: The name of your app derived from `package.json`. Uses "Roosevelt Express" if no name is supplied.
- `appVersion`: The version number of your app derived from `package.json`.
- `controllersPath`: Full path on the file system to where your app's controllers folder is located.
- `clientControllersBundledOutput`: Full path on the file system to where your app's client-exposed controllers folder is located.
- `clientViewsBundledOutput`: Full path on the file system to where your app's client-exposed views folder is located.
- `cssCompiledOutput`: Full path on the file system to where your app's minified CSS files are located.
- `cssPath`: Full path on the file system to where your app's CSS source files are located.
- `debugMarkup`: HTML you can add to your custom error pages if you define any that will print server errors if any exist, display the route list, and add some inline JavaScript that will serialize the request's `err`, `req`, and `res` objects so you can interactively examine them in the browser's developer tools. Only available in development mode.
- `env`: Either `development` or `production`.
- `express`: The Express module.
- `expressSession`: The [express-session](https://github.com/expressjs/session) module Roosevelt uses internally. Session middleware.
- `expressSessionStore`: The session store instance used by [express-session](https://github.com/expressjs/session) module Roosevelt uses internally.
- `htmlPath`: Full path on the file system to where your app's HTML static page source files are located.
- `htmlRenderedOutput`: Full path on the file system to where your app's rendered and minified static HTML files are located.
- `httpServer`: The [http server](https://nodejs.org/api/http.html#http_class_http_server) created by Roosevelt.
- `httpsServer`: The [https server](https://nodejs.org/api/https.html#https_class_https_server) created by Roosevelt.
- `jsPath`: Full path on the file system to where your app's JS source files are located.
- `logger`: The [roosevelt-logger](https://rooseveltframework.org/docs/roosevelt-logger) module Roosevelt uses internally. Used for console logging.
- `modelsPath`: Full path on the file system to where your app's models folder is located.
- `package`: The contents of `package.json`.
- `params`: The parameters you sent to Roosevelt.
- `preprocessedStaticsPath` or `preprocessedStatics`: Full path on the file system to where your app's preprocessed statics folder is located.
- `preprocessedViewsPath` or `preprocessedViews`: Full path on the file system to where your app's preprocessed views folder is located.
- `publicFolder`: Full path on the file system to where your app's public folder is located.
- `roosevelt:state`: Application state, e.g. `disconnecting` if the app is currently being shut down.
- `router`: Instance of router module used by Roosevelt.
- `routePrefix`: Prefix appended to routes via the `routePrefix` param. Will be `''` if not set.
- `routes`: List of all routes in the app.
- `staticsRoot`: Full path on the file system to where your app's statics folder is located.
- `view engine`: Default view engine file extension, e.g. `.html`.
- *viewEngine* e.g. `teddy` by default: Any view engine(s) you define will be exposed as an Express variable. For instance, the default view engine is teddy. So by default `app.get('teddy')` will return the `teddy` module.
- `viewsPath` or `views`: Full path on the file system to where your app's views folder is located.
Additionally the Roosevelt constructor returns the following object:
- `expressApp` *[Object]*: The [Express app](http://expressjs.com/api.html#express) created by Roosevelt.
- `initServer(callback)` or `init(callback)` *[async Function]*: Starts the HTML validator, sets up some middleware, runs the CSS and JS preprocessors, and maps routes, but does not start the HTTP server. Call this method manually first instead of `startServer` if you need to setup the Express app, but still need to do additional setup before the HTTP server is started. This method is automatically called by `startServer` once per instance if it has not yet already been called. Takes an optional callback.
- `startServer()` or `start()` *[async Function]*: Calls the `listen` method of `http`, `https`, or both (depending on your configuration) to start the web server with Roosevelt's config.
- `stopServer(params)` or `stop(params)` *[Function]*: Stops the server from accepting new connections before exiting and takes an optional argument `stopServer({ persistProcess: true })` which will allow the process to remain active after the server has closed.
## Recognized environment variables
The following is a list of [environment variables](https://en.wikipedia.org/wiki/Environment_variable) that Roosevelt listens for.
- `NODE_ENV`:
- Set to `production` to force the app into production mode.
- Set to `development` to force the app into development mode.
- `NODE_PORT`: Default HTTPS port to run your app on.
- Will set HTTP port instead if HTTPS is disabled.
- `HTTP_PORT`: Default HTTP port to run your app on. Takes precedence over `NODE_PORT`.
- `HTTPS_PORT`: Default HTTPS port to run your app on.
- `DISABLE_HTTPS`: When set to `true`, the HTTPS server will be disabled and the app will revert to HTTP regardless of what is set in the `rooseveltConfig`.
- `MAKE_BUILD_ARTIFACTS`: Lets you set Roosevelt's `makeBuildArtifacts` param via environment variable.
Environment variable precedence:
- Environment variables supersede your app's `rooseveltConfig`.
- Environment variables can be overridden with command line arguments.
## Command line usage
### Available npm scripts
Roosevelt apps created with the app generator come with the following notable [npm scripts](https://docs.npmjs.com/misc/scripts) prepopulated in [package.json](https://docs.npmjs.com/files/package.json):
- `npm run production`: Runs the app in production mode.
- Default shorthands:
- `npm run prod`
- `npm run p`
- `npm start`
- Script is short for: `nodemon app.js --production-mode`
- `npm run development`: Runs the app in development mode.
- Default shorthands:
- `npm run dev`
- `npm run d`
- Script is short for: `nodemon app.js --development-mode`
- `npm run production-proxy`: Runs the app in production mode, but with `localhostOnly` set to true and `hostPublic` set to false. This mode will make it so your app only listens to requests coming from localhost and does not serve anything in the public folder. This mode is useful when you want to host your app behind a reverse proxy from a web server like Apache or nginx and [is considered a best practice for Node.js deployments](https://expressjs.com/en/advanced/best-practice-performance.html#use-a-reverse-proxy).
- Default shorthands:
- `npm run prodproxy`
- `npm run x`
- Script is short for: `nodemon app.js --production-proxy-mode`
- `npm run generate-certs`: Generates self-signed HTTPS certs for your app.
- Script is short for: `node ./node_modules/roosevelt/lib/scripts/certsGenerator.js`
- Supports command line flags `--appDir somewhere` `--secretsPath somewhere` to override those default locations.
- `npm run generate-session-secret`: Generates a secret key for the `express-session` module.
- Script is short for: `node ./node_modules/roosevelt/lib/scripts/sessionSecretGenerator.js`
- Supports command line flags `--appDir somewhere` `--secretsPath somewhere` to override those default locations.
- `npm run generate-secrets`: Runs the above three scripts.
- Supports command line flags `--appDir somewhere` `--secretsPath somewhere` to override those default locations.
### Available command line arguments
- `node app.js --production-mode`: Runs the app in production mode.
- Default shorthands:
- `--prod`
- `-p`
- `node app.js --development-mode`: Runs the app in development mode.
- Default shorthands:
- `--dev`
- `-d`
- `node app.js --build`: Only runs the build scripts and doesn't start the app.
- Default shorthands:
- `-b`
- `node app.js --jsbundler=verbose`: Prints verbose errors from the JS bundler to the console.
- Default shorthands:
- `--jsb=verbose`
- `-j=verbose`
- `node app.js --jsbundler=verbose-file`: Prints verbose errors from the JS bundler to the console as well as write a jsBundlerError.txt file to the app's root directory containing the full error.
- Default shorthands:
- `--jsb=verbose-file`
- `-j=verbose-file`
- `node app.js --production-proxy-mode`: Runs the app in production mode, but with `localhostOnly` set to true and `hostPublic` set to false. This mode will make it so your app only listens to requests coming from localhost and does not serve anything in the public folder. This mode is useful when you want to host your app behind a reverse proxy from a web server like Apache or nginx and [is considered a best practice for Node.js deployments](https://expressjs.com/en/advanced/best-practice-performance.html#use-a-reverse-proxy).
- Default shorthands:
- `--prodproxy`
- `-x`
- `node app.js --enable-validator`: Forces the HTML validator to be enabled.
- Default shorthands:
- `--html-validator`
- `-h`
- `node app.js --disable-validator`: Forces the HTML validator to be disabled.
- Default shorthands:
- `--raw`
- `-r`
### Combining npm scripts and command line arguments
The npm scripts can be combined with the command line flags.
For example, running `npm run dev -- --disable-validator` will run your app in development mode and force the HTML validator to be disabled.