UNPKG

hapi

Version:

HTTP Server framework

853 lines (733 loc) 133 kB
# 1.0.x API Reference - [`Hapi.Server`](#hapiserver) - [`new Server([host], [port], [options])`](#new-serverhost-port-options) - [`createServer([host], [port], [options])`](#createServerhost-port-options) - [Server options](#server-options) - [`Server` properties](#server-properties) - [`Server` methods](#server-methods) - [`server.start([callback])`](#serverstartcallback) - [`server.stop([options], [callback])`](#serverstopoptions-callback) - [`server.route(options)`](#serverrouteoptions) - [Route options](#route-options) - [Path processing](#path-processing) - [Path parameters](#path-parameters) - [Route handler](#route-handler) - [Route prerequisites](#route-prerequisites) - [Route not found](#route-not-found) - [`server.route(routes)`](#serverrouteroutes) - [`server.routingTable()`](#serverroutingtable) - [`server.log(tags, [data, [timestamp]])`](#serverlogtags-data-timestamp) - [`server.state(name, [options])`](#serverstatename-options) - [`server.views(options)`](#serverviewsoptions) - [`server.auth(name, options)`](#serverauthname-options) - [Basic authentication](#basic-authentication) - [Cookie authentication](#cookie-authentication) - [Hawk authentication](#hawk-authentication) - [Bewit authentication](#bewit-authentication) - [`server.ext(event, method, [options])`](#serverextevent-method-options) - [Request lifecycle](#request-lifecycle) - [`server.helper(name, method, [options])`](#serverhelpername-method-options) - [`server.inject(options, callback)`](#serverinjectoptions-callback) - [`Server` events](#server-events) - [Request object](#request-object) - [`request` properties](#request-properties) - [`request` methods](#request-methods) - [`request.setUrl(url)`](#requestseturlurl) - [`request.setMethod(method)`](#requestsetmethodmethod) - [`request.log(tags, [data, [timestamp]])`](#requestlogtags-data-timestamp) - [`request.getLog([tags])`](#requestgetlogtags) - [`request.tail([name])`](#requesttailname) - [`request.setState(name, value, [options])`](#requestsetstatename-value-options) - [`request.clearState(name)`](#requestclearstatename) - [`request.reply([result])`](#requestreplyresult) - [`request.reply.redirect(uri)`](#requestreplyredirecturi) - [`request.reply.view(template, [context, [options]])`](#requestreplyviewtemplate-context-options) - [`request.reply.close()`](#requestreplyclose) - [`request.generateView(template, context, [options])`](#requestgenerateviewtemplate-context-options) - [`request.response()`](#requestresponse) - [`Hapi.response`](#hapiresponse) - [Flow control](#flow-control) - [Response types](#response-types) - [`Generic`](#generic) - [`Empty`](#empty) - [`Text`](#text) - [`Buffer`](#buffer) - [`Stream`](#stream) - [`Obj`](#obj) - [`File`](#file) - [`Redirection`](#redirection) - [`View`](#view) - [`Cacheable`](#cacheable) - [`Hapi.error`](#hapierror) - [Error transformation](#error-transformation) - [`badRequest([message])`](#badrequestmessage) - [`unauthorized(message, [scheme, [attributes]])`](#unauthorizedmessage-scheme-attributes) - [`unauthorized(message, wwwAuthenticate)`](#unauthorizedmessage-wwwauthenticate) - [`clientTimeout([message])`](#clienttimeoutmessage) - [`serverTimeout([message])`](#servertimeoutmessage) - [`forbidden([message])`](#forbiddenmessage) - [`notFound([message])`](#notfoundmessage) - [`internal([message, [data]])`](#internalmessage-data) - [`passThrough(code, payload, contentType, headers)`](#passthroughcode-payload-contenttype-headers) - [`Hapi.Pack`](#hapipack) - [`new Pack([options])`](#new-packoptions) - [`Pack` properties](#pack-properties) - [`Pack` methods](#pack-methods) - [`pack.server([host], [port], [options])`](#packserverhost-port-options) - [`pack.start([callback])`](#packstartcallback) - [`pack.stop([options], [callback])`](#packstopoptions-callback) - [`pack.allow(permissions)`](#packallowpermissions) - [`pack.require(name, options, callback)`](#packrequirename-options-callback) - [`pack.require(names, callback)`](#packrequirenames-callback) - [`pack.register(plugin, options, callback)`](#packregisterplugin-options-callback) - [`Hapi.Composer`](#hapicomposer) - [`new Composer(manifest)`](#new-composermanifest) - [`composer.compose(callback)`](#composercomposecallback) - [`composer.start([callback])`](#composerstartcallback) - [`composer.stop([options], [callback])`](#composerstopoptions-callback) - [Plugin interface](#plugin-interface) - [`exports.register(plugin, options, next)`](#exportsregisterplugin-options-next) - [Root methods and properties](#root-methods-and-properties) - [`plugin.version`](#pluginversion) - [`plugin.path`](#pluginpath) - [`plugin.hapi`](#pluginhapi) - [`plugin.app`](#pluginapp) - [`plugin.events`](#pluginevents) - [`plugin.log(tags, [data, [timestamp]])`](#pluginlogtags-data-timestamp) - [`plugin.dependency(deps)`](#plugindependencydeps) - [`plugin.views(options)`](#pluginviewsoptions) - [`plugin.helper(name, method, [options])`](#pluginhelpername-method-options) - [`plugin.cache(options)`](#plugincacheoptions) - [Selectable methods and properties](#selectable-methods-and-properties) - [`plugin.select(labels)`](#pluginselectlabels) - [`plugin.length`](#pluginlength) - [`plugin.api(key, value)`](#pluginapikey-value) - [`plugin.api(obj)`](#pluginapiobj) - [`plugin.route(options)`](#pluginrouteoptions) - [`plugin.route(routes)`](#pluginrouteroutes) - [`plugin.state(name, [options])`](#pluginstatename-options) - [`plugin.auth(name, options)`](#pluginauthname-options) - [`plugin.ext(event, method, [options])`](#pluginextevent-method-options) - [`Hapi.utils`](#hapiutils) - [`version()`](#version) - [`Hapi.types`](#hapitypes) - [`Hapi.state`](#hapistate) - [`prepareValue(name, value, options, callback)`](#preparevaluename-value-options-callback) ## `Hapi.Server` ### `new Server([host], [port], [options])` Creates a new server instance with the following arguments: - `host` - the hostname or IP address the server is bound to. Defaults to `0.0.0.0` which means any available network interface. Set to `127.0.0.1` or `localhost` to restrict connection to those coming from the same machine. - `port` - the TPC port the server is listening to. Defaults to port `80` for HTTP and to `443` when TLS is configured. to use an ephemeral port, use `0` and once the server is started, retrieve the port allocation via `server.info.port`. - `options` - An object with the server configuration as described in [server options](#server-options). ```javascript var Hapi = require('hapi'); var server = new Hapi.Server('localhost', 8000, { cors: true }); ``` ### `createServer([host], [port], [options])` An alternative method for creating a server instance using the same arguments as `new Server()`. ```javascript var Hapi = require('hapi'); var server = Hapi.createServer('localhost', 8000, { cors: true }); ``` ### Server options When creating a server instance, the following options configure the server's behavior: - `app` - application-specific configuration. Provides a safe place to store application configuration without potential conflicts with **hapi**. Should not be used by plugins which should use `plugins[name]`. <p></p> - `auth` - configures one or more authentication strategies. The `auth` key can be set to a single strategy object (the name will default to `'default'`), or to an object with multiple strategies where the strategy name is the object key. The authentication strategies and their options are described in [`server.auth()`](#serverauthname-options). <p></p> - <a name="server.config.cache"></a>`cache` - determines the type of server-side cache used. Every server includes a cache for storing and reusing request responses and helper results. By default a simple memory-based cache is used which has very limited capacity and is not suitable for production environments. In addition to the memory cache, a Redis-based or a MongoDB-based cache can be configured. Actual caching is only utilized if routes, helpers, and plugins are explicitly configured to store their state in the cache. The server cache configuration only defines the store itself. The `cache` options are described in the [**catbox** module documentation](https://github.com/spumko/catbox#client). <p></p> - `cors` - the [Cross-Origin Resource Sharing](http://www.w3.org/TR/cors/) protocol allows browsers to make cross-origin API calls. CORS is required by web application running inside a browser which are loaded from a different domain than the API server. CORS headers are disabled by default. To enable, set `cors` to `true`, or to an object with the following options: - `origin` - a strings array of allowed origin servers ('Access-Control-Allow-Origin'). Defaults to any origin `['*']`. - `maxAge` - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to `86400` (one day). - `headers` - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to `['Authorization', 'Content-Type', 'If-None-Match']`. - `additionalHeaders` - a strings array of additional headers to `headers`. Use this to keep the default headers in place. - `methods` - a strings array of allowed HTTP methods ('Access-Control-Allow-Methods'). Defaults to `['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']`. - `additionalMethods` - a strings array of additional methods to `methods`. Use this to keep the default methods in place. - `exposedHeaders` - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to `['WWW-Authenticate', 'Server-Authorization']`. - `additionalExposedHeaders` - a strings array of additional headers to `exposedHeaders`. Use this to keep the default headers in place. - `credentials` - if `true`, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to `false`. <p></p> - `debug` - controls the error types sent to the console: - `request` - a string array of request log tags to be displayed via `console.error()` when the events are logged via `request.log()`. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error (500) error response. For example, to display all errors, change the option to `['error', 'uncaught']`. To turn off all console debug messages set it to `false`. <p></p> - <a name="server.config.files"></a>`files` - defines the behavior for serving static resources using the built-in route handlers for files and directories: - `relativeTo` - determines how relative paths are resolved. Available values: - `'cwd'` - relative paths are resolved using the active process path (`process.cwd()`). This is the default setting. - `'routes'` - relative paths are resolved relative to the source file in which the `server.route()` method is called. This means the location of the source code determines the location of the static resources when using relative paths. - an absolute path (e.g. '/path') used as prefix for all relative paths. <p></p> - `labels` - a string array of labels used when registering plugins to [`plugin.select()`](#pluginselectlabels) matching server labels. Defaults to an empty array `[]` (no labels). <p></p> - <a name="server.config.location"></a>`location` - used to convert relative 'Location' header URIs to absolute, by adding this value as prefix. Value must not contain a trailing `'/'`. Defaults to the host received in the request HTTP 'Host' header and if missing, to `server.info.uri`. <p></p> - <a name="server.config.payload"></a>`payload` - controls how incoming payloads (request body) are processed: - `maxBytes` - limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. Defaults to `1048576` (1MB). <p></p> - `plugins` - plugin-specific configuration. Provides a place to store and pass plugin configuration that is at server-level. The `plugins` is an object where each key is a plugin name and the value is the configuration. <p></p> - <a name="server.config.router"></a>`router` - controls how incoming request URIs are matched against the routing table: - `isCaseSensitive` - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to `true`. - `normalizeRequestPath` - determines whether request paths should be normalized prior to matching. Normalization percent-encodes reserved characters, decodes unreserved characters, and capitalizes any percent encoded values. Useful when serving non-compliant HTTP clients. Defaults to `false`. <p></p> - <a name="server.config.state"></a>`state` - HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in [RFC 6265](https://tools.ietf.org/html/rfc6265)). - `cookies` - The server automatically parses incoming cookies based on these options: - `parse` - determines if incoming 'Cookie' headers are parsed and stored in the `request.cookies` object. Defaults to `true`. - `failAction` - determines how to handle cookie parsing errors. Allowed values are: - `'error'` - return a Bad Request (400) error response. This is the default value. - `'log'` - report the error but continue processing the request. - `'ignore'` - take no action. - `clearInvalid` - if `true`, automatically instruct the client to remove invalid cookies. Defaults to `false`. - `strictHeader` - if `false`, allows any cookie value including values in violation of [RFC 6265](https://tools.ietf.org/html/rfc6265). Defaults to `true`. <p></p> - `timeout` - define timeouts for processing durations: - `server` - response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response. Disabled by default (`false`). - `client` - request timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response. Set to `false` to disable. Defaults to `10000` (10 seconds). - `socket` - by default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Defaults to `undefined` which leaves the node default unchanged. Set to `false` to disable socket timeouts. <p></p> - `tls` - used to create an HTTPS server. The `tls` object is passed unchanged as options to the node.js HTTPS server as described in the [node.js HTTPS documentation](http://nodejs.org/api/https.html#https_https_createserver_options_requestlistener). <p></p> - <a name="server.config.views"></a>`views` - enables support for view rendering (using templates to generate responses). Disabled by default. To enable, set to an object with the following options: - `engines` - (required) an object where each key is a file extension (e.g. 'html', 'jade'), mapped to the npm module name (string) used for rendering the templates. Alternatively, the extension can be mapped to an object with the following options: - `module` - the npm module name (string) to require or an object with: - `compile(template, options)` - rendering function. Returns a function with signature `function(context, options)`. Follows the convention used in [handlebars](https://github.com/wycats/handlebars.js/). - any of the `views` options listed below (except `defaultExtension`) to override the defaults for a specific engine. - `defaultExtension` - defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value. - `path` - the root file path used to resolve and load the templates identified when calling `request.reply.view()`. Defaults to current working directory. - `partialsPath` - the root file path where partials are located. Partials are small segments of template code that can be nested and reused throughout other templates. Defaults to no partials support (empty path). - `basePath` - a base path used as prefix for `path` and `partialsPath`. No default. - `layout` - if set to `true`, layout support is enabled. A layout is a single template file used as the parent template for other view templates in the same engine. The layout template name must be 'layout.ext' where 'ext' is the engine's extension. Defaults to `false`. - `layoutKeyword` - the key used by the template engine to denote where primary template content should go. Defaults to `'content'`. - `encoding` - the text encoding used by the templates when reading the files and outputting the result. Defaults to `'utf-8'`. - `isCached` - if set to `false`, templates will not be cached (thus will be read from file on every use). Defaults to `true`. - `allowAbsolutePaths` - if set to `true`, allows absolute template paths passed to `request.reply.view()`. Defaults to `false`. - `allowInsecureAccess` - if set to `true`, allows template paths passed to `request.reply.view()` to contain '../'. Defaults to `false`. - `compileOptions` - options object passed to the engine's compile function. Defaults to empty options `{}`. - `runtimeOptions` - options object passed to the returned function from the compile operation. Defaults to empty options `{}`. - `contentType` - the content type of the engine results. Defaults to `'text/html'`. ### `Server` properties Each instance of the `Server` object have the following properties: - `app` - application-specific state. Provides a safe place to store application data without potential conflicts with **hapi**. Should not be used by plugins which should use `plugins[name]`. - `helpers` - helper functions registered with [`server.helper()`](#serverhelpername-method-options). - `info` - server information: - `port` - the port the server was configured to (before `start()`) or bound to (after `start()`). - `host` - the hostname the server was configured to (defaults to `'0.0.0.0'` if no host was provided). - `protocol` - the protocol used (e.g. `'http'` or `'https'`). - `uri` - a string with the following format: 'protocol://host:port' (e.g. 'http://example.com:8080'). - `listener` - the node HTTP server object. - `pack` - the [`Pack`](#hapipack) object the server belongs to (automatically assigned when creating a server instance directly). - `plugins` - an object where each key is a plugin name and the value is the API registered by that plugin using [`plugin.api()`](#pluginapikey-value). - `settings` - an object containing the [server options](#server-options) after applying the defaults. ### `Server` methods #### `server.start([callback])` Starts the server by listening for incoming connections on the configured port. If provided, `callback()` is called once the server is ready for new connections. If the server is already started, the `callback()` is called on the next tick. ```javascript var Hapi = require('hapi'); var server = new Hapi.Server(); server.start(function () { console.log('Server started at: ' + server.info.uri); }); ``` #### `server.stop([options], [callback])` Stops the server by refusing to accept any new connections. Existing connections will continue until closed or timeout (defaults to 5 seconds). Once the server stopped, all the connections have ended, and it is safe to exit the process, the callback (if provided) is called. If the server is already stopped, the `callback()` is called on the next tick. The optional `options` object supports: - `timeout` - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to `5000` (5 seconds). ```javascript server.stop({ timeout: 60 * 1000 }, function () { console.log('Server stopped'); }); ``` #### `server.route(options)` Adds a new route to the server where: - `options` - the route configuration as described in [route options](#route-options). ##### Route options The following options are available when adding a route: - `path` - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server [`router`](#server.config.router) configuration option. The path can include named parameters enclosed in `{}` which will be matched against literal values in the request as described in [Path parameters](#path-parameters). <p></p> - `method` - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use `*` to match against any HTTP method (only when an exact match was not found). <p></p> - `vhost` - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. <p></p> - `handler` - (required) the function called to generate the response after successful authentication and validation. The handler function is described in [Route handler](#route-handler). Alternatively, `handler` can be set to the string `'notfound'` to return a Not Found (404) error response, or `handler` can be assigned an object with one of: - <a name="route.config.file"></a>`file` - generates a static file endpoint for serving a single file. `file` can be set to: - a relative or absolute file path string (relative paths are resolved based on the server [`files`](#server.config.files) configuration). - a function with the signature `function(request)` which returns the relative or absolute file path. - an object with the following options: - `path` - a path string or function as described above. - `mode` - specifies whether to include the 'Content-Disposition' header with the response. Available values: - `false` - header is not included. This is the default value. - `'attachment'` - `'inline'` <p></p> - <a name="route.config.directory"></a>`directory` - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a single path parameter at the end of the path string (e.g. '/path/to/somewhere/{param}' where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. '{param}' for one level files only, '{param?}' for one level files or the directory root, '{param*}' for any level, or '{param*3}' for a specific level). The directory handler is an object with the following options: - `path` - (required) the directory root path (relative paths are resolved based on the server [`files`](#server.config.files) configuration). Value can be: - a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. - an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). - a function with the signature `function(request)` which returns the path string. - `index` - optional boolean, determines if 'index.html' will be served if found in the folder when requesting a directory. Defaults to `true`. - `listing` - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to `false`. - `showHidden` - optional boolean, determines if hidden files will be shown and served. Defaults to `false`. <p></p> - `proxy` - generates a reverse proxy handler with the following options: - `host` - the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host. - `port` - the upstream service port. - `protocol` - The protocol to use when making a request to the proxied host: - `'http'` - `'https'` - `passThrough` - if `true`, forwards the headers sent from the client to the upstream service being proxied to. Defaults to `false`. - `xforward` - if `true`, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to `false`. - `mapUri` - a function used to map the request URI to the proxied URI. The function signature is `function(request, callback)` where: - `request` - is the incoming `request` object - `callback` - is `function(err, uri)` where `uri` is the absolute proxy URI. Cannot be used together with `host`, `port`, or `protocol`. - `postResponse` - a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is `function(request, settings, res, payload)` where: - `request` - is the incoming `request` object. It is the responsibility of the `postResponse()` function to call `request.reply()`. - `settings` - the proxy handler configuration. - `res` - the node response object received from the upstream service. - `payload` - the response payload. - `httpClient` - an alternative HTTP client function, compatible with the [**request**](https://npmjs.org/package/request) module `request()` interface. <p></p> - <a name="route.config.view"></a>`view` - generates a template-based response. The `view` options is set to the desired template file name. The view context available to the template includes: - `payload` - maps to `request.payload`. - `params` - maps to `request.params`. - `query` - maps to `request.query`. <p></p> - `config` - additional route configuration (the `config` options allows splitting the route information from its implementation): - `handler` - an alternative location for the route handler function. Same as the `handler` option in the parent level. Can only include one handler per route. <p></p> - `pre` - an array with prerequisites methods which are executed in serial or in parallel before the handler is called and are described in [Route prerequisites](#route-prerequisites). <p></p> - `validate` - `query` - validation rules for an incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs (see [Query String](http://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options)) and stored in `request.query` prior to validation. Values allowed: - `true` - any query parameters allowed (no validation performed). This is the default. - `false` - no query parameters allowed. - a validation rules object as described in the [Joi](http://github.com/spumko/joi) module. <p></p> - `payload` - validation rules for an incoming request payload (request body). Values allowed: - `true` - any payload allowed (no validation performed). This is the default. - `false` - no payload allowed. - a validation rules object as described in the [Joi](http://github.com/spumko/joi) module. <p></p> - `path` - validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in `request.params`. Values allowed: - `true` - any path parameters allowed (no validation performed). This is the default. - `false` - no path variables allowed. - a validation rules object as described in the [Joi](http://github.com/spumko/joi) module. <p></p> - `response` - validation rules for the outgoing response payload (response body). Can only validate [object](#obj) response. Values allowed: - `true` - any payload allowed (no validation performed). This is the default. - `false` - no payload allowed. - an object with the following options: - `schema` - the validation schema as described in the [Joi](http://github.com/spumko/joi) module. - `sample` - the percent of responses validated (0 - 100). Set to `0` to disable all validation. Defaults to `100` (all responses). - `failAction` - defines what to do when a response fails validation. Options are: - `error` - return an Internal Server Error (500) error response. This is the default value. - `log` - log the error but send the response. <p></p> - `payload` - determines how the request payload is processed. Defaults to `'parse'` if `validate.payload` is set or when `method` is `'POST'` or `'PUT'`, otherwise `'stream'`. Payload processing is configured using the server [`payload`](#server.config.payload) configuration. Options are: - `'stream'` - the incoming request stream is left untouched, leaving it up to the handler to process the request via `request.raw.req`. - `'raw'` - the payload is read and stored in `request.rawPayload` as a `Buffer` and is not parsed. - `'parse'` - the payload is read and stored in `request.rawPayload` as a `Buffer`, and then parsed (JSON or form-encoded) and stored in `request.payload`. Parsing is performed based on the incoming request 'Content-Type' header. If the parsing is enabled and the format is unknown, a Bad Request (400) error response is sent. The supported mime types are: - application/json - application/x-www-form-urlencoded - multipart/form-data ([formidable](https://npmjs.org/package/formidable) is used for processing this data and is capable of receiving files as well as other form data. All values are assigned to their respective form names in `request.payload`. <p></p> - `cache` - if the route method is 'GET', the route can be configured to use the cache. The `cache` options are described in the [**catbox** module documentation](https://github.com/spumko/catbox#policy) with some additions: - `mode` - cache location. Available values: - `'client'` - caching is performed on the client by sending the HTTP `Cache-Control` header. This is the default value. - `'server'` - caching is performed on the server using the cache strategy configured. - `'client+server'` - caching it performed on both the client and server. - `segment` - optional segment name, used to isolate cached items within the cache partition. Defaults to the route fingerprint (the route path with parameters represented by a `'?'` character). Note that when using the MongoDB cache strategy, some paths will require manual override as their fingerprint will conflict with MongoDB collection naming rules. When setting segment names manually, the segment must begin with `'//'`. - `privacy` - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: - `'default'` - no privacy flag. This is the default setting. - `'public'` - mark the response as suitable for public caching. - `'private'` - mark the response as suitable only for private caching. - `expiresIn` - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with `expiresAt`. - `expiresAt` - time of day expressed in 24h notation using the 'MM:HH' format, at which point all cache records for the route expire. Cannot be used together with `expiresIn`. - `staleIn` - number of milliseconds to mark an item stored in cache as stale and reload it. Must be less than `expiresIn`. Available only when using server-side caching. - `staleTimeout` - number of milliseconds to wait before checking if an item is stale. Available only when using server-side caching. <p></p> - `auth` - authentication configuration. Value can be: - a string with the name of an authentication strategy registered with `server.auth()`. - a boolean where `false` means no authentication, and `true` means used the `'default'` authentication strategy. - an object with: - `mode` - the authentication mode. Defaults to `'required'` if a server authentication strategy is configured, otherwise defaults to no authentication. Available values: - `'required'` - authentication is required. - `'optional'` - authentication is optional (must be valid if present). - `'try'` - same as `'optional'` but allows for invalid authentication. - `strategies` - a string array of strategy names in order they should be attempted. If only one strategy is used, `strategy` can be used instead. Defaults to `'default'`. - `payload` - if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. [Hawk](#hawk-authentication)). Available values: - `false` - no payload authentication. This is the default value. - `'required'` - payload authentication required. - `'optional'` - payload authentication performed only when the client includes payload authentication information (e.g. `hash` attribute in Hawk). - `tos` - minimum terms-of-service version required (uses the [semver](https://npmjs.org/package/semver) module). If defined, the authentication credentials object must include a `tos` key which satisfies this requirement. Defaults to `false` which means no validation. - `scope` - required application scope. A scope string which must be included in the authentication credentials object in `scope` which is a string array. Defaults to no scope required. - `entity` - the required authenticated entity type. If set, must match the `entity` value of the authentication credentials. Available values: - `any` - the authentication can be on behalf of a user or application. This is the default value. - `user` - the authentication must be on behalf of a user. - `app` - the authentication must be on behalf of an application. <p></p> - `description` - route description used for generating documentation (string). - `notes` - route notes used for generating documentation (string or array of strings). - `tags` - route tags used for generating documentation (array of strings). ```javascript var Hapi = require('hapi'); var server = new Hapi.Server(); // Handler in top level var status = function () { this.reply('ok'); }; server.route({ method: 'GET', path: '/status', handler: status }); // Handler in config var user = { cache: { expiresIn: 5000 }, handler: function () { this.reply({ name: 'John' }); } }; server.route({ method: 'GET', path: '/user', config: user }); ``` ##### Path processing The router iterates through the routing table on each incoming request and executes the first (and only the first) matching route. Route matching is done on the request path only (excluding the query and other URI components). Requests are matches in a deterministic order where the order in which routes are added does not matter. The routes are sorted from the most specific to the most generic. For example, the following path array shows the order in which an incoming request path will be matched against the routes: ```javascript var paths = [ '/', '/a', '/b', '/ab', '/{p}', '/a/b', '/a/{p}', '/b/', '/a/b/c', '/a/b/{p}', '/a/{p}/b', '/a/{p}/c', '/a/{p*2}', '/a/b/c/d', '/a/b/{p*2}', '/a/{p}/b/{x}', '/{p*5}', '/a/b/{p*}', '/{p*}' ]; ``` ##### Path parameters Parameterized paths are processed by matching the named parameters to the content of the incoming request path at that path segment. For example, '/book/{id}/cover' will match '/book/123/cover' and `request.params.id` will be set to `'123'`. Each path segment (everything between the opening '/' and the closing '/' unless it is the end of the path) can only include one named parameter. An optional '?' suffix following the parameter name indicates an optional parameter (only allowed if the parameter is at the ends of the path). For example, the route '/book/{id?}' matches '/book/'. ```javascript var getAlbum = function () { this.reply('You asked for ' + (this.params.song ? this.params.song + ' from ' : '') + this.params.album); }; server.route({ path: '/{album}/{song?}', method: 'GET', handler: getAlbum }); ``` In addition to the optional '?' suffix, a parameter name can also specify the number of matching segments using the '*' suffix, followed by a number greater than 1. If the number of expected parts can be anything, then use '*' without a number (matching any number of segments can only be used in the last path segment). ```javascript var getPerson = function () { var nameParts = this.params.name.split('/'); this.reply({ first: nameParts[0], last: nameParts[1] }); }; server.route({ path: '/person/{name*2}', // Matches '/person/john/doe' method: 'GET', handler: getPerson }); ``` ##### Route handler When a route is matched against an incoming request, the route handler is called and passed a reference to the [request](#request-object) object. The handler method must call [`request.reply()`](#requestreplyresult) or one of its sub-methods to return control back to the router. Route handler functions can use one of three declaration styles: No arguments (the `request` object is bound to `this`, decorated by the `reply` interface): ```javascript var handler = function () { this.reply('success'); }; ``` One argument (the request is passed as an argument, decorated by the `reply` interface): ```javascript var handler = function (request) { request.reply('success'); }; ``` Two arguments (the request and the `reply` interface are passed as arguments): ```javascript var handler = function (request, reply) { reply('success'); }; ``` The two-arguments style is provided for symmetry with extension functions and prerequisite functions where the function signature is `function(request, next)`. In order to enable interchangeable use of these functions, the two argument style does not provide any of the [`request.reply`](#requestreplyresult) decorations. ##### Route prerequisites It is often necessary to perform prerequisite actions before the handler is called (e.g. load required reference data from a database). The route `pre` option allows defining such pre-handler methods. The methods are called in order, unless a `mode` is specified with value `'parallel'` in which case, all the parallel methods are executed first, then the rest in order. `pre` can be assigned a mixed array of: - objects with: - `method` - the function to call (or short-hand helper string as described below). The function signature is `function(request, next)` where: - `request` - the incoming `request` object. - `next` - the function called when the method is done with the signature `function(result)` where: - `result` - any return value including an `Error` object (created via `new Error()` or [`Hapi.error`](#hapierror)). If an error is returned, that value is sent back to the client and the handler method is not called. - `assign` - key name to assign the result of the function to within `request.pre`. - `mode` - set the calling order of the function. Available values: - `'serial'` - serial methods are executed after all the `'parallel'` methods in the order listed. This is the default value. - `'parallel'` - all parallel methods are executed first in parallel before any serial method. The first to return an error response will exist the set. - functions - same as including an object with a single `method` key. - strings - special short-hand notation for [registered server helpers](#serverhelpername-method-options) using the format 'name(args)' (e.g. `'user(params.id)'`) where: - 'name' - the helper name. The name is also used as the default value of `assign`. - 'args' - the helper arguments (excluding `next`) where each argument is a property of `request`. ```javascript var Hapi = require('hapi'); var server = new Hapi.Server(); var pre1 = function (request, next) { next('Hello'); }; var pre2 = function (request, next) { next('World'); }; var pre3 = function (request, next) { next(request.pre.m1 + ' ' + request.pre.m2); }; server.route({ method: 'GET', path: '/', config: { pre: [ { method: pre1, assign: 'm1', mode: 'parallel' }, { method: pre2, assign: 'm2', mode: 'parallel' }, { method: pre3, assign: 'm3' }, ], handler: function () { this.reply(this.pre.m3 + '\n'); } } }); ``` ##### Route not found If the application needs to override the default Not Found (404) error response, it can add a catch-all route for a specific method or all methods. Only one catch-all route can be defined per server instance. ```javascript var Hapi = require('hapi'); var server = new Hapi.Server(); var handler = function () { this.reply('The page was not found').code(404); }; server.route({ method: '*', path: '/{p*}', handler: handler }); ``` #### `server.route(routes)` Same as [server.route(options)](#serverrouteoptions) where `routes` is an array of route options. ```javascript server.route([ { method: 'GET', path: '/status', handler: status }, { method: 'GET', path: '/user', config: user } ]); ``` #### `server.routingTable()` Returns a copy of the routing table. The return value is an array of routes where each route contains: - `settings` - the route config with defaults applied. - `method` - the HTTP method in lower case. - `path` - the route path. ```javascript var table = server.routingTable() console.log(table); /* Output: [{ method: 'get', path: '/test/{p}/end', settings: { handler: [Function], method: 'get', plugins: {}, app: {}, validate: {}, payload: 'stream', auth: undefined, cache: [Object] } }] */ ``` #### `server.log(tags, [data, [timestamp]])` The `server.log()` method is used for logging server events that cannot be associated with a specific request. When called the server emits a `'log'` event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: - `tags` - a string or an array of strings (e.g. `['error', 'database', 'read']`) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the `'hapi'` tag along with event-specific information. - `data` - an optional message string or object with the application data being logged. - `timestamp` - an optional timestamp expressed in milliseconds. Defaults to `Date.now()` (now). ```javascript var Hapi = require('hapi'); var server = new Hapi.Server(); server.on('log', function (event, tags) { if (tags.error) { console.log(event); } }); server.log(['test', 'error'], 'Test event'); ``` #### `server.state(name, [options])` [HTTP state management](http://tools.ietf.org/html/rfc6265) uses client cookies to persist a state across multiple requests. Cookie definitions can be registered with the server using the `server.state()` method, where: - `name` - is the cookie name. - `options` - are the optional cookie settings: - `ttl` - time-to-live in milliseconds. Defaults to `null` (session time-life - cookies are deleted when the browser is closed). - `isSecure` - sets the 'Secure' flag. Defaults to `false`. - `isHttpOnly` - sets the 'HttpOnly' flag. Defaults to `false`. - `path` - the path scope. Defaults to `null` (no path). - `domain` - the domain scope. Defaults to `null` (no domain). - `autoValue` - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. - `encoding` - encoding performs on the provided value before serialization. Options are: - `'none'` - no encoding. When used, the cookie value must be a string. This is the default value. - `'base64'` - string value is encoded using Base64. - `'base64json'` - object value is JSON-stringified than encoded using Base64. - `'form'` - object value is encoded using the _x-www-form-urlencoded_ method. - `'iron'` - Encrypts and sign the value using [**iron**](https://github.com/hueniverse/iron). - `sign` - an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean to verify that the cookie value was generated by the server. Redundant when `'iron'` encoding is used. Options are: - `integrity` - algorithm options. Defaults to [`require('iron').defaults.integrity`](https://github.com/hueniverse/iron#options). - `password` - password used for HMAC key generation. - `password` - password used for `'iron'` encoding. - `iron` - options for `'iron'` encoding. Defaults to [`require('iron').defaults`](https://github.com/hueniverse/iron#options). ```javascript // Set cookie definition server.state('session', { ttl: 24 * 60 * 60 * 1000, // One day isSecure: true, path: '/', encoding: 'base64json' }); // Set state in route handler var handler = function () { var session = this.state.session; if (!session) { session = { user: 'joe' }; } session.last = Date.now(); this.reply('Success').state('session', session); }; ``` Registered cookies are automatically parsed when received. Parsing rules depends on the server [`state.cookies`](#server.config.state) configuration. If an incoming registered cookie fails parsing, it is not included in `request.state`, regardless of the `state.cookies.failAction` setting. When `state.cookies.failAction` is set to `'log'` and an invalid cookie value is received, the server will emit a `'request'` event. To capture these errors subscribe to the `'request'` events and filter on `'error'` and `'state'` tags: ```javascript server.on('request', function (request, event, tags) { if (tags.error && tags.state) { console.error(event); } }); ``` #### `server.views(options)` Initializes the server views manager programmatically instead of via the server [`views`](#server.config.views) configuration option. The `options` object is the same as the server [`views`](#server.config.views) config object. ```javascript server.views({ engines: { html: 'handlebars', jade: 'jade' }, path: '/static/templates' }); ``` #### `server.auth(name, options)` Registers an authentication strategy where: - `name` - is the strategy name (`'default'` is automatically assigned if a single strategy is registered via the server `auth` config). - `options` - required strategy options. Each scheme comes with its own set of required options, in addition to the options sharedby all schemes: - `scheme` - (required, except when `implementation` is used) the built-in scheme name. Available values: - `'basic'` - [HTTP Basic authentication](#basic-authentication) ([RFC 2617](http://tools.ietf.org/html/rfc2617)) - `'cookie'` - [cookie authentication](#cookie-authentication) - `'hawk'` - [HTTP Hawk authentication](#hawk-authentication) ([Hawk protocol](https://github.com/hueniverse/hawk)) - `'bewit'` - [URI Bewit (Hawk)](#bewit-authentication) query authentication ([Hawk protocol](https://github.com/hueniverse/hawk)) - `implementation` - an object with the **hapi** authentication scheme inter