files
dict
{ "content": "Title: Express 5.x - API Reference\n\nURL Source: https://expressjs.com/en/5x/api.html\n\nMarkdown Content:\n**Note**: This is early beta documentation that may be incomplete and is still under development.\n\n**Note**: Express 5.0 requires Node.js 18 or higher.\n\nexpress()\n---------\n\nCreates an Express application. The `express()` function is a top-level function exported by the `express` module.\n\n```\nconst express = require('express')\nconst app = express()\n```\n\n### Methods\n\n### express.json(\\[options\\])\n\nThis is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on [body-parser](https://expressjs.com/resources/middleware/body-parser.html).\n\nReturns middleware that only parses JSON and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts any Unicode encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings.\n\nA new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or an empty object (`{}`) if there was no body to parse, the `Content-Type` was not matched, or an error occurred.\n\nAs `req.body`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input.\n\nThe following table describes the properties of the optional `options` object.\n\n| Property | Description | Type | Default |\n| --- | --- | --- | --- |\n| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` |\n| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `\"100kb\"` |\n| `reviver` | The `reviver` option is passed directly to `JSON.parse` as the second argument. You can find more information on this argument [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). | Function | `null` |\n| `strict` | Enables or disables only accepting arrays and objects; when disabled will accept anything `JSON.parse` accepts. | Boolean | `true` |\n| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `json`), a mime type (like `application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `\"application/json\"` |\n| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` |\n\n### express.static(root, \\[options\\])\n\nThis is a built-in middleware function in Express. It serves static files and is based on [serve-static](https://expressjs.com/resources/middleware/serve-static.html).\n\nNOTE: For best results, [use a reverse proxy](https://expressjs.com/en/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets.\n\nThe `root` argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining `req.url` with the provided `root` directory. When a file is not found, instead of sending a 404 response, it instead calls `next()` to move on to the next middleware, allowing for stacking and fall-backs.\n\nThe following table describes the properties of the `options` object. See also the [example below](https://expressjs.com/en/5x/api.html#example.of.express.static).\n\n| Property | Description | Type | Default |\n| --- | --- | --- | --- |\n| `dotfiles` | Determines how dotfiles (files or directories that begin with a dot “.”) are treated.See [dotfiles](https://expressjs.com/en/5x/api.html#dotfiles) below.\n | String | “ignore” |\n| `etag` | Enable or disable etag generationNOTE: `express.static` always sends weak ETags.\n\n | Boolean | `true` |\n| `extensions` | Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: `['html', 'htm']`. | Mixed | `false` |\n| `fallthrough` | Let client errors fall-through as unhandled requests, otherwise forward a client error.See [fallthrough](https://expressjs.com/en/5x/api.html#fallthrough) below.\n\n | Boolean | `true` |\n| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | Boolean | `false` |\n| `index` | Sends the specified directory index file. Set to `false` to disable directory indexing. | Mixed | “index.html” |\n| `lastModified` | Set the `Last-Modified` header to the last modified date of the file on the OS. | Boolean | `true` |\n| `maxAge` | Set the max-age property of the Cache-Control header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms). | Number | 0 |\n| `redirect` | Redirect to trailing “/” when the pathname is a directory. | Boolean | `true` |\n| `setHeaders` | Function for setting HTTP headers to serve with the file.See [setHeaders](https://expressjs.com/en/5x/api.html#setHeaders) below.\n\n | Function |   |\n\nFor more information, see [Serving static files in Express](https://expressjs.com/starter/static-files.html). and [Using middleware - Built-in middleware](https://expressjs.com/en/guide/using-middleware.html#middleware.built-in).\n\n##### dotfiles\n\nPossible values for this option are:\n\n* “allow” - No special treatment for dotfiles.\n* “deny” - Deny a request for a dotfile, respond with `403`, then call `next()`.\n* “ignore” - Act as if the dotfile does not exist, respond with `404`, then call `next()`.\n\n##### fallthrough\n\nWhen this option is `true`, client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call `next()` to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke `next(err)`.\n\nSet this option to `true` so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.\n\nUse `false` if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.\n\nFor this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.\n\nThe signature of the function is:\n\n```\nfn(res, path, stat)\n```\n\nArguments:\n\n* `res`, the [response object](https://expressjs.com/en/5x/api.html#res).\n* `path`, the file path that is being sent.\n* `stat`, the `stat` object of the file that is being sent.\n\n#### Example of express.static\n\nHere is an example of using the `express.static` middleware function with an elaborate options object:\n\n```\nconst options = {\n dotfiles: 'ignore',\n etag: false,\n extensions: ['htm', 'html'],\n index: false,\n maxAge: '1d',\n redirect: false,\n setHeaders (res, path, stat) {\n res.set('x-timestamp', Date.now())\n }\n}\n\napp.use(express.static('public', options))\n```\n\n### express.Router(\\[options\\])\n\nCreates a new [router](https://expressjs.com/en/5x/api.html#router) object.\n\n```\nconst router = express.Router([options])\n```\n\nThe optional `options` parameter specifies the behavior of the router.\n\nYou can add middleware and HTTP method routes (such as `get`, `put`, `post`, and so on) to `router` just like an application.\n\nFor more information, see [Router](https://expressjs.com/en/5x/api.html#router).\n\n### express.urlencoded(\\[options\\])\n\nThis is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on [body-parser](https://expressjs.com/resources/middleware/body-parser.html).\n\nReturns middleware that only parses urlencoded bodies and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings.\n\nA new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or an empty object (`{}`) if there was no body to parse, the `Content-Type` was not matched, or an error occurred. This object will contain key-value pairs, where the value can be a string or array (when `extended` is `false`), or any type (when `extended` is `true`).\n\nAs `req.body`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input.\n\nThe following table describes the properties of the optional `options` object.\n\n| Property | Description | Type | Default |\n| --- | --- | --- | --- |\n| `extended` | This option allows to choose between parsing the URL-encoded data with the `querystring` library (when `false`) or the `qs` library (when `true`). The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please [see the qs library](https://www.npmjs.org/package/qs#readme). | Boolean | `false` |\n| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` |\n| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `\"100kb\"` |\n| `parameterLimit` | This option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, an error will be raised. | Number | `1000` |\n| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `urlencoded`), a mime type (like `application/x-www-form-urlencoded`), or a mime type with a wildcard (like `*/x-www-form-urlencoded`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `\"application/x-www-form-urlencoded\"` |\n| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` |\n\nApplication\n-----------\n\nThe `app` object conventionally denotes the Express application. Create it by calling the top-level `express()` function exported by the Express module:\n\n```\nconst express = require('express')\nconst app = express()\n\napp.get('/', (req, res) => {\n res.send('hello world')\n})\n\napp.listen(3000)\n```\n\nThe `app` object has methods for\n\n* Routing HTTP requests; see for example, [app.METHOD](https://expressjs.com/en/5x/api.html#app.METHOD) and [app.param](https://expressjs.com/en/5x/api.html#app.param).\n* Configuring middleware; see [app.route](https://expressjs.com/en/5x/api.html#app.route).\n* Rendering HTML views; see [app.render](https://expressjs.com/en/5x/api.html#app.render).\n* Registering a template engine; see [app.engine](https://expressjs.com/en/5x/api.html#app.engine).\n\nIt also has settings (properties) that affect how the application behaves; for more information, see [Application settings](https://expressjs.com/en/5x/api.html#app.settings.table).\n\nThe Express application object can be referred from the [request object](https://expressjs.com/en/5x/api.html#req) and the [response object](https://expressjs.com/en/5x/api.html#res) as `req.app`, and `res.app`, respectively.\n\n### Properties\n\n### app.locals\n\nThe `app.locals` object has properties that are local variables within the application, and will be available in templates rendered with [res.render](https://expressjs.com/en/5x/api.html#res.render).\n\n```\nconsole.dir(app.locals.title)\n// => 'My App'\n\nconsole.dir(app.locals.email)\n// => 'me@myapp.com'\n```\n\nOnce set, the value of `app.locals` properties persist throughout the life of the application, in contrast with [res.locals](https://expressjs.com/en/5x/api.html#res.locals) properties that are valid only for the lifetime of the request.\n\nYou can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via `req.app.locals` (see [req.app](https://expressjs.com/en/5x/api.html#req.app))\n\n```\napp.locals.title = 'My App'\napp.locals.strftime = require('strftime')\napp.locals.email = 'me@myapp.com'\n```\n\n### app.mountpath\n\nThe `app.mountpath` property contains one or more path patterns on which a sub-app was mounted.\n\nA sub-app is an instance of `express` that may be used for handling the request to a route.\n\n```\nconst express = require('express')\n\nconst app = express() // the main app\nconst admin = express() // the sub app\n\nadmin.get('/', (req, res) => {\n console.log(admin.mountpath) // /admin\n res.send('Admin Homepage')\n})\n\napp.use('/admin', admin) // mount the sub app\n```\n\nIt is similar to the [baseUrl](https://expressjs.com/en/5x/api.html#req.baseUrl) property of the `req` object, except `req.baseUrl` returns the matched URL path, instead of the matched patterns.\n\nIf a sub-app is mounted on multiple path patterns, `app.mountpath` returns the list of patterns it is mounted on, as shown in the following example.\n\n```\nconst admin = express()\n\nadmin.get('/', (req, res) => {\n console.log(admin.mountpath) // [ '/adm*n', '/manager' ]\n res.send('Admin Homepage')\n})\n\nconst secret = express()\nsecret.get('/', (req, res) => {\n console.log(secret.mountpath) // /secr*t\n res.send('Admin Secret')\n})\n\nadmin.use('/secr*t', secret) // load the 'secret' router on '/secr*t', on the 'admin' sub app\napp.use(['/adm*n', '/manager'], admin) // load the 'admin' router on '/adm*n' and '/manager', on the parent app\n```\n\n### app.router\n\nThe application’s in-built instance of router. This is created lazily, on first access.\n\n```\nconst express = require('express')\nconst app = express()\nconst router = app.router\n\nrouter.get('/', (req, res) => {\n res.send('hello world')\n})\n\napp.listen(3000)\n```\n\nYou can add middleware and HTTP method routes to the `router` just like an application.\n\nFor more information, see [Router](https://expressjs.com/en/5x/api.html#router).\n\n### Events\n\n### app.on('mount', callback(parent))\n\nThe `mount` event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.\n\n**NOTE**\n\nSub-apps will:\n\n* Not inherit the value of settings that have a default value. You must set the value in the sub-app.\n* Inherit the value of settings with no default value.\n\nFor details, see [Application settings](https://expressjs.com/en/5x/api.html#app.settings.table).\n\n```\nconst admin = express()\n\nadmin.on('mount', (parent) => {\n console.log('Admin Mounted')\n console.log(parent) // refers to the parent app\n})\n\nadmin.get('/', (req, res) => {\n res.send('Admin Homepage')\n})\n\napp.use('/admin', admin)\n```\n\n### Methods\n\n### app.all(path, callback \\[, callback ...\\])\n\nThis method is like the standard [app.METHOD()](https://expressjs.com/en/5x/api.html#app.METHOD) methods, except it matches all HTTP verbs.\n\n#### Arguments\n\n| Argument | Description | Default |\n| --- | --- | --- |\n| `path` | The path for which the middleware function is invoked; can be any of:\n* A string representing a path.\n* A path pattern.\n* A regular expression pattern to match paths.\n* An array of combinations of any of the above.\n\nFor examples, see [Path examples](https://expressjs.com/en/5x/api.html#path-examples). | '/' (root path) |\n| `callback` | Callback functions; can be:\n\n* A middleware function.\n* A series of middleware functions (separated by commas).\n* An array of middleware functions.\n* A combination of all of the above.\n\nYou can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.\n\nWhen a callback function throws an error or returns a rejected promise, \\`next(err)\\` will be invoked automatically.\n\nSince [router](https://expressjs.com/en/5x/api.html#router) and [app](https://expressjs.com/en/5x/api.html#application) implement the middleware interface, you can use them as you would any other middleware function.\n\nFor examples, see [Middleware callback function examples](https://expressjs.com/en/5x/api.html#middleware-callback-function-examples).\n\n | None |\n\n#### Examples\n\nThe following callback is executed for requests to `/secret` whether using GET, POST, PUT, DELETE, or any other HTTP request method:\n\n```\napp.all('/secret', (req, res, next) => {\n console.log('Accessing the secret section ...')\n next() // pass control to the next handler\n})\n```\n\nThe `app.all()` method is useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, it requires that all routes from that point on require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end-points: `loadUser` can perform a task, then call `next()` to continue matching subsequent routes.\n\n```\napp.all('*', requireAuthentication, loadUser)\n```\n\nOr the equivalent:\n\n```\napp.all('*', requireAuthentication)\napp.all('*', loadUser)\n```\n\nAnother example is white-listed “global” functionality. The example is similar to the ones above, but it only restricts paths that start with “/api”:\n\n```\napp.all('/api/*', requireAuthentication)\n```\n\n### app.delete(path, callback \\[, callback ...\\])\n\nRoutes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the [routing guide](https://expressjs.com/en/guide/routing.html).\n\n#### Arguments\n\n| Argument | Description | Default |\n| --- | --- | --- |\n| `path` | The path for which the middleware function is invoked; can be any of:\n* A string representing a path.\n* A path pattern.\n* A regular expression pattern to match paths.\n* An array of combinations of any of the above.\n\nFor examples, see [Path examples](https://expressjs.com/en/5x/api.html#path-examples). | '/' (root path) |\n| `callback` | Callback functions; can be:\n\n* A middleware function.\n* A series of middleware functions (separated by commas).\n* An array of middleware functions.\n* A combination of all of the above.\n\nYou can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.\n\nWhen a callback function throws an error or returns a rejected promise, \\`next(err)\\` will be invoked automatically.\n\nSince [router](https://expressjs.com/en/5x/api.html#router) and [app](https://expressjs.com/en/5x/api.html#application) implement the middleware interface, you can use them as you would any other middleware function.\n\nFor examples, see [Middleware callback function examples](https://expressjs.com/en/5x/api.html#middleware-callback-function-examples).\n\n | None |\n\n#### Example\n\n```\napp.delete('/', (req, res) => {\n res.send('DELETE request to homepage')\n})\n```\n\n### app.disable(name)\n\nSets the Boolean setting `name` to `false`, where `name` is one of the properties from the [app settings table](https://expressjs.com/en/5x/api.html#app.settings.table). Calling `app.set('foo', false)` for a Boolean property is the same as calling `app.disable('foo')`.\n\nFor example:\n\n```\napp.disable('trust proxy')\napp.get('trust proxy')\n// => false\n```\n\n### app.disabled(name)\n\nReturns `true` if the Boolean setting `name` is disabled (`false`), where `name` is one of the properties from the [app settings table](https://expressjs.com/en/5x/api.html#app.settings.table).\n\n```\napp.disabled('trust proxy')\n// => true\n\napp.enable('trust proxy')\napp.disabled('trust proxy')\n// => false\n```\n\n### app.enable(name)\n\nSets the Boolean setting `name` to `true`, where `name` is one of the properties from the [app settings table](https://expressjs.com/en/5x/api.html#app.settings.table). Calling `app.set('foo', true)` for a Boolean property is the same as calling `app.enable('foo')`.\n\n```\napp.enable('trust proxy')\napp.get('trust proxy')\n// => true\n```\n\n### app.enabled(name)\n\nReturns `true` if the setting `name` is enabled (`true`), where `name` is one of the properties from the [app settings table](https://expressjs.com/en/5x/api.html#app.settings.table).\n\n```\napp.enabled('trust proxy')\n// => false\n\napp.enable('trust proxy')\napp.enabled('trust proxy')\n// => true\n```\n\n### app.engine(ext, callback)\n\nRegisters the given template engine `callback` as `ext`.\n\nBy default, Express will `require()` the engine based on the file extension. For example, if you try to render a “foo.pug” file, Express invokes the following internally, and caches the `require()` on subsequent calls to increase performance.\n\n```\napp.engine('pug', require('pug').__express)\n```\n\nUse this method for engines that do not provide `.__express` out of the box, or if you wish to “map” a different extension to the template engine.\n\nFor example, to map the EJS template engine to “.html” files:\n\n```\napp.engine('html', require('ejs').renderFile)\n```\n\nIn this case, EJS provides a `.renderFile()` method with the same signature that Express expects: `(path, options, callback)`, though note that it aliases this method as `ejs.__express` internally so if you’re using “.ejs” extensions you don’t need to do anything.\n\nSome template engines do not follow this convention. The [consolidate.js](https://github.com/tj/consolidate.js) library maps Node template engines to follow this convention, so they work seamlessly with Express.\n\n```\nconst engines = require('consolidate')\napp.engine('haml', engines.haml)\napp.engine('html', engines.hogan)\n```\n\n### app.get(name)\n\nReturns the value of `name` app setting, where `name` is one of the strings in the [app settings table](https://expressjs.com/en/5x/api.html#app.settings.table). For example:\n\n```\napp.get('title')\n// => undefined\n\napp.set('title', 'My Site')\napp.get('title')\n// => \"My Site\"\n```\n\n### app.get(path, callback \\[, callback ...\\])\n\nRoutes HTTP GET requests to the specified path with the specified callback functions.\n\n#### Arguments\n\n| Argument | Description | Default |\n| --- | --- | --- |\n| `path` | The path for which the middleware function is invoked; can be any of:\n* A string representing a path.\n* A path pattern.\n* A regular expression pattern to match paths.\n* An array of combinations of any of the above.\n\nFor examples, see [Path examples](https://expressjs.com/en/5x/api.html#path-examples). | '/' (root path) |\n| `callback` | Callback functions; can be:\n\n* A middleware function.\n* A series of middleware functions (separated by commas).\n* An array of middleware functions.\n* A combination of all of the above.\n\nYou can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.\n\nWhen a callback function throws an error or returns a rejected promise, \\`next(err)\\` will be invoked automatically.\n\nSince [router](https://expressjs.com/en/5x/api.html#router) and [app](https://expressjs.com/en/5x/api.html#application) implement the middleware interface, you can use them as you would any other middleware function.\n\nFor examples, see [Middleware callback function examples](https://expressjs.com/en/5x/api.html#middleware-callback-function-examples).\n\n | None |\n\nFor more information, see the [routing guide](https://expressjs.com/en/guide/routing.html).\n\n#### Example\n\n```\napp.get('/', (req, res) => {\n res.send('GET request to homepage')\n})\n```\n\n### app.listen(path, \\[callback\\])\n\nStarts a UNIX socket and listens for connections on the given path. This method is identical to Node’s [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen).\n\n```\nconst express = require('express')\nconst app = express()\napp.listen('/tmp/sock')\n```\n\n### app.listen(\\[port\\[, host\\[, backlog\\]\\]\\]\\[, callback\\])\n\nBinds and listens for connections on the specified host and port. This method is identical to Node’s [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen).\n\nIf port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).\n\n```\nconst express = require('express')\nconst app = express()\napp.listen(3000)\n```\n\nThe `app` returned by `express()` is in fact a JavaScript `Function`, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):\n\n```\nconst express = require('express')\nconst https = require('https')\nconst http = require('http')\nconst app = express()\n\nhttp.createServer(app).listen(80)\nhttps.createServer(options, app).listen(443)\n```\n\nThe `app.listen()` method returns an [http.Server](https://nodejs.org/api/http.html#http_class_http_server) object and (for HTTP) is a convenience method for the following:\n\n```\napp.listen = function () {\n const server = http.createServer(this)\n return server.listen.apply(server, arguments)\n}\n```\n\nNOTE: All the forms of Node’s [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen) method are in fact actually supported.\n\n### app.METHOD(path, callback \\[, callback ...\\])\n\nRoutes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are `app.get()`, `app.post()`, `app.put()`, and so on. See [Routing methods](https://expressjs.com/en/5x/api.html#routing-methods) below for the complete list.\n\n#### Arguments\n\n| Argument | Description | Default |\n| --- | --- | --- |\n| `path` | The path for which the middleware function is invoked; can be any of:\n* A string representing a path.\n* A path pattern.\n* A regular expression pattern to match paths.\n* An array of combinations of any of the above.\n\nFor examples, see [Path examples](https://expressjs.com/en/5x/api.html#path-examples). | '/' (root path) |\n| `callback` | Callback functions; can be:\n\n* A middleware function.\n* A series of middleware functions (separated by commas).\n* An array of middleware functions.\n* A combination of all of the above.\n\nYou can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.\n\nWhen a callback function throws an error or returns a rejected promise, \\`next(err)\\` will be invoked automatically.\n\nSince [router](https://expressjs.com/en/5x/api.html#router) and [app](https://expressjs.com/en/5x/api.html#application) implement the middleware interface, you can use them as you would any other middleware function.\n\nFor examples, see [Middleware callback function examples](https://expressjs.com/en/5x/api.html#middleware-callback-function-examples).\n\n | None |\n\n#### Routing methods\n\nExpress supports the following routing methods corresponding to the HTTP methods of the same names:\n\n<table><tbody><tr><td><ul><li><code>checkout</code></li><li><code>copy</code></li><li><code>delete</code></li><li><code>get</code></li><li><code>head</code></li><li><code>lock</code></li><li><code>merge</code></li><li><code>mkactivity</code></li></ul></td><td><ul><li><code>mkcol</code></li><li><code>move</code></li><li><code>m-search</code></li><li><code>notify</code></li><li><code>options</code></li><li><code>patch</code></li><li><code>post</code></li></ul></td><td><ul><li><code>purge</code></li><li><code>put</code></li><li><code>report</code></li><li><code>search</code></li><li><code>subscribe</code></li><li><code>trace</code></li><li><code>unlock</code></li><li><code>unsubscribe</code></li></ul></td></tr></tbody></table>\n\nThe API documentation has explicit entries only for the most popular HTTP methods `app.get()`, `app.post()`, `app.put()`, and `app.delete()`. However, the other methods listed above work in exactly the same way.\n\nTo route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, `app['m-search']('/', function ...`.\n\nThe `app.get()` function is automatically called for the HTTP `HEAD` method in addition to the `GET` method if `app.head()` was not called for the path before `app.get()`.\n\nThe method, `app.all()`, is not derived from any HTTP method and loads middleware at the specified path for _all_ HTTP request methods. For more information, see [app.all](https://expressjs.com/en/5x/api.html#app.all).\n\nFor more information on routing, see the [routing guide](https://expressjs.com/en/guide/routing.html).\n\n### app.param(name, callback)\n\nAdd callback triggers to [route parameters](https://expressjs.com/en/guide/routing.html#route-parameters), where `name` is the name of the parameter or an array of them, and `callback` is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order.\n\nIf `name` is an array, the `callback` trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to `next` inside the callback will call the callback for the next declared parameter. For the last parameter, a call to `next` will call the next middleware in place for the route currently being processed, just like it would if `name` were just a string.\n\nFor example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input.\n\n```\napp.param('user', (req, res, next, id) => {\n // try to get the user details from the User model and attach it to the request object\n User.find(id, (err, user) => {\n if (err) {\n next(err)\n } else if (user) {\n req.user = user\n next()\n } else {\n next(new Error('failed to load user'))\n }\n })\n})\n```\n\nParam callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on `app` will be triggered only by route parameters defined on `app` routes.\n\nAll param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.\n\n```\napp.param('id', (req, res, next, id) => {\n console.log('CALLED ONLY ONCE')\n next()\n})\n\napp.get('/user/:id', (req, res, next) => {\n console.log('although this matches')\n next()\n})\n\napp.get('/user/:id', (req, res) => {\n console.log('and this matches too')\n res.end()\n})\n```\n\nOn `GET /user/42`, the following is printed:\n\n```\nCALLED ONLY ONCE\nalthough this matches\nand this matches too\n```\n\n```\napp.param(['id', 'page'], (req, res, next, value) => {\n console.log('CALLED ONLY ONCE with', value)\n next()\n})\n\napp.get('/user/:id/:page', (req, res, next) => {\n console.log('although this matches')\n next()\n})\n\napp.get('/user/:id/:page', (req, res) => {\n console.log('and this matches too')\n res.end()\n})\n```\n\nOn `GET /user/42/3`, the following is printed:\n\n```\nCALLED ONLY ONCE with 42\nCALLED ONLY ONCE with 3\nalthough this matches\nand this matches too\n```\n\n### app.path()\n\nReturns the canonical path of the app, a string.\n\n```\nconst app = express()\nconst blog = express()\nconst blogAdmin = express()\n\napp.use('/blog', blog)\nblog.use('/admin', blogAdmin)\n\nconsole.log(app.path()) // ''\nconsole.log(blog.path()) // '/blog'\nconsole.log(blogAdmin.path()) // '/blog/admin'\n```\n\nThe behavior of this method can become very complicated in complex cases of mounted apps: it is usually better to use [req.baseUrl](https://expressjs.com/en/5x/api.html#req.baseUrl) to get the canonical path of the app.\n\n### app.post(path, callback \\[, callback ...\\])\n\nRoutes HTTP POST requests to the specified path with the specified callback functions. For more information, see the [routing guide](https://expressjs.com/en/guide/routing.html).\n\n#### Arguments\n\n| Argument | Description | Default |\n| --- | --- | --- |\n| `path` | The path for which the middleware function is invoked; can be any of:\n* A string representing a path.\n* A path pattern.\n* A regular expression pattern to match paths.\n* An array of combinations of any of the above.\n\nFor examples, see [Path examples](https://expressjs.com/en/5x/api.html#path-examples). | '/' (root path) |\n| `callback` | Callback functions; can be:\n\n* A middleware function.\n* A series of middleware functions (separated by commas).\n* An array of middleware functions.\n* A combination of all of the above.\n\nYou can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.\n\nWhen a callback function throws an error or returns a rejected promise, \\`next(err)\\` will be invoked automatically.\n\nSince [router](https://expressjs.com/en/5x/api.html#router) and [app](https://expressjs.com/en/5x/api.html#application) implement the middleware interface, you can use them as you would any other middleware function.\n\nFor examples, see [Middleware callback function examples](https://expressjs.com/en/5x/api.html#middleware-callback-function-examples).\n\n | None |\n\n#### Example\n\n```\napp.post('/', (req, res) => {\n res.send('POST request to homepage')\n})\n```\n\n### app.put(path, callback \\[, callback ...\\])\n\nRoutes HTTP PUT requests to the specified path with the specified callback functions.\n\n#### Arguments\n\n| Argument | Description | Default |\n| --- | --- | --- |\n| `path` | The path for which the middleware function is invoked; can be any of:\n* A string representing a path.\n* A path pattern.\n* A regular expression pattern to match paths.\n* An array of combinations of any of the above.\n\nFor examples, see [Path examples](https://expressjs.com/en/5x/api.html#path-examples). | '/' (root path) |\n| `callback` | Callback functions; can be:\n\n* A middleware function.\n* A series of middleware functions (separated by commas).\n* An array of middleware functions.\n* A combination of all of the above.\n\nYou can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.\n\nWhen a callback function throws an error or returns a rejected promise, \\`next(err)\\` will be invoked automatically.\n\nSince [router](https://expressjs.com/en/5x/api.html#router) and [app](https://expressjs.com/en/5x/api.html#application) implement the middleware interface, you can use them as you would any other middleware function.\n\nFor examples, see [Middleware callback function examples](https://expressjs.com/en/5x/api.html#middleware-callback-function-examples).\n\n | None |\n\n#### Example\n\n```\napp.put('/', (req, res) => {\n res.send('PUT request to homepage')\n})\n```\n\n### app.render(view, \\[locals\\], callback)\n\nReturns the rendered HTML of a view via the `callback` function. It accepts an optional parameter that is an object containing local variables for the view. It is like [res.render()](https://expressjs.com/en/5x/api.html#res.render), except it cannot send the rendered view to the client on its own.\n\nThink of `app.render()` as a utility function for generating rendered view strings. Internally `res.render()` uses `app.render()` to render views.\n\nThe local variable `cache` is reserved for enabling view cache. Set it to `true`, if you want to cache view during development; view caching is enabled in production by default.\n\n```\napp.render('email', (err, html) => {\n // ...\n})\n\napp.render('email', { name: 'Tobi' }, (err, html) => {\n // ...\n})\n```\n\n### app.route(path)\n\nReturns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use `app.route()` to avoid duplicate route names (and thus typo errors).\n\n```\nconst app = express()\n\napp.route('/events')\n .all((req, res, next) => {\n // runs for all HTTP verbs first\n // think of it as route specific middleware!\n })\n .get((req, res, next) => {\n res.json({})\n })\n .post((req, res, next) => {\n // maybe add a new event...\n })\n```\n\n### app.set(name, value)\n\nAssigns setting `name` to `value`. You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the [app settings table](https://expressjs.com/en/5x/api.html#app.settings.table).\n\nCalling `app.set('foo', true)` for a Boolean property is the same as calling `app.enable('foo')`. Similarly, calling `app.set('foo', false)` for a Boolean property is the same as calling `app.disable('foo')`.\n\nRetrieve the value of a setting with [`app.get()`](https://expressjs.com/en/5x/api.html#app.get).\n\n```\napp.set('title', 'My Site')\napp.get('title') // \"My Site\"\n```\n\n#### Application Settings\n\nThe following table lists application settings.\n\nNote that sub-apps will:\n\n* Not inherit the value of settings that have a default value. You must set the value in the sub-app.\n* Inherit the value of settings with no default value; these are explicitly noted in the table below.\n\nExceptions: Sub-apps will inherit the value of `trust proxy` even though it has a default value (for backward-compatibility); Sub-apps will not inherit the value of `view cache` in production (when `NODE_ENV` is “production”).\n\n### app.use(\\[path,\\] callback \\[, callback...\\])\n\nMounts the specified [middleware](https://expressjs.com/en/guide/using-middleware.html) function or functions at the specified path: the middleware function is executed when the base of the requested path matches `path`.\n\n#### Arguments\n\n| Argument | Description | Default |\n| --- | --- | --- |\n| `path` | The path for which the middleware function is invoked; can be any of:\n* A string representing a path.\n* A path pattern.\n* A regular expression pattern to match paths.\n* An array of combinations of any of the above.\n\nFor examples, see [Path examples](https://expressjs.com/en/5x/api.html#path-examples). | '/' (root path) |\n| `callback` | Callback functions; can be:\n\n* A middleware function.\n* A series of middleware functions (separated by commas).\n* An array of middleware functions.\n* A combination of all of the above.\n\nYou can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.\n\nWhen a callback function throws an error or returns a rejected promise, \\`next(err)\\` will be invoked automatically.\n\nSince [router](https://expressjs.com/en/5x/api.html#router) and [app](https://expressjs.com/en/5x/api.html#application) implement the middleware interface, you can use them as you would any other middleware function.\n\nFor examples, see [Middleware callback function examples](https://expressjs.com/en/5x/api.html#middleware-callback-function-examples).\n\n | None |\n\n#### Description\n\nA route will match any path that follows its path immediately with a “`/`”. For example: `app.use('/apple', ...)` will match “/apple”, “/apple/images”, “/apple/images/news”, and so on.\n\nSince `path` defaults to “/”, middleware mounted without a path will be executed for every request to the app. \nFor example, this middleware function will be executed for _every_ request to the app:\n\n```\napp.use((req, res, next) => {\n console.log('Time: %d', Date.now())\n next()\n})\n```\n\n**NOTE**\n\nSub-apps will:\n\n* Not inherit the value of settings that have a default value. You must set the value in the sub-app.\n* Inherit the value of settings with no default value.\n\nFor details, see [Application settings](https://expressjs.com/en/5x/api.html#app.settings.table).\n\nMiddleware functions are executed sequentially, therefore the order of middleware inclusion is important.\n\n```\n// this middleware will not allow the request to go beyond it\napp.use((req, res, next) => {\n res.send('Hello World')\n})\n\n// requests will never reach this route\napp.get('/', (req, res) => {\n res.send('Welcome')\n})\n```\n\n**Error-handling middleware**\n\nError-handling middleware always takes _four_ arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: [Error handling](https://expressjs.com/en/guide/error-handling.html).\n\nDefine error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`):\n\n```\napp.use((err, req, res, next) => {\n console.error(err.stack)\n res.status(500).send('Something broke!')\n})\n```\n\n#### Path examples\n\nThe following table provides some simple examples of valid `path` values for mounting middleware.\n\n#### Middleware callback function examples\n\nThe following table provides some simple examples of middleware functions that can be used as the `callback` argument to `app.use()`, `app.METHOD()`, and `app.all()`. Even though the examples are for `app.use()`, they are also valid for `app.use()`, `app.METHOD()`, and `app.all()`.\n\n| Usage | Example |\n| --- | --- |\n| Single Middleware | You can define and mount a middleware function locally.\n```\napp.use((req, res, next) => {\n next()\n})\n```\n\nA router is valid middleware.\n\n```\nconst router = express.Router()\nrouter.get('/', (req, res, next) => {\n next()\n})\napp.use(router)\n```\n\nAn Express app is valid middleware.\n\n```\nconst subApp = express()\nsubApp.get('/', (req, res, next) => {\n next()\n})\napp.use(subApp)\n```\n\n |\n| Series of Middleware | You can specify more than one middleware function at the same mount path.\n\n```\nconst r1 = express.Router()\nr1.get('/', (req, res, next) => {\n next()\n})\n\nconst r2 = express.Router()\nr2.get('/', (req, res, next) => {\n next()\n})\n\napp.use(r1, r2)\n```\n\n |\n| Array | Use an array to group middleware logically.\n\n```\nconst r1 = express.Router()\nr1.get('/', (req, res, next) => {\n next()\n})\n\nconst r2 = express.Router()\nr2.get('/', (req, res, next) => {\n next()\n})\n\napp.use([r1, r2])\n```\n\n |\n| Combination | You can combine all the above ways of mounting middleware.\n\n```\nfunction mw1 (req, res, next) { next() }\nfunction mw2 (req, res, next) { next() }\n\nconst r1 = express.Router()\nr1.get('/', (req, res, next) => { next() })\n\nconst r2 = express.Router()\nr2.get('/', (req, res, next) => { next() })\n\nconst subApp = express()\nsubApp.get('/', (req, res, next) => { next() })\n\napp.use(mw1, [mw2, r1, r2], subApp)\n```\n\n |\n\nFollowing are some examples of using the [express.static](https://expressjs.com/en/guide/using-middleware.html#middleware.built-in) middleware in an Express app.\n\nServe static content for the app from the “public” directory in the application directory:\n\n```\n// GET /style.css etc\napp.use(express.static(path.join(__dirname, 'public')))\n```\n\nMount the middleware at “/static” to serve static content only when their request path is prefixed with “/static”:\n\n```\n// GET /static/style.css etc.\napp.use('/static', express.static(path.join(__dirname, 'public')))\n```\n\nDisable logging for static content requests by loading the logger middleware after the static middleware:\n\n```\napp.use(express.static(path.join(__dirname, 'public')))\napp.use(logger())\n```\n\nServe static files from multiple directories, but give precedence to “./public” over the others:\n\n```\napp.use(express.static(path.join(__dirname, 'public')))\napp.use(express.static(path.join(__dirname, 'files')))\napp.use(express.static(path.join(__dirname, 'uploads')))\n```\n\nRequest\n-------\n\nThe `req` object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as `req` (and the HTTP response is `res`) but its actual name is determined by the parameters to the callback function in which you’re working.\n\nFor example:\n\n```\napp.get('/user/:id', (req, res) => {\n res.send(`user ${req.params.id}`)\n})\n```\n\nBut you could just as well have:\n\n```\napp.get('/user/:id', (request, response) => {\n response.send(`user ${request.params.id}`)\n})\n```\n\nThe `req` object is an enhanced version of Node’s own request object and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_incomingmessage).\n\n### Properties\n\nIn Express 4, `req.files` is no longer available on the `req` object by default. To access uploaded files on the `req.files` object, use multipart-handling middleware like [busboy](https://www.npmjs.com/package/busboy), [multer](https://www.npmjs.com/package/multer), [formidable](https://www.npmjs.com/package/formidable), [multiparty](https://www.npmjs.com/package/multiparty), [connect-multiparty](https://www.npmjs.com/package/connect-multiparty), or [pez](https://www.npmjs.com/package/pez).\n\n### req.app\n\nThis property holds a reference to the instance of the Express application that is using the middleware.\n\nIf you follow the pattern in which you create a module that just exports a middleware function and `require()` it in your main file, then the middleware can access the Express instance via `req.app`\n\nFor example:\n\n```\n// index.js\napp.get('/viewdirectory', require('./mymiddleware.js'))\n```\n\n```\n// mymiddleware.js\nmodule.exports = (req, res) => {\n res.send(`The views directory is ${req.app.get('views')}`)\n}\n```\n\n### req.baseUrl\n\nThe URL path on which a router instance was mounted.\n\nThe `req.baseUrl` property is similar to the [mountpath](https://expressjs.com/en/5x/api.html#app.mountpath) property of the `app` object, except `app.mountpath` returns the matched path pattern(s).\n\nFor example:\n\n```\nconst greet = express.Router()\n\ngreet.get('/jp', (req, res) => {\n console.log(req.baseUrl) // /greet\n res.send('Konichiwa!')\n})\n\napp.use('/greet', greet) // load the router on '/greet'\n```\n\nEven if you use a path pattern or a set of path patterns to load the router, the `baseUrl` property returns the matched string, not the pattern(s). In the following example, the `greet` router is loaded on two path patterns.\n\n```\napp.use(['/gre+t', '/hel{2}o'], greet) // load the router on '/gre+t' and '/hel{2}o'\n```\n\nWhen a request is made to `/greet/jp`, `req.baseUrl` is “/greet”. When a request is made to `/hello/jp`, `req.baseUrl` is “/hello”.\n\n### req.body\n\nContains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use body-parsing middleware such as [body-parser](https://www.npmjs.org/package/body-parser) and [multer](https://www.npmjs.org/package/multer).\n\nAs `req.body`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input.\n\nThe following example shows how to use body-parsing middleware to populate `req.body`.\n\n```\nconst app = require('express')()\nconst bodyParser = require('body-parser')\nconst multer = require('multer') // v1.0.5\nconst upload = multer() // for parsing multipart/form-data\n\napp.use(bodyParser.json()) // for parsing application/json\napp.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded\n\napp.post('/profile', upload.array(), (req, res, next) => {\n console.log(req.body)\n res.json(req.body)\n})\n```\n\n### req.cookies\n\nWhen using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to `{}`.\n\n```\n// Cookie: name=tj\nconsole.dir(req.cookies.name)\n// => \"tj\"\n```\n\nIf the cookie has been signed, you have to use [req.signedCookies](https://expressjs.com/en/5x/api.html#req.signedCookies).\n\nFor more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser).\n\n### req.fresh\n\nWhen the response is still “fresh” in the client’s cache `true` is returned, otherwise `false` is returned to indicate that the client cache is now stale and the full response should be sent.\n\nWhen a client sends the `Cache-Control: no-cache` request header to indicate an end-to-end reload request, this module will return `false` to make handling these requests transparent.\n\nFurther details for how cache validation works can be found in the [HTTP/1.1 Caching Specification](https://tools.ietf.org/html/rfc7234).\n\n```\nconsole.dir(req.fresh)\n// => true\n```\n\n### req.host\n\nContains the host derived from the `Host` HTTP header.\n\nWhen the [`trust proxy` setting](https://expressjs.com/en/5x/api.html#app.settings.table) does not evaluate to `false`, this property will instead get the value from the `X-Forwarded-Host` header field. This header can be set by the client or by the proxy.\n\nIf there is more than one `X-Forwarded-Host` header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used.\n\n```\n// Host: \"example.com:3000\"\nconsole.dir(req.host)\n// => 'example.com:3000'\n\n// Host: \"[::1]:3000\"\nconsole.dir(req.host)\n// => '[::1]:3000'\n```\n\n### req.hostname\n\nContains the hostname derived from the `Host` HTTP header.\n\nWhen the [`trust proxy` setting](https://expressjs.com/5x/api.html#trust.proxy.options.table) does not evaluate to `false`, this property will instead get the value from the `X-Forwarded-Host` header field. This header can be set by the client or by the proxy.\n\nIf there is more than one `X-Forwarded-Host` header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used.\n\nPrior to Express v4.17.0, the `X-Forwarded-Host` could not contain multiple values or be present more than once.\n\n```\n// Host: \"example.com:3000\"\nconsole.dir(req.hostname)\n// => 'example.com'\n```\n\n### req.ip\n\nContains the remote IP address of the request.\n\nWhen the [`trust proxy` setting](https://expressjs.com/5x/api.html#trust.proxy.options.table) does not evaluate to `false`, the value of this property is derived from the left-most entry in the `X-Forwarded-For` header. This header can be set by the client or by the proxy.\n\n```\nconsole.dir(req.ip)\n// => \"127.0.0.1\"\n```\n\n### req.ips\n\nWhen the [`trust proxy` setting](https://expressjs.com/5x/api.html#trust.proxy.options.table) does not evaluate to `false`, this property contains an array of IP addresses specified in the `X-Forwarded-For` request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy.\n\nFor example, if `X-Forwarded-For` is `client, proxy1, proxy2`, `req.ips` would be `[\"client\", \"proxy1\", \"proxy2\"]`, where `proxy2` is the furthest downstream.\n\n### req.method\n\nContains a string corresponding to the HTTP method of the request: `GET`, `POST`, `PUT`, and so on.\n\n### req.originalUrl\n\n`req.url` is not a native Express property, it is inherited from Node’s [http module](https://nodejs.org/api/http.html#http_message_url).\n\nThis property is much like `req.url`; however, it retains the original request URL, allowing you to rewrite `req.url` freely for internal routing purposes. For example, the “mounting” feature of [app.use()](https://expressjs.com/en/5x/api.html#app.use) will rewrite `req.url` to strip the mount point.\n\n```\n// GET /search?q=something\nconsole.dir(req.originalUrl)\n// => \"/search?q=something\"\n```\n\n`req.originalUrl` is available both in middleware and router objects, and is a combination of `req.baseUrl` and `req.url`. Consider following example:\n\n```\n// GET 'http://www.example.com/admin/new?sort=desc'\napp.use('/admin', (req, res, next) => {\n console.dir(req.originalUrl) // '/admin/new?sort=desc'\n console.dir(req.baseUrl) // '/admin'\n console.dir(req.path) // '/new'\n next()\n})\n```\n\n### req.params\n\nThis property is an object containing properties mapped to the [named route “parameters”](https://expressjs.com/en/guide/routing.html#route-parameters). For example, if you have the route `/user/:name`, then the “name” property is available as `req.params.name`. This object defaults to `{}`.\n\n```\n// GET /user/tj\nconsole.dir(req.params.name)\n// => \"tj\"\n```\n\nWhen you use a regular expression for the route definition, capture groups are provided in the array using `req.params[n]`, where `n` is the nth capture group. This rule is applied to unnamed wild card matches with string routes such as `/file/*`:\n\n```\n// GET /file/javascripts/jquery.js\nconsole.dir(req.params[0])\n// => \"javascripts/jquery.js\"\n```\n\nIf you need to make changes to a key in `req.params`, use the [app.param](https://expressjs.com/en/5x/api.html#app.param) handler. Changes are applicable only to [parameters](https://expressjs.com/en/guide/routing.html#route-parameters) already defined in the route path.\n\nAny changes made to the `req.params` object in a middleware or route handler will be reset.\n\nNOTE: Express automatically decodes the values in `req.params` (using `decodeURIComponent`).\n\n### req.path\n\nContains the path part of the request URL.\n\n```\n// example.com/users?sort=desc\nconsole.dir(req.path)\n// => \"/users\"\n```\n\nWhen called from a middleware, the mount point is not included in `req.path`. See [app.use()](https://expressjs.com/5x/api.html#app.use) for more details.\n\n### req.protocol\n\nContains the request protocol string: either `http` or (for TLS requests) `https`.\n\nWhen the [`trust proxy` setting](https://expressjs.com/en/5x/api.html#trust.proxy.options.table) does not evaluate to `false`, this property will use the value of the `X-Forwarded-Proto` header field if present. This header can be set by the client or by the proxy.\n\n```\nconsole.dir(req.protocol)\n// => \"http\"\n```\n\n### req.query\n\nThis property is an object containing a property for each query string parameter in the route. When [query parser](https://expressjs.com/en/5x/api.html#app.settings.table) is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.\n\nAs `req.query`’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.query.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input.\n\nThe value of this property can be configured with the [query parser application setting](https://expressjs.com/en/5x/api.html#app.settings.table) to work how your application needs it. A very popular query string parser is the [`qs` module](https://www.npmjs.org/package/qs), and this is used by default. The `qs` module is very configurable with many settings, and it may be desirable to use different settings than the default to populate `req.query`:\n\n```\nconst qs = require('qs')\napp.set('query parser',\n (str) => qs.parse(str, { /* custom options */ }))\n```\n\nCheck out the [query parser application setting](https://expressjs.com/en/5x/api.html#app.settings.table) documentation for other customization options.\n\n### req.res\n\nThis property holds a reference to the [response object](https://expressjs.com/en/5x/api.html#res) that relates to this request object.\n\n### req.route\n\nContains the currently-matched route, a string. For example:\n\n```\napp.get('/user/:id?', (req, res) => {\n console.log(req.route)\n res.send('GET')\n})\n```\n\nExample output from the previous snippet:\n\n```\n{ path: '/user/:id?',\n stack:\n [ { handle: [Function: userIdHandler],\n name: 'userIdHandler',\n params: undefined,\n path: undefined,\n keys: [],\n regexp: /^\\/?$/i,\n method: 'get' } ],\n methods: { get: true }\n}\n```\n\n### req.secure\n\nA Boolean property that is true if a TLS connection is established. Equivalent to the following:\n\n```\nreq.protocol === 'https'\n```\n\n### req.signedCookies\n\nWhen using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside in a different object to show developer intent; otherwise, a malicious attack could be placed on `req.cookie` values (which are easy to spoof). Note that signing a cookie does not make it “hidden” or encrypted; but simply prevents tampering (because the secret used to sign is private).\n\nIf no signed cookies are sent, the property defaults to `{}`.\n\n```\n// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3\nconsole.dir(req.signedCookies.user)\n// => \"tobi\"\n```\n\nFor more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser).\n\n### req.stale\n\nIndicates whether the request is “stale,” and is the opposite of `req.fresh`. For more information, see [req.fresh](https://expressjs.com/en/5x/api.html#req.fresh).\n\n```\nconsole.dir(req.stale)\n// => true\n```\n\n### req.subdomains\n\nAn array of subdomains in the domain name of the request.\n\n```\n// Host: \"tobi.ferrets.example.com\"\nconsole.dir(req.subdomains)\n// => [\"ferrets\", \"tobi\"]\n```\n\nThe application property `subdomain offset`, which defaults to 2, is used for determining the beginning of the subdomain segments. To change this behavior, change its value using [app.set](https://expressjs.com/en/5x/api.html#app.set).\n\n### req.xhr\n\nA Boolean property that is `true` if the request’s `X-Requested-With` header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery.\n\n```\nconsole.dir(req.xhr)\n// => true\n```\n\n### Methods\n\n### req.accepts(types)\n\nChecks if the specified content types are acceptable, based on the request’s `Accept` HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns `false` (in which case, the application should respond with `406 \"Not Acceptable\"`).\n\nThe `type` value may be a single MIME type string (such as “application/json”), an extension name such as “json”, a comma-delimited list, or an array. For a list or array, the method returns the _best_ match (if any).\n\n```\n// Accept: text/html\nreq.accepts('html')\n// => \"html\"\n\n// Accept: text/*, application/json\nreq.accepts('html')\n// => \"html\"\nreq.accepts('text/html')\n// => \"text/html\"\nreq.accepts(['json', 'text'])\n// => \"json\"\nreq.accepts('application/json')\n// => \"application/json\"\n\n// Accept: text/*, application/json\nreq.accepts('image/png')\nreq.accepts('png')\n// => false\n\n// Accept: text/*;q=.5, application/json\nreq.accepts(['html', 'json'])\n// => \"json\"\n```\n\nFor more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).\n\n### req.acceptsCharsets(charset \\[, ...\\])\n\nReturns the first accepted charset of the specified character sets, based on the request’s `Accept-Charset` HTTP header field. If none of the specified charsets is accepted, returns `false`.\n\nFor more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).\n\n### req.acceptsEncodings(encoding \\[, ...\\])\n\nReturns the first accepted encoding of the specified encodings, based on the request’s `Accept-Encoding` HTTP header field. If none of the specified encodings is accepted, returns `false`.\n\nFor more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).\n\n### req.acceptsLanguages(lang \\[, ...\\])\n\nReturns the first accepted language of the specified languages, based on the request’s `Accept-Language` HTTP header field. If none of the specified languages is accepted, returns `false`.\n\nFor more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).\n\n### req.get(field)\n\nReturns the specified HTTP request header field (case-insensitive match). The `Referrer` and `Referer` fields are interchangeable.\n\n```\nreq.get('Content-Type')\n// => \"text/plain\"\n\nreq.get('content-type')\n// => \"text/plain\"\n\nreq.get('Something')\n// => undefined\n```\n\nAliased as `req.header(field)`.\n\n### req.is(type)\n\nReturns the matching content type if the incoming request’s “Content-Type” HTTP header field matches the MIME type specified by the `type` parameter. If the request has no body, returns `null`. Returns `false` otherwise.\n\n```\n// With Content-Type: text/html; charset=utf-8\nreq.is('html') // => 'html'\nreq.is('text/html') // => 'text/html'\nreq.is('text/*') // => 'text/*'\n\n// When Content-Type is application/json\nreq.is('json') // => 'json'\nreq.is('application/json') // => 'application/json'\nreq.is('application/*') // => 'application/*'\n\nreq.is('html')\n// => false\n```\n\nFor more information, or if you have issues or concerns, see [type-is](https://github.com/expressjs/type-is).\n\n### req.range(size\\[, options\\])\n\n`Range` header parser.\n\nThe `size` parameter is the maximum size of the resource.\n\nThe `options` parameter is an object that can have the following properties.\n\n| Property | Type | Description |\n| --- | --- | --- |\n| `combine` | Boolean | Specify if overlapping & adjacent ranges should be combined, defaults to `false`. When `true`, ranges will be combined and returned as if they were specified that way in the header. |\n\nAn array of ranges will be returned or negative numbers indicating an error parsing.\n\n* `-2` signals a malformed header string\n* `-1` signals an unsatisfiable range\n\n```\n// parse header from request\nconst range = req.range(1000)\n\n// the type of the range\nif (range.type === 'bytes') {\n // the ranges\n range.forEach((r) => {\n // do something with r.start and r.end\n })\n}\n```\n\nResponse\n--------\n\nThe `res` object represents the HTTP response that an Express app sends when it gets an HTTP request.\n\nIn this documentation and by convention, the object is always referred to as `res` (and the HTTP request is `req`) but its actual name is determined by the parameters to the callback function in which you’re working.\n\nFor example:\n\n```\napp.get('/user/:id', (req, res) => {\n res.send(`user ${req.params.id}`)\n})\n```\n\nBut you could just as well have:\n\n```\napp.get('/user/:id', (request, response) => {\n response.send(`user ${request.params.id}`)\n})\n```\n\nThe `res` object is an enhanced version of Node’s own response object and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_serverresponse).\n\n### Properties\n\n### res.app\n\nThis property holds a reference to the instance of the Express application that is using the middleware.\n\n`res.app` is identical to the [req.app](https://expressjs.com/en/5x/api.html#req.app) property in the request object.\n\nBoolean property that indicates if the app sent HTTP headers for the response.\n\n```\napp.get('/', (req, res) => {\n console.log(res.headersSent) // false\n res.send('OK')\n console.log(res.headersSent) // true\n})\n```\n\n### res.locals\n\nUse this property to set variables accessible in templates rendered with [res.render](https://expressjs.com/en/5x/api.html#res.render). The variables set on `res.locals` are available within a single request-response cycle, and will not be shared between requests.\n\nIn order to keep local variables for use in template rendering between requests, use [app.locals](https://expressjs.com/en/5x/api.html#app.locals) instead.\n\nThis property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application.\n\n```\napp.use((req, res, next) => {\n // Make `user` and `authenticated` available in templates\n res.locals.user = req.user\n res.locals.authenticated = !req.user.anonymous\n next()\n})\n```\n\n### res.req\n\nThis property holds a reference to the [request object](https://expressjs.com/en/5x/api.html#req) that relates to this response object.\n\n### Methods\n\n### res.append(field \\[, value\\])\n\n`res.append()` is supported by Express v4.11.0+\n\nAppends the specified `value` to the HTTP response header `field`. If the header is not already set, it creates the header with the specified value. The `value` parameter can be a string or an array.\n\nNote: calling `res.set()` after `res.append()` will reset the previously-set header value.\n\n```\nres.append('Link', ['<http://localhost/>', '<http://localhost:3000/>'])\nres.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly')\nres.append('Warning', '199 Miscellaneous warning')\n```\n\n### res.attachment(\\[filename\\])\n\nSets the HTTP response `Content-Disposition` header field to “attachment”. If a `filename` is given, then it sets the `Content-Type` based on the extension name via `res.type()`, and sets the `Content-Disposition` “filename=” parameter.\n\n```\nres.attachment()\n// Content-Disposition: attachment\n\nres.attachment('path/to/logo.png')\n// Content-Disposition: attachment; filename=\"logo.png\"\n// Content-Type: image/png\n```\n\n### res.cookie(name, value \\[, options\\])\n\nSets cookie `name` to `value`. The `value` parameter may be a string or object converted to JSON.\n\nThe `options` parameter is an object that can have the following properties.\n\n| Property | Type | Description |\n| --- | --- | --- |\n| `domain` | String | Domain name for the cookie. Defaults to the domain name of the app. |\n| `encode` | Function | A synchronous function used for cookie value encoding. Defaults to `encodeURIComponent`. |\n| `expires` | Date | Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. |\n| `httpOnly` | Boolean | Flags the cookie to be accessible only by the web server. |\n| `maxAge` | Number | Convenient option for setting the expiry time relative to the current time in milliseconds. |\n| `path` | String | Path for the cookie. Defaults to “/”. |\n| `secure` | Boolean | Marks the cookie to be used with HTTPS only. |\n| `signed` | Boolean | Indicates if the cookie should be signed. |\n| `sameSite` | Boolean or String | Value of the “SameSite” **Set-Cookie** attribute. More information at [https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1](https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1). |\n\nAll `res.cookie()` does is set the HTTP `Set-Cookie` header with the options provided. Any option not specified defaults to the value stated in [RFC 6265](http://tools.ietf.org/html/rfc6265).\n\nFor example:\n\n```\nres.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true })\nres.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })\n```\n\nThe `encode` option allows you to choose the function used for cookie value encoding. Does not support asynchronous functions.\n\nExample use case: You need to set a domain-wide cookie for another site in your organization. This other site (not under your administrative control) does not use URI-encoded cookie values.\n\n```\n// Default encoding\nres.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' })\n// Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/'\n\n// Custom encoding\nres.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com', encode: String })\n// Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;'\n```\n\nThe `maxAge` option is a convenience option for setting “expires” relative to the current time in milliseconds. The following is equivalent to the second example above.\n\n```\nres.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })\n```\n\nYou can pass an object as the `value` parameter; it is then serialized as JSON and parsed by `bodyParser()` middleware.\n\n```\nres.cookie('cart', { items: [1, 2, 3] })\nres.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 })\n```\n\nWhen using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this method also supports signed cookies. Simply include the `signed` option set to `true`. Then, `res.cookie()` will use the secret passed to `cookieParser(secret)` to sign the value.\n\n```\nres.cookie('name', 'tobi', { signed: true })\n```\n\nLater, you may access this value through the [req.signedCookies](https://expressjs.com/en/5x/api.html#req.signedCookies) object.\n\n### res.clearCookie(name \\[, options\\])\n\nClears the cookie specified by `name`. For details about the `options` object, see [res.cookie()](https://expressjs.com/en/5x/api.html#res.cookie).\n\nWeb browsers and other compliant clients will only clear the cookie if the given `options` is identical to those given to [res.cookie()](https://expressjs.com/en/5x/api.html#res.cookie), excluding `expires` and `maxAge`.\n\n```\nres.cookie('name', 'tobi', { path: '/admin' })\nres.clearCookie('name', { path: '/admin' })\n```\n\n### res.download(path \\[, filename\\] \\[, options\\] \\[, fn\\])\n\nThe optional `options` argument is supported by Express v4.16.0 onwards.\n\nTransfers the file at `path` as an “attachment”. Typically, browsers will prompt the user for download. By default, the `Content-Disposition` header “filename=” parameter is derived from the `path` argument, but can be overridden with the `filename` parameter. If `path` is relative, then it will be based on the current working directory of the process.\n\nThe following table provides details on the `options` parameter.\n\nThe optional `options` argument is supported by Express v4.16.0 onwards.\n\nThe method invokes the callback function `fn(err)` when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route.\n\n```\nres.download('/report-12345.pdf')\n\nres.download('/report-12345.pdf', 'report.pdf')\n\nres.download('/report-12345.pdf', 'report.pdf', (err) => {\n if (err) {\n // Handle error, but keep in mind the response may be partially-sent\n // so check res.headersSent\n } else {\n // decrement a download credit, etc.\n }\n})\n```\n\n### res.end(\\[data\\] \\[, encoding\\])\n\nEnds the response process. This method actually comes from Node core, specifically the [response.end() method of http.ServerResponse](https://nodejs.org/api/http.html#http_response_end_data_encoding_callback).\n\nUse to quickly end the response without any data. If you need to respond with data, instead use methods such as [res.send()](https://expressjs.com/en/5x/api.html#res.send) and [res.json()](https://expressjs.com/en/5x/api.html#res.json).\n\n```\nres.end()\nres.status(404).end()\n```\n\n### res.format(object)\n\nPerforms content-negotiation on the `Accept` HTTP header on the request object, when present. It uses [req.accepts()](https://expressjs.com/en/5x/api.html#req.accepts) to select a handler for the request, based on the acceptable types ordered by their quality values. If the header is not specified, the first callback is invoked. When no match is found, the server responds with 406 “Not Acceptable”, or invokes the `default` callback.\n\nThe `Content-Type` response header is set when a callback is selected. However, you may alter this within the callback using methods such as `res.set()` or `res.type()`.\n\nThe following example would respond with `{ \"message\": \"hey\" }` when the `Accept` header field is set to “application/json” or “\\*/json” (however, if it is “\\*/\\*”, then the response will be “hey”).\n\n```\nres.format({\n 'text/plain' () {\n res.send('hey')\n },\n\n 'text/html' () {\n res.send('<p>hey</p>')\n },\n\n 'application/json' () {\n res.send({ message: 'hey' })\n },\n\n default () {\n // log the request and respond with 406\n res.status(406).send('Not Acceptable')\n }\n})\n```\n\nIn addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation:\n\n```\nres.format({\n text () {\n res.send('hey')\n },\n\n html () {\n res.send('<p>hey</p>')\n },\n\n json () {\n res.send({ message: 'hey' })\n }\n})\n```\n\n### res.get(field)\n\nReturns the HTTP response header specified by `field`. The match is case-insensitive.\n\n```\nres.get('Content-Type')\n// => \"text/plain\"\n```\n\n### res.json(\\[body\\])\n\nSends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).\n\nThe parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.\n\n```\nres.json(null)\nres.json({ user: 'tobi' })\nres.status(500).json({ error: 'message' })\n```\n\n### res.jsonp(\\[body\\])\n\nSends a JSON response with JSONP support. This method is identical to `res.json()`, except that it opts-in to JSONP callback support.\n\n```\nres.jsonp(null)\n// => callback(null)\n\nres.jsonp({ user: 'tobi' })\n// => callback({ \"user\": \"tobi\" })\n\nres.status(500).jsonp({ error: 'message' })\n// => callback({ \"error\": \"message\" })\n```\n\nBy default, the JSONP callback name is simply `callback`. Override this with the [jsonp callback name](https://expressjs.com/en/5x/api.html#app.settings.table) setting.\n\nThe following are some examples of JSONP responses using the same code:\n\n```\n// ?callback=foo\nres.jsonp({ user: 'tobi' })\n// => foo({ \"user\": \"tobi\" })\n\napp.set('jsonp callback name', 'cb')\n\n// ?cb=foo\nres.status(500).jsonp({ error: 'message' })\n// => foo({ \"error\": \"message\" })\n```\n\n### res.links(links)\n\nJoins the `links` provided as properties of the parameter to populate the response’s `Link` HTTP header field.\n\nFor example, the following call:\n\n```\nres.links({\n next: 'http://api.example.com/users?page=2',\n last: 'http://api.example.com/users?page=5'\n})\n```\n\nYields the following results:\n\n```\nLink: <http://api.example.com/users?page=2>; rel=\"next\",\n <http://api.example.com/users?page=5>; rel=\"last\"\n```\n\n### res.location(path)\n\nSets the response `Location` HTTP header to the specified `path` parameter.\n\n```\nres.location('/foo/bar')\nres.location('http://example.com')\nres.location('back')\n```\n\nA `path` value of “back” has a special meaning, it refers to the URL specified in the `Referer` header of the request. If the `Referer` header was not specified, it refers to “/”.\n\nSee also [Security best practices: Prevent open redirect vulnerabilities](http://expressjs.com/en/advanced/best-practice-security.html#prevent-open-redirects).\n\nAfter encoding the URL, if not encoded already, Express passes the specified URL to the browser in the `Location` header, without any validation.\n\nBrowsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the `Location` header; and redirect the user accordingly.\n\n### res.redirect(\\[status,\\] path)\n\nRedirects to the URL derived from the specified `path`, with specified `status`, a positive integer that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html). If not specified, `status` defaults to `302 \"Found\"`.\n\n```\nres.redirect('/foo/bar')\nres.redirect('http://example.com')\nres.redirect(301, 'http://example.com')\nres.redirect('../login')\n```\n\nRedirects can be a fully-qualified URL for redirecting to a different site:\n\n```\nres.redirect('http://google.com')\n```\n\nRedirects can be relative to the root of the host name. For example, if the application is on `http://example.com/admin/post/new`, the following would redirect to the URL `http://example.com/admin`:\n\n```\nres.redirect('/admin')\n```\n\nRedirects can be relative to the current URL. For example, from `http://example.com/blog/admin/` (notice the trailing slash), the following would redirect to the URL `http://example.com/blog/admin/post/new`.\n\n```\nres.redirect('post/new')\n```\n\nRedirecting to `post/new` from `http://example.com/blog/admin` (no trailing slash), will redirect to `http://example.com/blog/post/new`.\n\nIf you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.\n\nPath-relative redirects are also possible. If you were on `http://example.com/admin/post/new`, the following would redirect to `http://example.com/admin/post`:\n\n```\nres.redirect('..')\n```\n\nA `back` redirection redirects the request back to the [referer](http://en.wikipedia.org/wiki/HTTP_referer), defaulting to `/` when the referer is missing.\n\n```\nres.redirect('back')\n```\n\nSee also [Security best practices: Prevent open redirect vulnerabilities](http://expressjs.com/en/advanced/best-practice-security.html#prevent-open-redirects).\n\n### res.render(view \\[, locals\\] \\[, callback\\])\n\nRenders a `view` and sends the rendered HTML string to the client. Optional parameters:\n\n* `locals`, an object whose properties define local variables for the view.\n* `callback`, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes `next(err)` internally.\n\nThe `view` argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the `views` setting. If the path does not contain a file extension, then the `view engine` setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via `require()`) and render it using the loaded module’s `__express` function.\n\nFor more information, see [Using template engines with Express](https://expressjs.com/en/guide/using-template-engines.html).\n\n**NOTE:** The `view` argument performs file system operations like reading a file from disk and evaluating Node.js modules, and as so for security reasons should not contain input from the end-user.\n\nThe local variable `cache` enables view caching. Set it to `true`, to cache the view during development; view caching is enabled in production by default.\n\n```\n// send the rendered view to the client\nres.render('index')\n\n// if a callback is specified, the rendered HTML string has to be sent explicitly\nres.render('index', (err, html) => {\n res.send(html)\n})\n\n// pass a local variable to the view\nres.render('user', { name: 'Tobi' }, (err, html) => {\n // ...\n})\n```\n\n### res.send(\\[body\\])\n\nSends the HTTP response.\n\nThe `body` parameter can be a `Buffer` object, a `String`, an object, `Boolean`, or an `Array`. For example:\n\n```\nres.send(Buffer.from('whoop'))\nres.send({ some: 'json' })\nres.send('<p>some html</p>')\nres.status(404).send('Sorry, we cannot find that!')\nres.status(500).send({ error: 'something blew up' })\n```\n\nThis method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the `Content-Length` HTTP response header field and provides automatic HEAD and HTTP cache freshness support.\n\nWhen the parameter is a `Buffer` object, the method sets the `Content-Type` response header field to “application/octet-stream”, unless previously defined as shown below:\n\n```\nres.set('Content-Type', 'text/html')\nres.send(Buffer.from('<p>some html</p>'))\n```\n\nWhen the parameter is a `String`, the method sets the `Content-Type` to “text/html”:\n\n```\nres.send('<p>some html</p>')\n```\n\nWhen the parameter is an `Array` or `Object`, Express responds with the JSON representation:\n\n```\nres.send({ user: 'tobi' })\nres.send([1, 2, 3])\n```\n\n### res.sendFile(path \\[, options\\] \\[, fn\\])\n\n`res.sendFile()` is supported by Express v4.8.0 onwards.\n\nTransfers the file at the given `path`. Sets the `Content-Type` response HTTP header field based on the filename’s extension. Unless the `root` option is set in the options object, `path` must be an absolute path to the file.\n\nThis API provides access to data on the running file system. Ensure that either (a) the way in which the `path` argument was constructed into an absolute path is secure if it contains user input or (b) set the `root` option to the absolute path of a directory to contain access within.\n\nWhen the `root` option is provided, the `path` argument is allowed to be a relative path, including containing `..`. Express will validate that the relative path provided as `path` will resolve within the given `root` option.\n\nThe following table provides details on the `options` parameter.\n\nThe method invokes the callback function `fn(err)` when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route.\n\nHere is an example of using `res.sendFile` with all its arguments.\n\n```\napp.get('/file/:name', (req, res, next) => {\n const options = {\n root: path.join(__dirname, 'public'),\n dotfiles: 'deny',\n headers: {\n 'x-timestamp': Date.now(),\n 'x-sent': true\n }\n }\n\n const fileName = req.params.name\n res.sendFile(fileName, options, (err) => {\n if (err) {\n next(err)\n } else {\n console.log('Sent:', fileName)\n }\n })\n})\n```\n\nThe following example illustrates using `res.sendFile` to provide fine-grained support for serving files:\n\n```\napp.get('/user/:uid/photos/:file', (req, res) => {\n const uid = req.params.uid\n const file = req.params.file\n\n req.user.mayViewFilesFrom(uid, (yes) => {\n if (yes) {\n res.sendFile(`/uploads/${uid}/${file}`)\n } else {\n res.status(403).send(\"Sorry! You can't see that.\")\n }\n })\n})\n```\n\nFor more information, or if you have issues or concerns, see [send](https://github.com/pillarjs/send).\n\n### res.sendStatus(statusCode)\n\nSets the response HTTP status code to `statusCode` and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.\n\n```\nres.sendStatus(404)\n```\n\nSome versions of Node.js will throw when `res.statusCode` is set to an invalid HTTP status code (outside of the range `100` to `599`). Consult the HTTP server documentation for the Node.js version being used.\n\n[More about HTTP Status Codes](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes)\n\n### res.set(field \\[, value\\])\n\nSets the response’s HTTP header `field` to `value`. To set multiple fields at once, pass an object as the parameter.\n\n```\nres.set('Content-Type', 'text/plain')\n\nres.set({\n 'Content-Type': 'text/plain',\n 'Content-Length': '123',\n ETag: '12345'\n})\n```\n\nAliased as `res.header(field [, value])`.\n\n### res.status(code)\n\nSets the HTTP status for the response. It is a chainable alias of Node’s [response.statusCode](http://nodejs.org/api/http.html#http_response_statuscode).\n\n```\nres.status(403).end()\nres.status(400).send('Bad Request')\nres.status(404).sendFile('/absolute/path/to/404.png')\n```\n\n### res.type(type)\n\nSets the `Content-Type` HTTP header to the MIME type as determined by the specified `type`. If `type` contains the “/” character, then it sets the `Content-Type` to the exact value of `type`, otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the `express.static.mime.lookup()` method.\n\n```\nres.type('.html') // => 'text/html'\nres.type('html') // => 'text/html'\nres.type('json') // => 'application/json'\nres.type('application/json') // => 'application/json'\nres.type('png') // => image/png:\n```\n\n### res.vary(field)\n\nAdds the field to the `Vary` response header, if it is not there already.\n\n```\nres.vary('User-Agent').render('docs')\n```\n\nRouter\n------\n\nA `router` object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.\n\nA router behaves like middleware itself, so you can use it as an argument to [app.use()](https://expressjs.com/en/5x/api.html#app.use) or as the argument to another router’s [use()](https://expressjs.com/en/5x/api.html#router.use) method.\n\nThe top-level `express` object has a [Router()](https://expressjs.com/en/5x/api.html#express.router) method that creates a new `router` object.\n\nOnce you’ve created a router object, you can add middleware and HTTP method routes (such as `get`, `put`, `post`, and so on) to it just like an application. For example:\n\n```\n// invoked for any requests passed to this router\nrouter.use((req, res, next) => {\n // .. some logic here .. like any other middleware\n next()\n})\n\n// will handle any request that ends in /events\n// depends on where the router is \"use()'d\"\nrouter.get('/events', (req, res, next) => {\n // ..\n})\n```\n\nYou can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.\n\n```\n// only requests to /calendar/* will be sent to our \"router\"\napp.use('/calendar', router)\n```\n\n### Methods\n\n### router.all(path, \\[callback, ...\\] callback)\n\nThis method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).\n\nThis method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you placed the following route at the top of all other route definitions, it would require that all routes from that point on would require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end points; `loadUser` can perform a task, then call `next()` to continue matching subsequent routes.\n\n```\nrouter.all('*', requireAuthentication, loadUser)\n```\n\nOr the equivalent:\n\n```\nrouter.all('*', requireAuthentication)\nrouter.all('*', loadUser)\n```\n\nAnother example of this is white-listed “global” functionality. Here, the example is much like before, but it only restricts paths prefixed with “/api”:\n\n```\nrouter.all('/api/*', requireAuthentication)\n```\n\n### router.METHOD(path, \\[callback, ...\\] callback)\n\nThe `router.METHOD()` methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are `router.get()`, `router.post()`, `router.put()`, and so on.\n\nThe `router.get()` function is automatically called for the HTTP `HEAD` method in addition to the `GET` method if `router.head()` was not called for the path before `router.get()`.\n\nYou can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to perform pre-conditions on a route then pass control to subsequent routes when there is no reason to proceed with the route matched.\n\nThe following snippet illustrates the most simple route definition possible. Express translates the path strings to regular expressions, used internally to match incoming requests. Query strings are _not_ considered when performing these matches, for example “GET /” would match the following route, as would “GET /?name=tobi”.\n\n```\nrouter.get('/', (req, res) => {\n res.send('hello world')\n})\n```\n\nYou can also use regular expressions—useful if you have very specific constraints, for example the following would match “GET /commits/71dbb9c” as well as “GET /commits/71dbb9c..4c084f9”.\n\n```\nrouter.get(/^\\/commits\\/(\\w+)(?:\\.\\.(\\w+))?$/, (req, res) => {\n const from = req.params[0]\n const to = req.params[1] || 'HEAD'\n res.send(`commit range ${from}..${to}`)\n})\n```\n\nYou can use `next` primitive to implement a flow control between different middleware functions, based on a specific program state. Invoking `next` with the string `'router'` will cause all the remaining route callbacks on that router to be bypassed.\n\nThe following example illustrates `next('router')` usage.\n\n```\nfunction fn (req, res, next) {\n console.log('I come here')\n next('router')\n}\nrouter.get('/foo', fn, (req, res, next) => {\n console.log('I dont come here')\n})\nrouter.get('/foo', (req, res, next) => {\n console.log('I dont come here')\n})\napp.get('/foo', (req, res) => {\n console.log(' I come here too')\n res.end('good')\n})\n```\n\n### router.param(name, callback)\n\nAdds callback triggers to route parameters, where `name` is the name of the parameter and `callback` is the callback function. Although `name` is technically optional, using this method without it is deprecated starting with Express v4.11.0 (see below).\n\nThe parameters of the callback function are:\n\n* `req`, the request object.\n* `res`, the response object.\n* `next`, indicating the next middleware function.\n* The value of the `name` parameter.\n* The name of the parameter.\n\nUnlike `app.param()`, `router.param()` does not accept an array of route parameters.\n\nFor example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input.\n\n```\nrouter.param('user', (req, res, next, id) => {\n // try to get the user details from the User model and attach it to the request object\n User.find(id, (err, user) => {\n if (err) {\n next(err)\n } else if (user) {\n req.user = user\n next()\n } else {\n next(new Error('failed to load user'))\n }\n })\n})\n```\n\nParam callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on `router` will be triggered only by route parameters defined on `router` routes.\n\nA param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.\n\n```\nrouter.param('id', (req, res, next, id) => {\n console.log('CALLED ONLY ONCE')\n next()\n})\n\nrouter.get('/user/:id', (req, res, next) => {\n console.log('although this matches')\n next()\n})\n\nrouter.get('/user/:id', (req, res) => {\n console.log('and this matches too')\n res.end()\n})\n```\n\nOn `GET /user/42`, the following is printed:\n\n```\nCALLED ONLY ONCE\nalthough this matches\nand this matches too\n```\n\nThe following section describes `router.param(callback)`, which is deprecated as of v4.11.0.\n\nThe behavior of the `router.param(name, callback)` method can be altered entirely by passing only a function to `router.param()`. This function is a custom implementation of how `router.param(name, callback)` should behave - it accepts two parameters and must return a middleware.\n\nThe first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.\n\nThe middleware returned by the function decides the behavior of what happens when a URL parameter is captured.\n\nIn this example, the `router.param(name, callback)` signature is modified to `router.param(name, accessId)`. Instead of accepting a name and a callback, `router.param()` will now accept a name and a number.\n\n```\nconst express = require('express')\nconst app = express()\nconst router = express.Router()\n\n// customizing the behavior of router.param()\nrouter.param((param, option) => {\n return (req, res, next, val) => {\n if (val === option) {\n next()\n } else {\n res.sendStatus(403)\n }\n }\n})\n\n// using the customized router.param()\nrouter.param('id', 1337)\n\n// route to trigger the capture\nrouter.get('/user/:id', (req, res) => {\n res.send('OK')\n})\n\napp.use(router)\n\napp.listen(3000, () => {\n console.log('Ready')\n})\n```\n\nIn this example, the `router.param(name, callback)` signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.\n\n```\nrouter.param((param, validator) => {\n return (req, res, next, val) => {\n if (validator(val)) {\n next()\n } else {\n res.sendStatus(403)\n }\n }\n})\n\nrouter.param('id', (candidate) => {\n return !isNaN(parseFloat(candidate)) && isFinite(candidate)\n})\n```\n\n### router.route(path)\n\nReturns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use `router.route()` to avoid duplicate route naming and thus typing errors.\n\nBuilding on the `router.param()` example above, the following code shows how to use `router.route()` to specify various HTTP method handlers.\n\n```\nconst router = express.Router()\n\nrouter.param('user_id', (req, res, next, id) => {\n // sample user, would actually fetch from DB, etc...\n req.user = {\n id,\n name: 'TJ'\n }\n next()\n})\n\nrouter.route('/users/:user_id')\n .all((req, res, next) => {\n // runs for all HTTP verbs first\n // think of it as route specific middleware!\n next()\n })\n .get((req, res, next) => {\n res.json(req.user)\n })\n .put((req, res, next) => {\n // just an example of maybe updating the user\n req.user.name = req.params.name\n // save user ... etc\n res.json(req.user)\n })\n .post((req, res, next) => {\n next(new Error('not implemented'))\n })\n .delete((req, res, next) => {\n next(new Error('not implemented'))\n })\n```\n\nThis approach re-uses the single `/users/:user_id` path and adds handlers for various HTTP methods.\n\nNOTE: When you use `router.route()`, middleware ordering is based on when the _route_ is created, not when method handlers are added to the route. For this purpose, you can consider method handlers to belong to the route to which they were added.\n\n### router.use(\\[path\\], \\[function, ...\\] function)\n\nUses the specified middleware function or functions, with optional mount path `path`, that defaults to “/”.\n\nThis method is similar to [app.use()](https://expressjs.com/en/5x/api.html#app.use). A simple example and use case is described below. See [app.use()](https://expressjs.com/en/5x/api.html#app.use) for more information.\n\nMiddleware is like a plumbing pipe: requests start at the first middleware function defined and work their way “down” the middleware stack processing for each path they match.\n\n```\nconst express = require('express')\nconst app = express()\nconst router = express.Router()\n\n// simple logger for this router's requests\n// all requests to this router will first hit this middleware\nrouter.use((req, res, next) => {\n console.log('%s %s %s', req.method, req.url, req.path)\n next()\n})\n\n// this will only be invoked if the path starts with /bar from the mount point\nrouter.use('/bar', (req, res, next) => {\n // ... maybe some additional /bar logging ...\n next()\n})\n\n// always invoked\nrouter.use((req, res, next) => {\n res.send('Hello World')\n})\n\napp.use('/foo', router)\n\napp.listen(3000)\n```\n\nThe “mount” path is stripped and is _not_ visible to the middleware function. The main effect of this feature is that a mounted middleware function may operate without code changes regardless of its “prefix” pathname.\n\nThe order in which you define middleware with `router.use()` is very important. They are invoked sequentially, thus the order defines middleware precedence. For example, usually a logger is the very first middleware you would use, so that every request gets logged.\n\n```\nconst logger = require('morgan')\n\nrouter.use(logger())\nrouter.use(express.static(path.join(__dirname, 'public')))\nrouter.use((req, res) => {\n res.send('Hello')\n})\n```\n\nNow suppose you wanted to ignore logging requests for static files, but to continue logging routes and middleware defined after `logger()`. You would simply move the call to `express.static()` to the top, before adding the logger middleware:\n\n```\nrouter.use(express.static(path.join(__dirname, 'public')))\nrouter.use(logger())\nrouter.use((req, res) => {\n res.send('Hello')\n})\n```\n\nAnother example is serving files from multiple directories, giving precedence to “./public” over the others:\n\n```\napp.use(express.static(path.join(__dirname, 'public')))\napp.use(express.static(path.join(__dirname, 'files')))\napp.use(express.static(path.join(__dirname, 'uploads')))\n```\n\nThe `router.use()` method also supports named parameters so that your mount points for other routers can benefit from preloading using named parameters.\n\n**NOTE**: Although these middleware functions are added via a particular router, _when_ they run is defined by the path they are attached to (not the router). Therefore, middleware added via one router may run for other routers if its routes match. For example, this code shows two different routers mounted on the same path:\n\n```\nconst authRouter = express.Router()\nconst openRouter = express.Router()\n\nauthRouter.use(require('./authenticate').basic(usersdb))\n\nauthRouter.get('/:user_id/edit', (req, res, next) => {\n // ... Edit user UI ...\n})\nopenRouter.get('/', (req, res, next) => {\n // ... List users ...\n})\nopenRouter.get('/:user_id', (req, res, next) => {\n // ... View user ...\n})\n\napp.use('/users', authRouter)\napp.use('/users', openRouter)\n```\n\nEven though the authentication middleware was added via the `authRouter` it will run on the routes defined by the `openRouter` as well since both routers were mounted on `/users`. To avoid this behavior, use different paths for each router.\n", "filename": "api.md", "package": "express" }
{ "content": "Title: Express basic routing\n\nURL Source: https://expressjs.com/en/starter/basic-routing.html\n\nMarkdown Content:\nExpress basic routing\n===============\n \nBasic routing\n=============\n\n_Routing_ refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).\n\nEach route can have one or more handler functions, which are executed when the route is matched.\n\nRoute definition takes the following structure:\n\n```javascript\napp.METHOD(PATH, HANDLER)\n```\n\nWhere:\n\n* `app` is an instance of `express`.\n* `METHOD` is an [HTTP request method](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods), in lowercase.\n* `PATH` is a path on the server.\n* `HANDLER` is the function executed when the route is matched.\n\nThis tutorial assumes that an instance of `express` named `app` is created and the server is running. If you are not familiar with creating an app and starting it, see the [Hello world example](https://expressjs.com/en/starter/hello-world.html).\n\nThe following examples illustrate defining simple routes.\n\nRespond with `Hello World!` on the homepage:\n\n```javascript\napp.get('/', (req, res) => {\n res.send('Hello World!')\n})\n```\n\nRespond to POST request on the root route (`/`), the application’s home page:\n\n```javascript\napp.post('/', (req, res) => {\n res.send('Got a POST request')\n})\n```\n\nRespond to a PUT request to the `/user` route:\n\n```javascript\napp.put('/user', (req, res) => {\n res.send('Got a PUT request at /user')\n})\n```\n\nRespond to a DELETE request to the `/user` route:\n\n```javascript\napp.delete('/user', (req, res) => {\n res.send('Got a DELETE request at /user')\n})\n```\n\nFor more details about routing, see the [routing guide](https://expressjs.com/en/guide/routing.html).\n\n### [Previous: Express application generator](https://expressjs.com/en/starter/generator.html)     [Next: Serving static files in Express](https://expressjs.com/en/starter/static-files.html)\n\n[![Image 1](https://expressjs.com/images/arrow.png)](https://expressjs.com/en/starter/basic-routing.html#)\n\nDocumentation translations provided by StrongLoop/IBM: [French](https://expressjs.com/fr/), [German](https://expressjs.com/de/), [Spanish](https://expressjs.com/es/), [Italian](https://expressjs.com/it/), [Japanese](https://expressjs.com/ja/), [Russian](https://expressjs.com/ru/), [Chinese](https://expressjs.com/zh-cn/), [Traditional Chinese](https://expressjs.com/zh-tw/), [Korean](https://expressjs.com/ko/), [Portuguese](https://expressjs.com/pt-br/). \nCommunity translation available for: [Slovak](https://expressjs.com/sk/), [Ukrainian](https://expressjs.com/uk/), [Uzbek](https://expressjs.com/uz/), [Turkish](https://expressjs.com/tr/), [Thai](https://expressjs.com/th/) and [Indonesian](https://expressjs.com/id/).\n\n[![Image 2: Preview Deploys by Netlify](https://www.netlify.com/v3/img/components/netlify-color-accent.svg)](https://www.netlify.com/)\n\n[Express](https://expressjs.com/) is a project of the [OpenJS Foundation](https://openjsf.org/).\n\n[Edit this page on GitHub](https://github.com/expressjs/expressjs.com/blob/gh-pages/en/starter/basic-routing.md).\n\nCopyright © 2017 StrongLoop, IBM, and other expressjs.com contributors.\n\n[![Image 3: Creative Commons License](https://i.creativecommons.org/l/by-sa/3.0/us/80x15.png)](http://creativecommons.org/licenses/by-sa/3.0/us/) This work is licensed under a [Creative Commons Attribution-ShareAlike 3.0 United States License](http://creativecommons.org/licenses/by-sa/3.0/us/).\n", "filename": "basic-routing.md", "package": "express" }
{ "content": "Title: Express behind proxies\n\nURL Source: https://expressjs.com/en/guide/behind-proxies.html\n\nMarkdown Content:\nWhen running an Express app behind a reverse proxy, some of the Express APIs may return different values than expected. In order to adjust for this, the `trust proxy` application setting may be used to expose information provided by the reverse proxy in the Express APIs. The most common issue is express APIs that expose the client’s IP address may instead show an internal IP address of the reverse proxy.\n\nWhen configuring the `trust proxy` setting, it is important to understand the exact setup of the reverse proxy. Since this setting will trust values provided in the request, it is important that the combination of the setting in Express matches how the reverse proxy operates.\n\nThe application setting `trust proxy` may be set to one of the values listed in the following table.\n\n| Type | Value |\n| --- | --- |\n| Boolean | If `true`, the client’s IP address is understood as the left-most entry in the `X-Forwarded-For` header.\nIf `false`, the app is understood as directly facing the client and the client’s IP address is derived from `req.socket.remoteAddress`. This is the default setting.\n\nWhen setting to `true`, it is important to ensure that the last reverse proxy trusted is removing/overwriting all of the following HTTP headers: `X-Forwarded-For`, `X-Forwarded-Host`, and `X-Forwarded-Proto`, otherwise it may be possible for the client to provide any value.\n\n |\n| IP addresses | An IP address, subnet, or an array of IP addresses and subnets to trust as being a reverse proxy. The following list shows the pre-configured subnet names:\n\n* loopback - `127.0.0.1/8`, `::1/128`\n* linklocal - `169.254.0.0/16`, `fe80::/10`\n* uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7`\n\nYou can set IP addresses in any of the following ways:\n\n```\napp.set('trust proxy', 'loopback') // specify a single subnet\napp.set('trust proxy', 'loopback, 123.123.123.123') // specify a subnet and an address\napp.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple subnets as CSV\napp.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array\n```\n\nWhen specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client’s IP address. This works by checking if `req.socket.remoteAddress` is trusted. If so, then each address in `X-Forwarded-For` is checked from right to left until the first non-trusted address.\n\n |\n| Number | Use the address that is at most `n` number of hops away from the Express application. `req.socket.remoteAddress` is the first hop, and the rest are looked for in the `X-Forwarded-For` header from right to left. A value of `0` means that the first untrusted address would be `req.socket.remoteAddress`, i.e. there is no reverse proxy.\n\nWhen using this setting, it is important to ensure there are not multiple, different-length paths to the Express application such that the client can be less than the configured number of hops away, otherwise it may be possible for the client to provide any value.\n\n |\n| Function | Custom trust implementation.\n\n```\napp.set('trust proxy', (ip) => {\n if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs\n else return false\n})\n```\n\n |\n\nEnabling `trust proxy` will have the following impact:\n\n* The value of [req.hostname](https://expressjs.com/en/api.html#req.hostname) is derived from the value set in the `X-Forwarded-Host` header, which can be set by the client or by the proxy.\n \n* `X-Forwarded-Proto` can be set by the reverse proxy to tell the app whether it is `https` or `http` or even an invalid name. This value is reflected by [req.protocol](https://expressjs.com/en/api.html#req.protocol).\n \n* The [req.ip](https://expressjs.com/en/api.html#req.ip) and [req.ips](https://expressjs.com/en/api.html#req.ips) values are populated based on the socket address and `X-Forwarded-For` header, starting at the first untrusted address.\n \n\nThe `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation.\n", "filename": "behind-proxies.md", "package": "express" }
{ "content": "Title: Performance Best Practices Using Express in Production\n\nURL Source: https://expressjs.com/en/advanced/best-practice-performance.html\n\nMarkdown Content:\nProduction best practices: performance and reliability\n------------------------------------------------------\n\n### Use gzip compression\n\nGzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the [compression](https://www.npmjs.com/package/compression) middleware for gzip compression in your Express app. For example:\n\n```\nconst compression = require('compression')\nconst express = require('express')\nconst app = express()\napp.use(compression())\n```\n\nFor a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](https://expressjs.com/en/advanced/best-practice-performance.html#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx\\_http\\_gzip\\_module](http://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation.\n\n### Don’t use synchronous functions\n\nSynchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.\n\nAlthough Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup.\n\nIf you are using Node.js 4.0+ or io.js 2.1.0+, you can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn’t want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#cli_trace_sync_io) for more information.\n\n### Do logging correctly\n\nIn general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console_console_1) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program.\n\n#### For debugging\n\nIf you’re logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you’d still want to pipe `console.error()` to another program. But then, you’re not really going to debug in production, are you?\n\n#### For app activity\n\nIf you’re logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Winston](https://www.npmjs.com/package/winston) or [Bunyan](https://www.npmjs.com/package/bunyan). For a detailed comparison of these two libraries, see the StrongLoop blog post [Comparing Winston and Bunyan Node.js Logging](https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/).\n\n### Handle exceptions properly\n\nNode apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](https://expressjs.com/en/advanced/best-practice-performance.html#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly.\n\nTo ensure you handle all exceptions, use the following techniques:\n\n* [Use try-catch](https://expressjs.com/en/advanced/best-practice-performance.html#use-try-catch)\n* [Use promises](https://expressjs.com/en/advanced/best-practice-performance.html#use-promises)\n\nBefore diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an “error-first callback” convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain.\n\nFor more on the fundamentals of error handling, see:\n\n* [Error Handling in Node.js](https://www.tritondatacenter.com/node-js/production/design/errors)\n* [Building Robust Node Applications: Error Handling](https://strongloop.com/strongblog/robust-node-applications-error-handling/) (StrongLoop blog)\n\n#### What not to do\n\nOne thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable.\n\nAdditionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#process_event_uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error.\n\nWe also don’t recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn’t solve the problem and is a deprecated module.\n\n#### Use try-catch\n\nTry-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.\n\nUse a tool such as [JSHint](http://jshint.com/) or [JSLint](http://www.jslint.com/) to help you find implicit exceptions like [reference errors on undefined variables](http://www.jshint.com/docs/options/#undef).\n\nHere is an example of using try-catch to handle a potential process-crashing exception. This middleware function accepts a query field parameter named “params” that is a JSON object.\n\n```\napp.get('/search', (req, res) => {\n // Simulating async operation\n setImmediate(() => {\n const jsonStr = req.query.params\n try {\n const jsonObj = JSON.parse(jsonStr)\n res.send('Success')\n } catch (e) {\n res.status(400).send('Invalid JSON string')\n }\n })\n})\n```\n\nHowever, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won’t catch a lot of exceptions.\n\n#### Use promises\n\nPromises will handle any exceptions (both explicit and implicit) in asynchronous code blocks that use `then()`. Just add `.catch(next)` to the end of promise chains. For example:\n\n```\napp.get('/', (req, res, next) => {\n // do some sync stuff\n queryDb()\n .then((data) => makeCsv(data)) // handle data\n .then((csv) => { /* handle csv */ })\n .catch(next)\n})\n\napp.use((err, req, res, next) => {\n // handle error\n})\n```\n\nNow, all errors asynchronous and synchronous get propagated to the error middleware.\n\nHowever, there are two caveats:\n\n1. All your asynchronous code must return promises (except emitters). If a particular library does not return promises, convert the base object by using a helper function like [Bluebird.promisifyAll()](http://bluebirdjs.com/docs/api/promise.promisifyall.html).\n2. Event emitters (like `streams`) can still cause uncaught exceptions. So make sure you are handling the error event properly; for example:\n\n```\nconst wrap = fn => (...args) => fn(...args).catch(args[2])\n\napp.get('/', wrap(async (req, res, next) => {\n const company = await getCompanyById(req.query.id)\n const stream = getLogoStreamById(company.id)\n stream.on('error', next).pipe(res)\n}))\n```\n\nThe `wrap()` function is a wrapper that catches rejected promises and calls `next()` with the error as the first argument. For details, see [Asynchronous Error Handling in Express with Promises, Generators and ES7](https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/#cleaner-code-with-generators).\n\nFor more information about error-handling by using promises, see [Promises in Node.js with Q – An Alternative to Callbacks](https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/).\n\nThings to do in your environment / setup\n----------------------------------------\n\nHere are some things you can do in your system environment to improve your app’s performance:\n\n* [Set NODE\\_ENV to “production”](https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production)\n* [Ensure your app automatically restarts](https://expressjs.com/en/advanced/best-practice-performance.html#ensure-your-app-automatically-restarts)\n* [Run your app in a cluster](https://expressjs.com/en/advanced/best-practice-performance.html#run-your-app-in-a-cluster)\n* [Cache request results](https://expressjs.com/en/advanced/best-practice-performance.html#cache-request-results)\n* [Use a load balancer](https://expressjs.com/en/advanced/best-practice-performance.html#use-a-load-balancer)\n* [Use a reverse proxy](https://expressjs.com/en/advanced/best-practice-performance.html#use-a-reverse-proxy)\n\n### Set NODE\\_ENV to “production”\n\nThe NODE\\_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE\\_ENV to “production.”\n\nSetting NODE\\_ENV to “production” makes Express:\n\n* Cache view templates.\n* Cache CSS files generated from CSS extensions.\n* Generate less verbose error messages.\n\n[Tests indicate](http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three!\n\nIf you need to write environment-specific code, you can check the value of NODE\\_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly.\n\nIn development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general, you shouldn’t do that on a production server; instead, use your OS’s init system (systemd or Upstart). The next section provides more details about using your init system in general, but setting `NODE_ENV` is so important for performance (and easy to do), that it’s highlighted here.\n\nWith Upstart, use the `env` keyword in your job file. For example:\n\n```\n# /etc/init/env.conf\n env NODE_ENV=production\n```\n\nFor more information, see the [Upstart Intro, Cookbook and Best Practices](http://upstart.ubuntu.com/cookbook/#environment-variables).\n\nWith systemd, use the `Environment` directive in your unit file. For example:\n\n```\n# /etc/systemd/system/myservice.service\nEnvironment=NODE_ENV=production\n```\n\nFor more information, see [Using Environment Variables In systemd Units](https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html).\n\n### Ensure your app automatically restarts\n\nIn production, you don’t want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by:\n\n* Using a process manager to restart the app (and Node) when it crashes.\n* Using the init system provided by your OS to restart the process manager when the OS crashes. It’s also possible to use the init system without a process manager.\n\nNode applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](https://expressjs.com/en/advanced/best-practice-performance.html#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart.\n\n#### Use a process manager\n\nIn development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a “container” for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime.\n\nIn addition to restarting your app when it crashes, a process manager can enable you to:\n\n* Gain insights into runtime performance and resource consumption.\n* Modify settings dynamically to improve performance.\n* Control clustering (StrongLoop PM and pm2).\n\nThe most popular process managers for Node are as follows:\n\n* [StrongLoop Process Manager](http://strong-pm.io/)\n* [PM2](https://github.com/Unitech/pm2)\n* [Forever](https://www.npmjs.com/package/forever)\n\nFor a feature-by-feature comparison of the three process managers, see [http://strong-pm.io/compare/](http://strong-pm.io/compare/).\n\nUsing any of these process managers will suffice to keep your application up, even if it does crash from time to time.\n\nHowever, StrongLoop PM has lots of features that specifically target production deployment. You can use it and the related StrongLoop tools to:\n\n* Build and package your app locally, then deploy it securely to your production system.\n* Automatically restart your app if it crashes for any reason.\n* Manage your clusters remotely.\n* View CPU profiles and heap snapshots to optimize performance and diagnose memory leaks.\n* View performance metrics for your application.\n* Easily scale to multiple hosts with integrated control for Nginx load balancer.\n\nAs explained below, when you install StrongLoop PM as an operating system service using your init system, it will automatically restart when the system restarts. Thus, it will keep your application processes and clusters alive forever.\n\n#### Use an init system\n\nThe next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The two main init systems in use today are [systemd](https://wiki.debian.org/systemd) and [Upstart](http://upstart.ubuntu.com/).\n\nThere are two ways to use init systems with your Express app:\n\n* Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach.\n* Run your app (and Node) directly with the init system. This is somewhat simpler, but you don’t get the additional advantages of using a process manager.\n\n##### Systemd\n\nSystemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system.\n\nA systemd service configuration file is called a _unit file_, with a filename ending in `.service`. Here’s an example unit file to manage a Node app directly. Replace the values enclosed in `<angle brackets>` for your system and app:\n\n```\n[Unit]\nDescription=<Awesome Express App>\n\n[Service]\nType=simple\nExecStart=/usr/local/bin/node </projects/myapp/index.js>\nWorkingDirectory=</projects/myapp>\n\nUser=nobody\nGroup=nogroup\n\n# Environment variables:\nEnvironment=NODE_ENV=production\n\n# Allow many incoming connections\nLimitNOFILE=infinity\n\n# Allow core dumps for debugging\nLimitCORE=infinity\n\nStandardInput=null\nStandardOutput=syslog\nStandardError=syslog\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\n```\n\nFor more information on systemd, see the [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit.html).\n\n##### StrongLoop PM as a systemd service\n\nYou can easily install StrongLoop Process Manager as a systemd service. After you do, when the server restarts, it will automatically restart StrongLoop PM, which will then restart all the apps it is managing.\n\nTo install StrongLoop PM as a systemd service:\n\n```\n$ sudo sl-pm-install --systemd\n```\n\nThen start the service with:\n\n```\n$ sudo /usr/bin/systemctl start strong-pm\n```\n\nFor more information, see [Setting up a production host (StrongLoop documentation)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHEL7+,Ubuntu15.04or15.10).\n\n##### Upstart\n\nUpstart is a system tool available on many Linux distributions for starting tasks and services during system startup, stopping them during shutdown, and supervising them. You can configure your Express app or process manager as a service and then Upstart will automatically restart it when it crashes.\n\nAn Upstart service is defined in a job configuration file (also called a “job”) with filename ending in `.conf`. The following example shows how to create a job called “myapp” for an app named “myapp” with the main file located at `/projects/myapp/index.js`.\n\nCreate a file named `myapp.conf` at `/etc/init/` with the following content (replace the bold text with values for your system and app):\n\n```\n# When to start the process\nstart on runlevel [2345]\n\n# When to stop the process\nstop on runlevel [016]\n\n# Increase file descriptor limit to be able to handle more requests\nlimit nofile 50000 50000\n\n# Use production mode\nenv NODE_ENV=production\n\n# Run as www-data\nsetuid www-data\nsetgid www-data\n\n# Run from inside the app dir\nchdir /projects/myapp\n\n# The process to start\nexec /usr/local/bin/node /projects/myapp/index.js\n\n# Restart the process if it is down\nrespawn\n\n# Limit restart attempt to 10 times within 10 seconds\nrespawn limit 10 10\n```\n\nNOTE: This script requires Upstart 1.4 or newer, supported on Ubuntu 12.04-14.10.\n\nSince the job is configured to run when the system starts, your app will be started along with the operating system, and automatically restarted if the app crashes or the system goes down.\n\nApart from automatically restarting the app, Upstart enables you to use these commands:\n\n* `start myapp` – Start the app\n* `restart myapp` – Restart the app\n* `stop myapp` – Stop the app.\n\nFor more information on Upstart, see [Upstart Intro, Cookbook and Best Practises](http://upstart.ubuntu.com/cookbook).\n\n##### StrongLoop PM as an Upstart service\n\nYou can easily install StrongLoop Process Manager as an Upstart service. After you do, when the server restarts, it will automatically restart StrongLoop PM, which will then restart all the apps it is managing.\n\nTo install StrongLoop PM as an Upstart 1.4 service:\n\n```\n$ sudo sl-pm-install\n```\n\nThen run the service with:\n\n```\n$ sudo /sbin/initctl start strong-pm\n```\n\nNOTE: On systems that don’t support Upstart 1.4, the commands are slightly different. See [Setting up a production host (StrongLoop documentation)](https://docs.strongloop.com/display/SLC/Setting+up+a+production+host#Settingupaproductionhost-RHELLinux5and6,Ubuntu10.04-.10,11.04-.10) for more information.\n\n### Run your app in a cluster\n\nIn a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances.\n\n![Image 1: Balancing between application instances using the cluster API](https://expressjs.com/images/clustering.png)\n\nIMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](http://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers.\n\nIn clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork().\n\n#### Using Node’s cluster module\n\nClustering is made possible with Node’s [cluster module](https://nodejs.org/dist/latest-v4.x/docs/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers. However, rather than using this module directly, it’s far better to use one of the many tools out there that does it for you automatically; for example [node-pm](https://www.npmjs.com/package/node-pm) or [cluster-service](https://www.npmjs.com/package/cluster-service).\n\n#### Using StrongLoop PM\n\nIf you deploy your application to StrongLoop Process Manager (PM), then you can take advantage of clustering _without_ modifying your application code.\n\nWhen StrongLoop Process Manager (PM) runs an application, it automatically runs it in a cluster with a number of workers equal to the number of CPU cores on the system. You can manually change the number of worker processes in the cluster using the slc command line tool without stopping the app.\n\nFor example, assuming you’ve deployed your app to prod.foo.com and StrongLoop PM is listening on port 8701 (the default), then to set the cluster size to eight using slc:\n\n```\n$ slc ctl -C http://prod.foo.com:8701 set-size my-app 8\n```\n\nFor more information on clustering with StrongLoop PM, see [Clustering](https://docs.strongloop.com/display/SLC/Clustering) in StrongLoop documentation.\n\n#### Using PM2\n\nIf you deploy your application with PM2, then you can take advantage of clustering _without_ modifying your application code. You should ensure your [application is stateless](http://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like).\n\nWhen running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app.\n\nTo enable cluster mode, start your application like so:\n\n```\n# Start 4 worker processes\n$ pm2 start npm --name my-app -i 4 -- start\n# Auto-detect number of available CPUs and start that many worker processes\n$ pm2 start npm --name my-app -i max -- start\n```\n\nThis can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start.\n\nOnce running, the application can be scaled like so:\n\n```\n# Add 3 more workers\n$ pm2 scale my-app +3\n# Scale to a specific number of workers\n$ pm2 scale my-app 2\n```\n\nFor more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation.\n\n### Cache request results\n\nAnother strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly.\n\nUse a caching server like [Varnish](https://www.varnish-cache.org/) or [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) (see also [Nginx Caching](https://serversforhackers.com/nginx-caching/)) to greatly improve the speed and performance of your app.\n\n### Use a load balancer\n\nNo matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app’s performance and speed, and enable it to scale more than is possible with a single instance.\n\nA load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](http://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts).\n\nWith load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).\n\n### Use a reverse proxy\n\nA reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things.\n\nHanding over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://www.nginx.com/) or [HAProxy](http://www.haproxy.org/) in production.\n", "filename": "best-practice-performance.md", "package": "express" }
{ "content": "Title: Security Best Practices for Express in Production\n\nURL Source: https://expressjs.com/en/advanced/best-practice-security.html\n\nMarkdown Content:\nOverview\n--------\n\nThe term _“production”_ refers to the stage in the software lifecycle when an application or API is generally available to its end-users or consumers. In contrast, in the _“development”_ stage, you’re still actively writing and testing code, and the application is not open to external access. The corresponding system environments are known as _production_ and _development_ environments, respectively.\n\nDevelopment and production environments are usually set up differently and have vastly different requirements. What’s fine in development may not be acceptable in production. For example, in a development environment you may want verbose logging of errors for debugging, while the same behavior can become a security concern in a production environment. And in development, you don’t need to worry about scalability, reliability, and performance, while those concerns become critical in production.\n\nDon’t use deprecated or vulnerable versions of Express\n------------------------------------------------------\n\nExpress 2.x and 3.x are no longer maintained. Security and performance issues in these versions won’t be fixed. Do not use them! If you haven’t moved to version 4, follow the [migration guide](https://expressjs.com/en/guide/migrating-4.html).\n\nAlso ensure you are not using any of the vulnerable Express versions listed on the [Security updates page](https://expressjs.com/en/advanced/security-updates.html). If you are, update to one of the stable releases, preferably the latest.\n\nUse TLS\n-------\n\nIf your app deals with or transmits sensitive data, use [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) to secure the connection and the data. This technology encrypts data before it is sent from the client to the server, thus preventing some common (and easy) hacks. Although Ajax and POST requests might not be visibly obvious and seem “hidden” in browsers, their network traffic is vulnerable to [packet sniffing](https://en.wikipedia.org/wiki/Packet_analyzer) and [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).\n\nYou may be familiar with Secure Socket Layer (SSL) encryption. [TLS is simply the next progression of SSL](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380515/(v=vs.85/).aspx). In other words, if you were using SSL before, consider upgrading to TLS. In general, we recommend Nginx to handle TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (Mozilla Wiki)](https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_Server_Configurations).\n\nAlso, a handy tool to get a free TLS certificate is [Let’s Encrypt](https://letsencrypt.org/about/), a free, automated, and open certificate authority (CA) provided by the [Internet Security Research Group (ISRG)](https://www.abetterinternet.org/).\n\nDo not trust user input\n-----------------------\n\nFor web applications, one of the most critical security requirements is proper user input validation and handling. This comes in many forms and we will not cover all of them here. Ultimately, the responsibility for validating and correctly handling the types of user input your application accepts. Here are a few examples of validating user input specifically using a few `express` apis.\n\n### Prevent open redirects\n\nAn example of potentially dangerous user input is an _open redirect_, where an application accepts a URL as user input (often in the URL query, for example `?url=https://example.com`) and uses `res.redirect` to set the `location` header and return a 3xx status.\n\nAn application must validate that it supports redirecting to the incoming URL to avoid sending users to malicious links such as phishing websites, among other risks.\n\nHere is an example of checking URLs before using `res.redirect` or `res.location`:\n\n```\napp.use((req, res) => {\n try {\n if (new Url(req.query.url).host !== 'example.com') {\n return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`)\n }\n } catch (e) {\n return res.status(400).end(`Invalid url: ${req.query.url}`)\n }\n res.redirect(req.query.url)\n})\n```\n\nUse Helmet\n----------\n\n[Helmet](https://helmetjs.github.io/) can help protect your app from some well-known web vulnerabilities by setting HTTP headers appropriately.\n\nHelmet is a collection of several smaller middleware functions that set security-related HTTP response headers. Some examples include:\n\n* `helmet.contentSecurityPolicy` which sets the `Content-Security-Policy` header. This helps prevent cross-site scripting attacks among many other things.\n* `helmet.hsts` which sets the `Strict-Transport-Security` header. This helps enforce secure (HTTPS) connections to the server.\n* `helmet.frameguard` which sets the `X-Frame-Options` header. This provides [clickjacking](https://www.owasp.org/index.php/Clickjacking) protection.\n\nHelmet includes several other middleware functions which you can read about [at its documentation website](https://helmetjs.github.io/).\n\nInstall Helmet like any other module:\n\n```\n$ npm install --save helmet\n```\n\nThen to use it in your code:\n\n```\n// ...\n\nconst helmet = require('helmet')\napp.use(helmet())\n\n// ...\n```\n\nReduce fingerprinting\n---------------------\n\nIt can help to provide an extra layer of security to reduce the ability of attackers to determine the software that a server uses, known as “fingerprinting.” Though not a security issue itself, reducing the ability to fingerprint an application improves its overall security posture. Server software can be fingerprinted by quirks in how it responds to specific requests, for example in the HTTP response headers.\n\nBy default, Express sends the `X-Powered-By` response header that you can disable using the `app.disable()` method:\n\n```\napp.disable('x-powered-by')\n```\n\n**Note**: Disabling the `X-Powered-By header` does not prevent a sophisticated attacker from determining that an app is running Express. It may discourage a casual exploit, but there are other ways to determine an app is running Express.\n\nExpress also sends its own formatted “404 Not Found” messages and formatter error response messages. These can be changed by [adding your own not found handler](https://expressjs.com/en/starter/faq.html#how-do-i-handle-404-responses) and [writing your own error handler](https://expressjs.com/en/guide/error-handling.html#writing-error-handlers):\n\n```\n// last app.use calls right before app.listen():\n\n// custom 404\napp.use((req, res, next) => {\n res.status(404).send(\"Sorry can't find that!\")\n})\n\n// custom error handler\napp.use((err, req, res, next) => {\n console.error(err.stack)\n res.status(500).send('Something broke!')\n})\n```\n\nUse cookies securely\n--------------------\n\nTo ensure cookies don’t open your app to exploits, don’t use the default session cookie name and set cookie security options appropriately.\n\nThere are two main middleware cookie session modules:\n\n* [express-session](https://www.npmjs.com/package/express-session) that replaces `express.session` middleware built-in to Express 3.x.\n* [cookie-session](https://www.npmjs.com/package/cookie-session) that replaces `express.cookieSession` middleware built-in to Express 3.x.\n\nThe main difference between these two modules is how they save cookie session data. The [express-session](https://www.npmjs.com/package/express-session) middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment. In production, you’ll need to set up a scalable session-store; see the list of [compatible session stores](https://github.com/expressjs/session#compatible-session-stores).\n\nIn contrast, [cookie-session](https://www.npmjs.com/package/cookie-session) middleware implements cookie-backed storage: it serializes the entire session to the cookie, rather than just a session key. Only use it when session data is relatively small and easily encoded as primitive values (rather than objects). Although browsers are supposed to support at least 4096 bytes per cookie, to ensure you don’t exceed the limit, don’t exceed a size of 4093 bytes per domain. Also, be aware that the cookie data will be visible to the client, so if there is any reason to keep it secure or obscure, then `express-session` may be a better choice.\n\n### Don’t use the default session cookie name\n\nUsing the default session cookie name can open your app to attacks. The security issue posed is similar to `X-Powered-By`: a potential attacker can use it to fingerprint the server and target attacks accordingly.\n\nTo avoid this problem, use generic cookie names; for example using [express-session](https://www.npmjs.com/package/express-session) middleware:\n\n```\nconst session = require('express-session')\napp.set('trust proxy', 1) // trust first proxy\napp.use(session({\n secret: 's3Cur3',\n name: 'sessionId'\n}))\n```\n\n### Set cookie security options\n\nSet the following cookie options to enhance security:\n\n* `secure` - Ensures the browser only sends the cookie over HTTPS.\n* `httpOnly` - Ensures the cookie is sent only over HTTP(S), not client JavaScript, helping to protect against cross-site scripting attacks.\n* `domain` - indicates the domain of the cookie; use it to compare against the domain of the server in which the URL is being requested. If they match, then check the path attribute next.\n* `path` - indicates the path of the cookie; use it to compare against the request path. If this and domain match, then send the cookie in the request.\n* `expires` - use to set expiration date for persistent cookies.\n\nHere is an example using [cookie-session](https://www.npmjs.com/package/cookie-session) middleware:\n\n```\nconst session = require('cookie-session')\nconst express = require('express')\nconst app = express()\n\nconst expiryDate = new Date(Date.now() + 60 * 60 * 1000) // 1 hour\napp.use(session({\n name: 'session',\n keys: ['key1', 'key2'],\n cookie: {\n secure: true,\n httpOnly: true,\n domain: 'example.com',\n path: 'foo/bar',\n expires: expiryDate\n }\n}))\n```\n\nMake sure login endpoints are protected to make private data more secure.\n\nA simple and powerful technique is to block authorization attempts using two metrics:\n\n1. The number of consecutive failed attempts by the same user name and IP address.\n2. The number of failed attempts from an IP address over some long period of time. For example, block an IP address if it makes 100 failed attempts in one day.\n\n[rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) package provides tools to make this technique easy and fast. You can find [an example of brute-force protection in the documentation](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection)\n\nEnsure your dependencies are secure\n-----------------------------------\n\nUsing npm to manage your application’s dependencies is powerful and convenient. But the packages that you use may contain critical security vulnerabilities that could also affect your application. The security of your app is only as strong as the “weakest link” in your dependencies.\n\nSince npm@6, npm automatically reviews every install request. Also, you can use `npm audit` to analyze your dependency tree.\n\n```\n$ npm audit\n```\n\nIf you want to stay more secure, consider [Snyk](https://snyk.io/).\n\nSnyk offers both a [command-line tool](https://www.npmjs.com/package/snyk) and a [Github integration](https://snyk.io/docs/github) that checks your application against [Snyk’s open source vulnerability database](https://snyk.io/vuln/) for any known vulnerabilities in your dependencies. Install the CLI as follows:\n\n```\n$ npm install -g snyk\n$ cd your-app\n```\n\nUse this command to test your application for vulnerabilities:\n\n```\n$ snyk test\n```\n\n### Avoid other known vulnerabilities\n\nKeep an eye out for [Node Security Project](https://npmjs.com/advisories) or [Snyk](https://snyk.io/vuln/) advisories that may affect Express or other modules that your app uses. In general, these databases are excellent resources for knowledge and tools about Node security.\n\nFinally, Express apps—like any other web apps—can be vulnerable to a variety of web-based attacks. Familiarize yourself with known [web vulnerabilities](https://www.owasp.org/www-project-top-ten/) and take precautions to avoid them.\n\nAdditional considerations\n-------------------------\n\nHere are some further recommendations from the excellent [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Refer to that blog post for all the details on these recommendations:\n\n* Always filter and sanitize user input to protect against cross-site scripting (XSS) and command injection attacks.\n* Defend against SQL injection attacks by using parameterized queries or prepared statements.\n* Use the open-source [sqlmap](http://sqlmap.org/) tool to detect SQL injection vulnerabilities in your app.\n* Use the [nmap](https://nmap.org/) and [sslyze](https://github.com/nabla-c0d3/sslyze) tools to test the configuration of your SSL ciphers, keys, and renegotiation as well as the validity of your certificate.\n* Use [safe-regex](https://www.npmjs.com/package/safe-regex) to ensure your regular expressions are not susceptible to [regular expression denial of service](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) attacks.\n", "filename": "best-practice-security.md", "package": "express" }
{ "content": "Title: Express database integration\n\nURL Source: https://expressjs.com/en/guide/database-integration.html\n\nMarkdown Content:\nAdding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app:\n\n* [Cassandra](https://expressjs.com/en/guide/database-integration.html#cassandra)\n* [Couchbase](https://expressjs.com/en/guide/database-integration.html#couchbase)\n* [CouchDB](https://expressjs.com/en/guide/database-integration.html#couchdb)\n* [LevelDB](https://expressjs.com/en/guide/database-integration.html#leveldb)\n* [MySQL](https://expressjs.com/en/guide/database-integration.html#mysql)\n* [MongoDB](https://expressjs.com/en/guide/database-integration.html#mongodb)\n* [Neo4j](https://expressjs.com/en/guide/database-integration.html#neo4j)\n* [Oracle](https://expressjs.com/en/guide/database-integration.html#oracle)\n* [PostgreSQL](https://expressjs.com/en/guide/database-integration.html#postgresql)\n* [Redis](https://expressjs.com/en/guide/database-integration.html#redis)\n* [SQL Server](https://expressjs.com/en/guide/database-integration.html#sql-server)\n* [SQLite](https://expressjs.com/en/guide/database-integration.html#sqlite)\n* [Elasticsearch](https://expressjs.com/en/guide/database-integration.html#elasticsearch)\n\nThese database drivers are among many that are available. For other options, search on the [npm](https://www.npmjs.com/) site.\n\nCassandra\n---------\n\n**Module**: [cassandra-driver](https://github.com/datastax/nodejs-driver)\n\n### Installation\n\n```\n$ npm install cassandra-driver\n```\n\n### Example\n\n```\nconst cassandra = require('cassandra-driver')\nconst client = new cassandra.Client({ contactPoints: ['localhost'] })\n\nclient.execute('select key from system.local', (err, result) => {\n if (err) throw err\n console.log(result.rows[0])\n})\n```\n\nCouchbase\n---------\n\n**Module**: [couchnode](https://github.com/couchbase/couchnode)\n\n### Installation\n\n```\n$ npm install couchbase\n```\n\n### Example\n\n```\nconst couchbase = require('couchbase')\nconst bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName')\n\n// add a document to a bucket\nbucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => {\n if (err) {\n console.log(err)\n } else {\n console.log(result)\n }\n})\n\n// get all documents with shoe size 13\nconst n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1'\nconst query = N1qlQuery.fromString(n1ql)\nbucket.query(query, [13], (err, result) => {\n if (err) {\n console.log(err)\n } else {\n console.log(result)\n }\n})\n```\n\nCouchDB\n-------\n\n**Module**: [nano](https://github.com/dscape/nano)\n\n### Installation\n\n```\n$ npm install nano\n```\n\n### Example\n\n```\nconst nano = require('nano')('http://localhost:5984')\nnano.db.create('books')\nconst books = nano.db.use('books')\n\n// Insert a book document in the books database\nbooks.insert({ name: 'The Art of war' }, null, (err, body) => {\n if (err) {\n console.log(err)\n } else {\n console.log(body)\n }\n})\n\n// Get a list of all books\nbooks.list((err, body) => {\n if (err) {\n console.log(err)\n } else {\n console.log(body.rows)\n }\n})\n```\n\nLevelDB\n-------\n\n**Module**: [levelup](https://github.com/rvagg/node-levelup)\n\n### Installation\n\n```\n$ npm install level levelup leveldown\n```\n\n### Example\n\n```\nconst levelup = require('levelup')\nconst db = levelup('./mydb')\n\ndb.put('name', 'LevelUP', (err) => {\n if (err) return console.log('Ooops!', err)\n\n db.get('name', (err, value) => {\n if (err) return console.log('Ooops!', err)\n\n console.log(`name=${value}`)\n })\n})\n```\n\nMySQL\n-----\n\n**Module**: [mysql](https://github.com/felixge/node-mysql/)\n\n### Installation\n\n```\n$ npm install mysql\n```\n\n### Example\n\n```\nconst mysql = require('mysql')\nconst connection = mysql.createConnection({\n host: 'localhost',\n user: 'dbuser',\n password: 's3kreee7',\n database: 'my_db'\n})\n\nconnection.connect()\n\nconnection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {\n if (err) throw err\n\n console.log('The solution is: ', rows[0].solution)\n})\n\nconnection.end()\n```\n\nMongoDB\n-------\n\n**Module**: [mongodb](https://github.com/mongodb/node-mongodb-native)\n\n### Installation\n\n```\n$ npm install mongodb\n```\n\n### Example (v2.\\*)\n\n```\nconst MongoClient = require('mongodb').MongoClient\n\nMongoClient.connect('mongodb://localhost:27017/animals', (err, db) => {\n if (err) throw err\n\n db.collection('mammals').find().toArray((err, result) => {\n if (err) throw err\n\n console.log(result)\n })\n})\n```\n\n### Example (v3.\\*)\n\n```\nconst MongoClient = require('mongodb').MongoClient\n\nMongoClient.connect('mongodb://localhost:27017/animals', (err, client) => {\n if (err) throw err\n\n const db = client.db('animals')\n\n db.collection('mammals').find().toArray((err, result) => {\n if (err) throw err\n\n console.log(result)\n })\n})\n```\n\nIf you want an object model driver for MongoDB, look at [Mongoose](https://github.com/LearnBoost/mongoose).\n\nNeo4j\n-----\n\n**Module**: [neo4j-driver](https://github.com/neo4j/neo4j-javascript-driver)\n\n### Installation\n\n```\n$ npm install neo4j-driver\n```\n\n### Example\n\n```\nconst neo4j = require('neo4j-driver')\nconst driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein'))\n\nconst session = driver.session()\n\nsession.readTransaction((tx) => {\n return tx.run('MATCH (n) RETURN count(n) AS count')\n .then((res) => {\n console.log(res.records[0].get('count'))\n })\n .catch((error) => {\n console.log(error)\n })\n})\n```\n\nOracle\n------\n\n**Module**: [oracledb](https://github.com/oracle/node-oracledb)\n\n### Installation\n\nNOTE: [See installation prerequisites](https://github.com/oracle/node-oracledb#-installation).\n\n```\n$ npm install oracledb\n```\n\n### Example\n\n```\nconst oracledb = require('oracledb')\nconst config = {\n user: '<your db user>',\n password: '<your db password>',\n connectString: 'localhost:1521/orcl'\n}\n\nasync function getEmployee (empId) {\n let conn\n\n try {\n conn = await oracledb.getConnection(config)\n\n const result = await conn.execute(\n 'select * from employees where employee_id = :id',\n [empId]\n )\n\n console.log(result.rows[0])\n } catch (err) {\n console.log('Ouch!', err)\n } finally {\n if (conn) { // conn assignment worked, need to close\n await conn.close()\n }\n }\n}\n\ngetEmployee(101)\n```\n\nPostgreSQL\n----------\n\n**Module**: [pg-promise](https://github.com/vitaly-t/pg-promise)\n\n### Installation\n\n```\n$ npm install pg-promise\n```\n\n### Example\n\n```\nconst pgp = require('pg-promise')(/* options */)\nconst db = pgp('postgres://username:password@host:port/database')\n\ndb.one('SELECT $1 AS value', 123)\n .then((data) => {\n console.log('DATA:', data.value)\n })\n .catch((error) => {\n console.log('ERROR:', error)\n })\n```\n\nRedis\n-----\n\n**Module**: [redis](https://github.com/mranney/node_redis)\n\n### Installation\n\n```\n$ npm install redis\n```\n\n### Example\n\n```\nconst redis = require('redis')\nconst client = redis.createClient()\n\nclient.on('error', (err) => {\n console.log(`Error ${err}`)\n})\n\nclient.set('string key', 'string val', redis.print)\nclient.hset('hash key', 'hashtest 1', 'some value', redis.print)\nclient.hset(['hash key', 'hashtest 2', 'some other value'], redis.print)\n\nclient.hkeys('hash key', (err, replies) => {\n console.log(`${replies.length} replies:`)\n\n replies.forEach((reply, i) => {\n console.log(` ${i}: ${reply}`)\n })\n\n client.quit()\n})\n```\n\nSQL Server\n----------\n\n**Module**: [tedious](https://github.com/tediousjs/tedious)\n\n### Installation\n\n```\n$ npm install tedious\n```\n\n### Example\n\n```\nconst Connection = require('tedious').Connection\nconst Request = require('tedious').Request\n\nconst config = {\n server: 'localhost',\n authentication: {\n type: 'default',\n options: {\n userName: 'your_username', // update me\n password: 'your_password' // update me\n }\n }\n}\n\nconst connection = new Connection(config)\n\nconnection.on('connect', (err) => {\n if (err) {\n console.log(err)\n } else {\n executeStatement()\n }\n})\n\nfunction executeStatement () {\n request = new Request(\"select 123, 'hello world'\", (err, rowCount) => {\n if (err) {\n console.log(err)\n } else {\n console.log(`${rowCount} rows`)\n }\n connection.close()\n })\n\n request.on('row', (columns) => {\n columns.forEach((column) => {\n if (column.value === null) {\n console.log('NULL')\n } else {\n console.log(column.value)\n }\n })\n })\n\n connection.execSql(request)\n}\n```\n\nSQLite\n------\n\n**Module**: [sqlite3](https://github.com/mapbox/node-sqlite3)\n\n### Installation\n\n```\n$ npm install sqlite3\n```\n\n### Example\n\n```\nconst sqlite3 = require('sqlite3').verbose()\nconst db = new sqlite3.Database(':memory:')\n\ndb.serialize(() => {\n db.run('CREATE TABLE lorem (info TEXT)')\n const stmt = db.prepare('INSERT INTO lorem VALUES (?)')\n\n for (let i = 0; i < 10; i++) {\n stmt.run(`Ipsum ${i}`)\n }\n\n stmt.finalize()\n\n db.each('SELECT rowid AS id, info FROM lorem', (err, row) => {\n console.log(`${row.id}: ${row.info}`)\n })\n})\n\ndb.close()\n```\n\nElasticsearch\n-------------\n\n**Module**: [elasticsearch](https://github.com/elastic/elasticsearch-js)\n\n### Installation\n\n```\n$ npm install elasticsearch\n```\n\n### Example\n\n```\nconst elasticsearch = require('elasticsearch')\nconst client = elasticsearch.Client({\n host: 'localhost:9200'\n})\n\nclient.search({\n index: 'books',\n type: 'book',\n body: {\n query: {\n multi_match: {\n query: 'express js',\n fields: ['title', 'description']\n }\n }\n }\n}).then((response) => {\n const hits = response.hits.hits\n}, (error) => {\n console.trace(error.message)\n})\n```\n", "filename": "database-integration.md", "package": "express" }
{ "content": "Title: Debugging Express\n\nURL Source: https://expressjs.com/en/guide/debugging.html\n\nMarkdown Content:\nTo see all the internal logs used in Express, set the `DEBUG` environment variable to `express:*` when launching your app.\n\n```\n$ DEBUG=express:* node index.js\n```\n\nOn Windows, use the corresponding command.\n\n```\n> set DEBUG=express:* & node index.js\n```\n\nRunning this command on the default app generated by the [express generator](https://expressjs.com/en/starter/generator.html) prints the following output:\n\n```\n$ DEBUG=express:* node ./bin/www\n express:router:route new / +0ms\n express:router:layer new / +1ms\n express:router:route get / +1ms\n express:router:layer new / +0ms\n express:router:route new / +1ms\n express:router:layer new / +0ms\n express:router:route get / +0ms\n express:router:layer new / +0ms\n express:application compile etag weak +1ms\n express:application compile query parser extended +0ms\n express:application compile trust proxy false +0ms\n express:application booting in development mode +1ms\n express:router use / query +0ms\n express:router:layer new / +0ms\n express:router use / expressInit +0ms\n express:router:layer new / +0ms\n express:router use / favicon +1ms\n express:router:layer new / +0ms\n express:router use / logger +0ms\n express:router:layer new / +0ms\n express:router use / jsonParser +0ms\n express:router:layer new / +1ms\n express:router use / urlencodedParser +0ms\n express:router:layer new / +0ms\n express:router use / cookieParser +0ms\n express:router:layer new / +0ms\n express:router use / stylus +90ms\n express:router:layer new / +0ms\n express:router use / serveStatic +0ms\n express:router:layer new / +0ms\n express:router use / router +0ms\n express:router:layer new / +1ms\n express:router use /users router +0ms\n express:router:layer new /users +0ms\n express:router use / &lt;anonymous&gt; +0ms\n express:router:layer new / +0ms\n express:router use / &lt;anonymous&gt; +0ms\n express:router:layer new / +0ms\n express:router use / &lt;anonymous&gt; +0ms\n express:router:layer new / +0ms\n```\n\nWhen a request is then made to the app, you will see the logs specified in the Express code:\n\n```\n express:router dispatching GET / +4h\n express:router query : / +2ms\n express:router expressInit : / +0ms\n express:router favicon : / +0ms\n express:router logger : / +1ms\n express:router jsonParser : / +0ms\n express:router urlencodedParser : / +1ms\n express:router cookieParser : / +0ms\n express:router stylus : / +0ms\n express:router serveStatic : / +2ms\n express:router router : / +2ms\n express:router dispatching GET / +1ms\n express:view lookup \"index.pug\" +338ms\n express:view stat \"/projects/example/views/index.pug\" +0ms\n express:view render \"/projects/example/views/index.pug\" +1ms\n```\n\nTo see the logs only from the router implementation, set the value of `DEBUG` to `express:router`. Likewise, to see logs only from the application implementation, set the value of `DEBUG` to `express:application`, and so on.\n\nApplications generated by `express`\n-----------------------------------\n\nAn application generated by the `express` command uses the `debug` module and its debug namespace is scoped to the name of the application.\n\nFor example, if you generated the app with `$ express sample-app`, you can enable the debug statements with the following command:\n\n```\n$ DEBUG=sample-app:* node ./bin/www\n```\n\nYou can specify more than one debug namespace by assigning a comma-separated list of names:\n\n```\n$ DEBUG=http,mail,express:* node index.js\n```\n\nAdvanced options\n----------------\n\nWhen running through Node.js, you can set a few environment variables that will change the behavior of the debug logging:\n\n| Name | Purpose |\n| --- | --- |\n| `DEBUG` | Enables/disables specific debugging namespaces. |\n| `DEBUG_COLORS` | Whether or not to use colors in the debug output. |\n| `DEBUG_DEPTH` | Object inspection depth. |\n| `DEBUG_FD` | File descriptor to write debug output to. |\n| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |\n\n**Note:** The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list.\n", "filename": "debugging.md", "package": "express" }
{ "content": "Title: Developing template engines for Express\n\nURL Source: https://expressjs.com/en/advanced/developing-template-engines.html\n\nMarkdown Content:\nDeveloping template engines for Express\n=======================================\n\nUse the `app.engine(ext, callback)` method to create your own template engine. `ext` refers to the file extension, and `callback` is the template engine function, which accepts the following items as parameters: the location of the file, the options object, and the callback function.\n\nThe following code is an example of implementing a very simple template engine for rendering `.ntl` files.\n\n```javascript\nconst fs = require('fs') // this engine requires the fs module\napp.engine('ntl', (filePath, options, callback) => { // define the template engine\n fs.readFile(filePath, (err, content) => {\n if (err) return callback(err)\n // this is an extremely simple template engine\n const rendered = content.toString()\n .replace('#title#', `<title>${options.title}</title>`)\n .replace('#message#', `<h1>${options.message}</h1>`)\n return callback(null, rendered)\n })\n})\napp.set('views', './views') // specify the views directory\napp.set('view engine', 'ntl') // register the template engine\n```\n\nYour app will now be able to render `.ntl` files. Create a file named `index.ntl` in the `views` directory with the following content.\n\n```text\n#title#\n#message#\n```\n\nThen, create the following route in your app.\n\n```javascript\napp.get('/', (req, res) => {\n res.render('index', { title: 'Hey', message: 'Hello there!' })\n})\n```\n\nWhen you make a request to the home page, `index.ntl` will be rendered as HTML.\n\n[![Image 1](https://expressjs.com/images/arrow.png)](https://expressjs.com/en/advanced/developing-template-engines.html#)\n\nDocumentation translations provided by StrongLoop/IBM: [French](https://expressjs.com/fr/), [German](https://expressjs.com/de/), [Spanish](https://expressjs.com/es/), [Italian](https://expressjs.com/it/), [Japanese](https://expressjs.com/ja/), [Russian](https://expressjs.com/ru/), [Chinese](https://expressjs.com/zh-cn/), [Traditional Chinese](https://expressjs.com/zh-tw/), [Korean](https://expressjs.com/ko/), [Portuguese](https://expressjs.com/pt-br/). \nCommunity translation available for: [Slovak](https://expressjs.com/sk/), [Ukrainian](https://expressjs.com/uk/), [Uzbek](https://expressjs.com/uz/), [Turkish](https://expressjs.com/tr/), [Thai](https://expressjs.com/th/) and [Indonesian](https://expressjs.com/id/).\n\n[![Image 2: Preview Deploys by Netlify](https://www.netlify.com/v3/img/components/netlify-color-accent.svg)](https://www.netlify.com/)\n\n[Express](https://expressjs.com/) is a project of the [OpenJS Foundation](https://openjsf.org/).\n\n[Edit this page on GitHub](https://github.com/expressjs/expressjs.com/blob/gh-pages/en/advanced/developing-template-engines.md).\n\nCopyright © 2017 StrongLoop, IBM, and other expressjs.com contributors.\n\n[![Image 3: Creative Commons License](https://i.creativecommons.org/l/by-sa/3.0/us/80x15.png)](http://creativecommons.org/licenses/by-sa/3.0/us/) This work is licensed under a [Creative Commons Attribution-ShareAlike 3.0 United States License](http://creativecommons.org/licenses/by-sa/3.0/us/).\n", "filename": "developing-template-engines.md", "package": "express" }
{ "content": "Title: Express error handling\n\nURL Source: https://expressjs.com/en/guide/error-handling.html\n\nMarkdown Content:\n_Error Handling_ refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don’t need to write your own to get started.\n\nCatching Errors\n---------------\n\nIt’s important to ensure that Express catches all errors that occur while running route handlers and middleware.\n\nErrors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it. For example:\n\n```\napp.get('/', (req, res) => {\n throw new Error('BROKEN') // Express will catch this on its own.\n})\n```\n\nFor errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the `next()` function, where Express will catch and process them. For example:\n\n```\napp.get('/', (req, res, next) => {\n fs.readFile('/file-does-not-exist', (err, data) => {\n if (err) {\n next(err) // Pass errors to Express.\n } else {\n res.send(data)\n }\n })\n})\n```\n\nStarting with Express 5, route handlers and middleware that return a Promise will call `next(value)` automatically when they reject or throw an error. For example:\n\n```\napp.get('/user/:id', async (req, res, next) => {\n const user = await getUserById(req.params.id)\n res.send(user)\n})\n```\n\nIf `getUserById` throws an error or rejects, `next` will be called with either the thrown error or the rejected value. If no rejected value is provided, `next` will be called with a default Error object provided by the Express router.\n\nIf you pass anything to the `next()` function (except the string `'route'`), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.\n\nIf the callback in a sequence provides no data, only errors, you can simplify this code as follows:\n\n```\napp.get('/', [\n function (req, res, next) {\n fs.writeFile('/inaccessible-path', 'data', next)\n },\n function (req, res) {\n res.send('OK')\n }\n])\n```\n\nIn the above example, `next` is provided as the callback for `fs.writeFile`, which is called with or without errors. If there is no error, the second handler is executed, otherwise Express catches and processes the error.\n\nYou must catch errors that occur in asynchronous code invoked by route handlers or middleware and pass them to Express for processing. For example:\n\n```\napp.get('/', (req, res, next) => {\n setTimeout(() => {\n try {\n throw new Error('BROKEN')\n } catch (err) {\n next(err)\n }\n }, 100)\n})\n```\n\nThe above example uses a `try...catch` block to catch errors in the asynchronous code and pass them to Express. If the `try...catch` block were omitted, Express would not catch the error since it is not part of the synchronous handler code.\n\nUse promises to avoid the overhead of the `try...catch` block or when using functions that return promises. For example:\n\n```\napp.get('/', (req, res, next) => {\n Promise.resolve().then(() => {\n throw new Error('BROKEN')\n }).catch(next) // Errors will be passed to Express.\n})\n```\n\nSince promises automatically catch both synchronous errors and rejected promises, you can simply provide `next` as the final catch handler and Express will catch errors, because the catch handler is given the error as the first argument.\n\nYou could also use a chain of handlers to rely on synchronous error catching, by reducing the asynchronous code to something trivial. For example:\n\n```\napp.get('/', [\n function (req, res, next) {\n fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => {\n res.locals.data = data\n next(err)\n })\n },\n function (req, res) {\n res.locals.data = res.locals.data.split(',')[1]\n res.send(res.locals.data)\n }\n])\n```\n\nThe above example has a couple of trivial statements from the `readFile` call. If `readFile` causes an error, then it passes the error to Express, otherwise you quickly return to the world of synchronous error handling in the next handler in the chain. Then, the example above tries to process the data. If this fails, then the synchronous error handler will catch it. If you had done this processing inside the `readFile` callback, then the application might exit and the Express error handlers would not run.\n\nWhichever method you use, if you want Express error handlers to be called in and the application to survive, you must ensure that Express receives the error.\n\nThe default error handler\n-------------------------\n\nExpress comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack.\n\nIf you pass an error to `next()` and you do not handle it in a custom error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment.\n\nSet the environment variable `NODE_ENV` to `production`, to run the app in production mode.\n\nWhen an error is written, the following information is added to the response:\n\n* The `res.statusCode` is set from `err.status` (or `err.statusCode`). If this value is outside the 4xx or 5xx range, it will be set to 500.\n* The `res.statusMessage` is set according to the status code.\n* The body will be the HTML of the status code message when in production environment, otherwise will be `err.stack`.\n* Any headers specified in an `err.headers` object.\n\nIf you call `next()` with an error after you have started writing the response (for example, if you encounter an error while streaming the response to the client), the Express default error handler closes the connection and fails the request.\n\nSo when you add a custom error handler, you must delegate to the default Express error handler, when the headers have already been sent to the client:\n\n```\nfunction errorHandler (err, req, res, next) {\n if (res.headersSent) {\n return next(err)\n }\n res.status(500)\n res.render('error', { error: err })\n}\n```\n\nNote that the default error handler can get triggered if you call `next()` with an error in your code more than once, even if custom error handling middleware is in place.\n\nOther error handling middleware can be found at [Express middleware](https://expressjs.com/en/resources/middleware.html).\n\nWriting error handlers\n----------------------\n\nDefine error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: `(err, req, res, next)`. For example:\n\n```\napp.use((err, req, res, next) => {\n console.error(err.stack)\n res.status(500).send('Something broke!')\n})\n```\n\nYou define error-handling middleware last, after other `app.use()` and routes calls; for example:\n\n```\nconst bodyParser = require('body-parser')\nconst methodOverride = require('method-override')\n\napp.use(bodyParser.urlencoded({\n extended: true\n}))\napp.use(bodyParser.json())\napp.use(methodOverride())\napp.use((err, req, res, next) => {\n // logic\n})\n```\n\nResponses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string.\n\nFor organizational (and higher-level framework) purposes, you can define several error-handling middleware functions, much as you would with regular middleware functions. For example, to define an error-handler for requests made by using `XHR` and those without:\n\n```\nconst bodyParser = require('body-parser')\nconst methodOverride = require('method-override')\n\napp.use(bodyParser.urlencoded({\n extended: true\n}))\napp.use(bodyParser.json())\napp.use(methodOverride())\napp.use(logErrors)\napp.use(clientErrorHandler)\napp.use(errorHandler)\n```\n\nIn this example, the generic `logErrors` might write request and error information to `stderr`, for example:\n\n```\nfunction logErrors (err, req, res, next) {\n console.error(err.stack)\n next(err)\n}\n```\n\nAlso in this example, `clientErrorHandler` is defined as follows; in this case, the error is explicitly passed along to the next one.\n\nNotice that when _not_ calling “next” in an error-handling function, you are responsible for writing (and ending) the response. Otherwise, those requests will “hang” and will not be eligible for garbage collection.\n\n```\nfunction clientErrorHandler (err, req, res, next) {\n if (req.xhr) {\n res.status(500).send({ error: 'Something failed!' })\n } else {\n next(err)\n }\n}\n```\n\nImplement the “catch-all” `errorHandler` function as follows (for example):\n\n```\nfunction errorHandler (err, req, res, next) {\n res.status(500)\n res.render('error', { error: err })\n}\n```\n\nIf you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. For example:\n\n```\napp.get('/a_route_behind_paywall',\n (req, res, next) => {\n if (!req.user.hasPaid) {\n // continue handling this request\n next('route')\n } else {\n next()\n }\n }, (req, res, next) => {\n PaidContent.find((err, doc) => {\n if (err) return next(err)\n res.json(doc)\n })\n })\n```\n\nIn this example, the `getPaidContent` handler will be skipped but any remaining handlers in `app` for `/a_route_behind_paywall` would continue to be executed.\n\nCalls to `next()` and `next(err)` indicate that the current handler is complete and in what state. `next(err)` will skip all remaining handlers in the chain except for those that are set up to handle errors as described above.\n", "filename": "error-handling.md", "package": "express" }
{ "content": "Title: Express FAQ\n\nURL Source: https://expressjs.com/en/starter/faq.html\n\nMarkdown Content:\nHow should I structure my application?\n--------------------------------------\n\nThere is no definitive answer to this question. The answer depends on the scale of your application and the team that is involved. To be as flexible as possible, Express makes no assumptions in terms of structure.\n\nRoutes and other application-specific logic can live in as many files as you wish, in any directory structure you prefer. View the following examples for inspiration:\n\n* [Route listings](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-L47)\n* [Route map](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66)\n* [MVC style controllers](https://github.com/expressjs/express/tree/master/examples/mvc)\n\nAlso, there are third-party extensions for Express, which simplify some of these patterns:\n\n* [Resourceful routing](https://github.com/expressjs/express-resource)\n\nHow do I define models?\n-----------------------\n\nExpress has no notion of a database. This concept is left up to third-party Node modules, allowing you to interface with nearly any database.\n\nSee [LoopBack](http://loopback.io/) for an Express-based framework that is centered around models.\n\nHow can I authenticate users?\n-----------------------------\n\nAuthentication is another opinionated area that Express does not venture into. You may use any authentication scheme you wish. For a simple username / password scheme, see [this example](https://github.com/expressjs/express/tree/master/examples/auth).\n\nWhich template engines does Express support?\n--------------------------------------------\n\nExpress supports any template engine that conforms with the `(path, locals, callback)` signature. To normalize template engine interfaces and caching, see the [consolidate.js](https://github.com/visionmedia/consolidate.js) project for support. Unlisted template engines might still support the Express signature.\n\nFor more information, see [Using template engines with Express](https://expressjs.com/en/guide/using-template-engines.html).\n\nHow do I handle 404 responses?\n------------------------------\n\nIn Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:\n\n```\napp.use((req, res, next) => {\n res.status(404).send(\"Sorry can't find that!\")\n})\n```\n\nAdd routes dynamically at runtime on an instance of `express.Router()` so the routes are not superseded by a middleware function.\n\nHow do I setup an error handler?\n--------------------------------\n\nYou define error-handling middleware in the same way as other middleware, except with four arguments instead of three; specifically with the signature `(err, req, res, next)`:\n\n```\napp.use((err, req, res, next) => {\n console.error(err.stack)\n res.status(500).send('Something broke!')\n})\n```\n\nFor more information, see [Error handling](https://expressjs.com/en/guide/error-handling.html).\n\nHow do I render plain HTML?\n---------------------------\n\nYou don’t! There’s no need to “render” HTML with the `res.render()` function. If you have a specific file, use the `res.sendFile()` function. If you are serving many assets from a directory, use the `express.static()` middleware function.\n\nWhat version of Node.js does Express require?\n---------------------------------------------\n\n* [Express 4.x](https://expressjs.com/en/4x/api.html) requires Node.js 0.10 or higher.\n* [Express 5.x](https://expressjs.com/en/5x/api.html) requires Node.js 18 or higher.\n\n### [Previous: More examples](https://expressjs.com/en/starter/examples.html)\n", "filename": "faq.md", "package": "express" }
{ "content": "Title: Express application generator\n\nURL Source: https://expressjs.com/en/starter/generator.html\n\nMarkdown Content:\nUse the application generator tool, `express-generator`, to quickly create an application skeleton.\n\nYou can run the application generator with the `npx` command (available in Node.js 8.2.0).\n\n```\n$ npx express-generator\n```\n\nFor earlier Node versions, install the application generator as a global npm package and then launch it:\n\n```\n$ npm install -g express-generator\n$ express\n```\n\nDisplay the command options with the `-h` option:\n\n```\n$ express -h\n\n Usage: express [options] [dir]\n\n Options:\n\n -h, --help output usage information\n --version output the version number\n -e, --ejs add ejs engine support\n --hbs add handlebars engine support\n --pug add pug engine support\n -H, --hogan add hogan.js engine support\n --no-view generate without view engine\n -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)\n -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)\n --git add .gitignore\n -f, --force force on non-empty directory\n```\n\nFor example, the following creates an Express app named _myapp_. The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to [Pug](https://pugjs.org/ \"Pug documentation\"):\n\n```\n$ express --view=pug myapp\n\n create : myapp\n create : myapp/package.json\n create : myapp/app.js\n create : myapp/public\n create : myapp/public/javascripts\n create : myapp/public/images\n create : myapp/routes\n create : myapp/routes/index.js\n create : myapp/routes/users.js\n create : myapp/public/stylesheets\n create : myapp/public/stylesheets/style.css\n create : myapp/views\n create : myapp/views/index.pug\n create : myapp/views/layout.pug\n create : myapp/views/error.pug\n create : myapp/bin\n create : myapp/bin/www\n```\n\nThen install dependencies:\n\n```\n$ cd myapp\n$ npm install\n```\n\nOn MacOS or Linux, run the app with this command:\n\n```\n$ DEBUG=myapp:* npm start\n```\n\nOn Windows Command Prompt, use this command:\n\n```\n> set DEBUG=myapp:* & npm start\n```\n\nOn Windows PowerShell, use this command:\n\n```\nPS> $env:DEBUG='myapp:*'; npm start\n```\n\nThen, load `http://localhost:3000/` in your browser to access the app.\n\nThe generated app has the following directory structure:\n\n```\n.\n├── app.js\n├── bin\n│ └── www\n├── package.json\n├── public\n│ ├── images\n│ ├── javascripts\n│ └── stylesheets\n│ └── style.css\n├── routes\n│ ├── index.js\n│ └── users.js\n└── views\n ├── error.pug\n ├── index.pug\n └── layout.pug\n\n7 directories, 9 files\n```\n\nThe app structure created by the generator is just one of many ways to structure Express apps. Feel free to use this structure or modify it to best suit your needs.\n\n### [Previous: Hello World](https://expressjs.com/en/starter/hello-world.html)     [Next: Basic routing](https://expressjs.com/en/starter/basic-routing.html)\n", "filename": "generator.md", "package": "express" }
{ "content": "Title: Express glossary\n\nURL Source: https://expressjs.com/en/resources/glossary.html\n\nMarkdown Content:\n### application\n\nIn general, one or more programs that are designed to carry out operations for a specific purpose. In the context of Express, a program that uses the Express API running on the Node.js platform. Might also refer to an [app object](https://expressjs.com/en/api.html#express).\n\n### API\n\nApplication programming interface. Spell out the abbreviation when it is first used.\n\n### Express\n\nA fast, un-opinionated, minimalist web framework for Node.js applications. In general, “Express” is preferred to “Express.js,” though the latter is acceptable.\n\n### libuv\n\nA multi-platform support library which focuses on asynchronous I/O, primarily developed for use by Node.js.\n\n### middleware\n\nA function that is invoked by the Express routing layer before the final request handler, and thus sits in the middle between a raw request and the final intended route. A few fine points of terminology around middleware:\n\n* `var foo = require('middleware')` is called _requiring_ or _using_ a Node.js module. Then the statement `var mw = foo()` typically returns the middleware.\n* `app.use(mw)` is called _adding the middleware to the global processing stack_.\n* `app.get('/foo', mw, function (req, res) { ... })` is called _adding the middleware to the “GET /foo” processing stack_.\n\n### Node.js\n\nA software platform that is used to build scalable network applications. Node.js uses JavaScript as its scripting language, and achieves high throughput via non-blocking I/O and a single-threaded event loop. See [nodejs.org](https://nodejs.org/en/). **Usage note**: Initially, “Node.js,” thereafter “Node”.\n\n### open-source, open source\n\nWhen used as an adjective, hyphenate; for example: “This is open-source software.” See [Open-source software on Wikipedia](http://en.wikipedia.org/wiki/Open-source_software). Note: Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective.\n\n### request\n\nAn HTTP request. A client submits an HTTP request message to a server, which returns a response. The request must use one of several [request methods](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) such as GET, POST, and so on.\n\n### response\n\nAn HTTP response. A server returns an HTTP response message to the client. The response contains completion status information about the request and might also contain requested content in its message body.\n\n### route\n\nPart of a URL that identifies a resource. For example, in `http://foo.com/products/id`, “/products/id” is the route.\n\n### router\n\nSee [router](https://expressjs.com/en/api.html#router) in the API reference.\n", "filename": "glossary.md", "package": "express" }
{ "content": "Title: Health Checks and Graceful Shutdown\n\nURL Source: https://expressjs.com/en/advanced/healthcheck-graceful-shutdown.html\n\nMarkdown Content:\nHealth Checks and Graceful Shutdown\n===============\n \n\n[Express](https://expressjs.com/)\n\n* [Home](https://expressjs.com/)\n* * [Getting started](https://expressjs.com/en/starter/installing.html)\n * [Installing](https://expressjs.com/en/starter/installing.html)\n * [Hello world](https://expressjs.com/en/starter/hello-world.html)\n * [Express generator](https://expressjs.com/en/starter/generator.html)\n * [Basic routing](https://expressjs.com/en/starter/basic-routing.html)\n * [Static files](https://expressjs.com/en/starter/static-files.html)\n * [More examples](https://expressjs.com/en/starter/examples.html)\n * [FAQ](https://expressjs.com/en/starter/faq.html)\n* * [Guide](https://expressjs.com/en/guide/routing.html)\n * [Routing](https://expressjs.com/en/guide/routing.html)\n * [Writing middleware](https://expressjs.com/en/guide/writing-middleware.html)\n * [Using middleware](https://expressjs.com/en/guide/using-middleware.html)\n * [Overriding the Express API](https://expressjs.com/en/guide/overriding-express-api.html)\n * [Using template engines](https://expressjs.com/en/guide/using-template-engines.html)\n * [Error handling](https://expressjs.com/en/guide/error-handling.html)\n * [Debugging](https://expressjs.com/en/guide/debugging.html)\n * [Express behind proxies](https://expressjs.com/en/guide/behind-proxies.html)\n * [Moving to Express 4](https://expressjs.com/en/guide/migrating-4.html)\n * [Moving to Express 5](https://expressjs.com/en/guide/migrating-5.html)\n * [Database integration](https://expressjs.com/en/guide/database-integration.html)\n* * [API reference](https://expressjs.com/en/4x/api.html)\n * [5.x (beta)](https://expressjs.com/en/5x/api.html)\n * [4.x](https://expressjs.com/en/4x/api.html)\n * [3.x (deprecated)](https://expressjs.com/en/3x/api.html)\n * [2.x (deprecated)](https://expressjs.com/2x/)\n* * [Advanced topics](https://expressjs.com/en/advanced/developing-template-engines.html)\n * [Building template engines](https://expressjs.com/en/advanced/developing-template-engines.html)\n * [Security updates](https://expressjs.com/en/advanced/security-updates.html)\n * [Security best practices](https://expressjs.com/en/advanced/best-practice-security.html)\n * [Performance best practices](https://expressjs.com/en/advanced/best-practice-performance.html)\n * [Health checks & shutdown](https://expressjs.com/en/advanced/healthcheck-graceful-shutdown.html)\n* * [Resources](https://expressjs.com/en/resources/glossary.html)\n * [Community](https://expressjs.com/en/resources/community.html)\n * [Glossary](https://expressjs.com/en/resources/glossary.html)\n * [Middleware](https://expressjs.com/en/resources/middleware.html)\n * [Utility modules](https://expressjs.com/en/resources/utils.html)\n * [Contributing to Express](https://expressjs.com/en/resources/contributing.html)\n * [Release Change Log](https://expressjs.com/en/changelog/4x.html)\n\nHealth Checks and Graceful Shutdown\n===================================\n\nGraceful shutdown\n-----------------\n\nWhen you deploy a new version of your application, you must replace the previous version. The process manager you’re using will first send a SIGTERM signal to the application to notify it that it will be killed. Once the application gets this signal, it should stop accepting new requests, finish all the ongoing requests, clean up the resources it used, including database connections and file locks then exit.\n\n### Example\n\n```javascript\nconst server = app.listen(port)\n\nprocess.on('SIGTERM', () => {\n debug('SIGTERM signal received: closing HTTP server')\n server.close(() => {\n debug('HTTP server closed')\n })\n})\n```\n\nHealth checks\n-------------\n\nA load balancer uses health checks to determine if an application instance is healthy and can accept requests. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/):\n\n* `liveness`, that determines when to restart a container.\n* `readiness`, that determines when a container is ready to start accepting traffic. When a pod is not ready, it is removed from the service load balancers.\n\n[![Image 1](https://expressjs.com/images/arrow.png)](https://expressjs.com/en/advanced/healthcheck-graceful-shutdown.html#)\n\nDocumentation translations provided by StrongLoop/IBM: [French](https://expressjs.com/fr/), [German](https://expressjs.com/de/), [Spanish](https://expressjs.com/es/), [Italian](https://expressjs.com/it/), [Japanese](https://expressjs.com/ja/), [Russian](https://expressjs.com/ru/), [Chinese](https://expressjs.com/zh-cn/), [Traditional Chinese](https://expressjs.com/zh-tw/), [Korean](https://expressjs.com/ko/), [Portuguese](https://expressjs.com/pt-br/). \nCommunity translation available for: [Slovak](https://expressjs.com/sk/), [Ukrainian](https://expressjs.com/uk/), [Uzbek](https://expressjs.com/uz/), [Turkish](https://expressjs.com/tr/), [Thai](https://expressjs.com/th/) and [Indonesian](https://expressjs.com/id/).\n\n[![Image 2: Preview Deploys by Netlify](https://www.netlify.com/v3/img/components/netlify-color-accent.svg)](https://www.netlify.com/)\n\n[Express](https://expressjs.com/) is a project of the [OpenJS Foundation](https://openjsf.org/).\n\n[Edit this page on GitHub](https://github.com/expressjs/expressjs.com/blob/gh-pages/en/advanced/healthcheck-graceful-shutdown.md).\n\nCopyright © 2017 StrongLoop, IBM, and other expressjs.com contributors.\n\n[![Image 3: Creative Commons License](https://i.creativecommons.org/l/by-sa/3.0/us/80x15.png)](http://creativecommons.org/licenses/by-sa/3.0/us/) This work is licensed under a [Creative Commons Attribution-ShareAlike 3.0 United States License](http://creativecommons.org/licenses/by-sa/3.0/us/).\n", "filename": "healthcheck-graceful-shutdown.md", "package": "express" }

js-docs

A collection of documentation for popular javascript packages and frameworks, in markdown. Perfect for filling your vector stores.

Downloads last month
11
Edit dataset card