# Express.js — Official Middleware > Official middleware modules maintained by the Express.js team. --- ## body-parser middleware URL: https://expressjs.com/en/resources/middleware/body-parser Node.js body parsing middleware. Parse incoming request bodies in a middleware before your handlers, available under the `req.body` property. **Note** As `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 the `foo` property 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. [Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/learn/http/anatomy-of-an-http-transaction). _This does not handle multipart bodies_, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: - [busboy](https://www.npmjs.com/package/busboy#readme) and [connect-busboy](https://www.npmjs.com/package/connect-busboy#readme) - [multiparty](https://www.npmjs.com/package/multiparty#readme) and [connect-multiparty](https://www.npmjs.com/package/connect-multiparty#readme) - [formidable](https://www.npmjs.com/package/formidable#readme) - [multer](https://www.npmjs.com/package/multer#readme) This module provides the following parsers: - [JSON body parser](#bodyparserjsonoptions) - [Raw body parser](#bodyparserrawoptions) - [Text body parser](#bodyparsertextoptions) - [URL-encoded form body parser](#bodyparserurlencodedoptions) All parsers support automatic inflation of `gzip`, `br` (brotli), `deflate` and `zstd` encodings. `zstd` is available in Node.js `^22.15.0` and `>=23.8.0`. Other body parsers you might be interested in: - [body](https://www.npmjs.com/package/body#readme) - [co-body](https://www.npmjs.com/package/co-body#readme) ## Installation `body-parser` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js // Import all parsers const bodyParser = require('body-parser'); // Or import individual parsers directly const json = require('body-parser/json'); const urlencoded = require('body-parser/urlencoded'); const raw = require('body-parser/raw'); const text = require('body-parser/text'); ``` The `bodyParser` object exposes various factories to create middlewares. All middlewares will populate the `req.body` property with the parsed body when the `Content-Type` request header matches the `type` option. **Note** As of v2, `req.body` is left `undefined` when no body is parsed (for example when the request has neither `Content-Length` nor `Transfer-Encoding`, or when `Content-Type` does not match). In v1, `req.body` was always initialized to `{}`. Code that assumes `req.body` is always an object should use optional chaining (for example `req.body?.username`) or set a default. The various errors returned by this module are described in the [errors section](#errors). ### bodyParser.json([options]) Returns 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. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). #### Options The `json` function takes an optional `options` object that may contain any of the following keys: ##### defaultCharset Specify the default character set for the json content if the charset is not specified in the `Content-Type` header of the request. Defaults to `utf-8`. ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### 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. Defaults to `'100kb'`. > It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. ##### 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#the_reviver_parameter). ##### strict When set to `true`, it will only accept arrays and objects; when `false`, it will accept anything `JSON.parse` accepts. Defaults to `true`. ##### type The `type` option 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.com/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. Defaults to `application/json`. ##### verify The `verify` 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. ### bodyParser.raw([options]) Returns middleware that parses all bodies as a `Buffer` and only looks at requests where the `Content-Type` header matches the `type` option. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This will be a `Buffer` object of the body. #### Options The `raw` function takes an optional `options` object that may contain any of the following keys: ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### 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. Defaults to `'100kb'`. > It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. ##### type The `type` option 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.com/package/type-is#readme) library and this can be an extension name (like `bin`), a mime type (like `application/octet-stream`), or a mime type with a wildcard (like `*/*` or `application/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `application/octet-stream`. ##### verify The `verify` 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. ### bodyParser.text([options]) Returns middleware that parses all bodies as a string and only looks at requests where the `Content-Type` header matches the `type` option. A new `body` string containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This will be a string of the body. #### Options The `text` function takes an optional `options` object that may contain any of the following keys: ##### defaultCharset Specify the default character set for the text content if the charset is not specified in the `Content-Type` header of the request. Defaults to `utf-8`. ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### 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. Defaults to `'100kb'`. > It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. ##### type The `type` option 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.com/package/type-is#readme) library and this can be an extension name (like `txt`), a mime type (like `text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `text/plain`. ##### verify The `verify` 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. ### bodyParser.urlencoded([options]) Returns 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 and ISO-8859-1 encodings of the body. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). 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`). #### Options The `urlencoded` function takes an optional `options` object that may contain any of the following keys: ##### extended 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.com/package/qs#readme). Defaults to `false`. ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### 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. Defaults to `'100kb'`. > It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. ##### parameterLimit The `parameterLimit` option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, a 413 will be returned to the client. Defaults to `1000`. ##### type The `type` option 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.com/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. Defaults to `application/x-www-form-urlencoded`. ##### verify The `verify` 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. ##### defaultCharset The default charset to parse as, if not specified in content-type. Must be either `utf-8` or `iso-8859-1`. Defaults to `utf-8`. ##### charsetSentinel Whether to let the value of the `utf8` parameter take precedence as the charset selector. It requires the form to contain a parameter named `utf8` with a value of `✓`. Defaults to `false`. ##### interpretNumericEntities Whether to decode numeric entities such as `☺` when parsing an iso-8859-1 form. Defaults to `false`. ##### depth The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible. ## Errors The middlewares provided by this module create errors using the [`http-errors` module](https://www.npmjs.com/package/http-errors). The errors will typically have a `status`/`statusCode` property that contains the suggested HTTP response code, an `expose` property to determine if the `message` property should be displayed to the client, a `type` property to determine the type of error without matching against the `message`, and a `body` property containing the read body, if available. The following are the common errors created, though any error can come through for various reasons. ### content encoding unsupported This error will occur when the request had a `Content-Encoding` header that contained an encoding but the "inflation" option was set to `false`. The `status` property is set to `415`, the `type` property is set to `'encoding.unsupported'`, and the `charset` property will be set to the encoding that is unsupported. ### entity parse failed This error will occur when the request contained an entity that could not be parsed by the middleware. The `status` property is set to `400`, the `type` property is set to `'entity.parse.failed'`, and the `body` property is set to the entity value that failed parsing. ### entity verify failed This error will occur when the request contained an entity that could not be verified by the defined `verify` option. The `status` property is set to `403`, the `type` property is set to `'entity.verify.failed'`, and the `body` property is set to the entity value that failed verification. ### request aborted This error will occur when the request is aborted by the client before reading the body has finished. The `received` property will be set to the number of bytes received before the request was aborted and the `expected` property is set to the number of expected bytes. The `status` property is set to `400` and `type` property is set to `'request.aborted'`. ### request entity too large This error will occur when the request body's size is larger than the "limit" option. The `limit` property will be set to the byte limit and the `length` property will be set to the request body's length. The `status` property is set to `413` and the `type` property is set to `'entity.too.large'`. ### request size did not match content length This error will occur when the request's length did not match the length from the `Content-Length` header. This typically occurs when the request is malformed, typically when the `Content-Length` header was calculated based on characters instead of bytes. The `status` property is set to `400` and the `type` property is set to `'request.size.invalid'`. ### stream encoding should not be set This error will occur when something called the `req.setEncoding` method prior to this middleware. This module operates directly on bytes only and you cannot call `req.setEncoding` when using this module. The `status` property is set to `500` and the `type` property is set to `'stream.encoding.set'`. ### stream is not readable This error will occur when the request is no longer readable when this middleware attempts to read it. This typically means something other than a middleware from this module read the request body already and the middleware was also configured to read the same request. The `status` property is set to `500` and the `type` property is set to `'stream.not.readable'`. ### too many parameters This error will occur when the content of the request exceeds the configured `parameterLimit` for the `urlencoded` parser. The `status` property is set to `413` and the `type` property is set to `'parameters.too.many'`. ### unsupported charset "BOGUS" This error will occur when the request had a charset parameter in the `Content-Type` header, but the `iconv-lite` module does not support it OR the parser does not support it. The charset is contained in the message as well as in the `charset` property. The `status` property is set to `415`, the `type` property is set to `'charset.unsupported'`, and the `charset` property is set to the charset that is unsupported. ### unsupported content encoding "bogus" This error will occur when the request had a `Content-Encoding` header that contained an unsupported encoding. The encoding is contained in the message as well as in the `encoding` property. The `status` property is set to `415`, the `type` property is set to `'encoding.unsupported'`, and the `encoding` property is set to the encoding that is unsupported. ### The input exceeded the depth This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. With the default `depth` of `32`, an input with 33 or more levels of nesting gets this error. ## Examples ### Express/Connect top-level generic This example demonstrates adding a generic JSON and URL-encoded parser as a top-level middleware, which will parse the bodies of all incoming requests. This is the simplest setup. ```js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded()); // parse application/json app.use(bodyParser.json()); app.use(function (req, res) { res.setHeader('Content-Type', 'text/plain'); res.write('you posted:\n'); res.end(String(JSON.stringify(req.body, null, 2))); }); ``` ### Express route-specific This example demonstrates adding body parsers specifically to the routes that need them. In general, this is the most recommended way to use body-parser with Express. ```js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // create application/json parser const jsonParser = bodyParser.json(); // create application/x-www-form-urlencoded parser const urlencodedParser = bodyParser.urlencoded(); // POST /login gets urlencoded bodies app.post('/login', urlencodedParser, function (req, res) { if (!req.body || !req.body.username) res.sendStatus(400); res.send('welcome, ' + req.body.username); }); // POST /api/users gets JSON bodies app.post('/api/users', jsonParser, function (req, res) { if (!req.body) res.sendStatus(400); // create user in req.body }); ``` ### Change accepted type for parsers All the parsers accept a `type` option which allows you to change the `Content-Type` that the middleware will parse. ```js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // parse various different custom JSON types as JSON app.use(bodyParser.json({ type: 'application/*+json' })); // parse some custom thing into a Buffer app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })); // parse an HTML body into a string app.use(bodyParser.text({ type: 'text/html' })); ``` ## License [MIT](https://github.com/expressjs/body-parser/blob/HEAD/LICENSE) [npm-url]: https://npmjs.com/package/body-parser [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser --- ## compression middleware URL: https://expressjs.com/en/resources/middleware/compression Node.js compression middleware. The following compression codings are supported: - deflate - gzip - br (brotli) **Note** Brotli is available in all currently supported Node.js LTS versions (v18+). ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/downloading-and-installing-packages-locally): `compression` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var compression = require('compression'); ``` ### compression([options]) Returns the compression middleware using the given `options`. The middleware will attempt to compress response bodies for all requests that traverse through the middleware, based on the given `options`. This middleware will never compress responses that include a `Cache-Control` header with the [`no-transform` directive](https://tools.ietf.org/html/rfc7234#section-5.2.2.4), as compressing will transform the body. #### Options `compression()` accepts these properties in the options object. In addition to those listed below, [zlib](https://nodejs.org/api/zlib.html) options may be passed in to the options object or [brotli](https://nodejs.org/api/zlib.html#zlib_class_brotlioptions) options. ##### chunkSize Type: `Number`
Default: `zlib.constants.Z_DEFAULT_CHUNK`, or `16384`. See [Node.js documentation](https://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### filter Type: `Function` A function to decide if the response should be considered for compression. This function is called as `filter(req, res)` and is expected to return `true` to consider the response for compression, or `false` to not compress the response. The default filter function uses the [compressible](https://www.npmjs.com/package/compressible) module to determine if `res.getHeader('Content-Type')` is compressible. ##### level Type: `Number`
Default: `zlib.constants.Z_DEFAULT_COMPRESSION`, or `-1` The level of zlib compression to apply to responses. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster. This is an integer in the range of `0` (no compression) to `9` (maximum compression). The special value `-1` can be used to mean the "default compression level", which is a default compromise between speed and compression (currently equivalent to level 6). - `-1` Default compression level (also `zlib.constants.Z_DEFAULT_COMPRESSION`). - `0` No compression (also `zlib.constants.Z_NO_COMPRESSION`). - `1` Fastest compression (also `zlib.constants.Z_BEST_SPEED`). - `2` - `3` - `4` - `5` - `6` (currently what `zlib.constants.Z_DEFAULT_COMPRESSION` points to). - `7` - `8` - `9` Best compression (also `zlib.constants.Z_BEST_COMPRESSION`). **Note** in the list above, `zlib` is from `zlib = require('zlib')`. ##### memLevel Type: `Number`
Default: `zlib.constants.Z_DEFAULT_MEMLEVEL`, or `8` This specifies how much memory should be allocated for the internal compression state and is an integer in the range of `1` (minimum level) and `9` (maximum level). See [Node.js documentation](https://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### brotli Type: `Object` This specifies the options for configuring Brotli. See [Node.js documentation](https://nodejs.org/api/zlib.html#class-brotlioptions) for a complete list of available options. ##### strategy Type: `Number`
Default: `zlib.constants.Z_DEFAULT_STRATEGY` This is used to tune the compression algorithm. This value only affects the compression ratio, not the correctness of the compressed output, even if it is not set appropriately. - `zlib.constants.Z_DEFAULT_STRATEGY` Use for normal data. - `zlib.constants.Z_FILTERED` Use for data produced by a filter (or predictor). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect is to force more Huffman coding and less string matching; it is somewhat intermediate between `zlib.constants.Z_DEFAULT_STRATEGY` and `zlib.constants.Z_HUFFMAN_ONLY`. - `zlib.constants.Z_FIXED` Use to prevent the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. - `zlib.constants.Z_HUFFMAN_ONLY` Use to force Huffman encoding only (no string match). - `zlib.constants.Z_RLE` Use to limit match distances to one (run-length encoding). This is designed to be almost as fast as `zlib.constants.Z_HUFFMAN_ONLY`, but give better compression for PNG image data. **Note** in the list above, `zlib` is from `zlib = require('zlib')`. ##### threshold Type: `Number` or `String`
Default: `1kb` The byte threshold for the response body size before compression is considered for the response. This is a number of bytes or any string accepted by the [bytes](https://www.npmjs.com/package/bytes) module. **Note** this is only an advisory setting; if the response size cannot be determined at the time the response headers are written, then it is assumed the response is _over_ the threshold. To guarantee the response size can be determined, be sure set a `Content-Length` response header. ##### windowBits Type: `Number`
Default: `zlib.constants.Z_DEFAULT_WINDOWBITS`, or `15` See [Node.js documentation](https://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### enforceEncoding Type: `String`
Default: `identity` This is the default encoding to use when the client does not specify an encoding in the request's [Accept-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding) header. #### .filter The default `filter` function. This is used to construct a custom filter function that is an extension of the default function. ```js var compression = require('compression'); var express = require('express'); var app = express(); app.use(compression({ filter: shouldCompress })); function shouldCompress(req, res) { if (req.headers['x-no-compression']) { // don't compress responses with this request header return false; } // fallback to standard filter function return compression.filter(req, res); } ``` ### res.flush This module adds a `res.flush()` method to force the partially-compressed response to be flushed to the client. ## Examples ### express When using this module with express, simply `app.use` the module as high as you like. Requests that pass through the middleware will be compressed. ```js var compression = require('compression'); var express = require('express'); var app = express(); // compress all responses app.use(compression()); // add all routes ``` ### Node.js HTTP server ```js var compression = require('compression')({ threshold: 0 }); var http = require('http'); function createServer(fn) { return http.createServer(function (req, res) { compression(req, res, function (err) { if (err) { res.statusCode = err.status || 500; res.end(err.message); return; } fn(req, res); }); }); } var server = createServer(function (req, res) { res.setHeader('Content-Type', 'text/plain'); res.end('hello world!'); }); server.listen(3000, () => { console.log('> Listening at http://localhost:3000'); }); ``` ### Server-Sent Events Because of the nature of compression this module does not work out of the box with server-sent events. To compress content, a window of the output needs to be buffered up in order to get good compression. Typically when using server-sent events, there are certain block of data that need to reach the client. You can achieve this by calling `res.flush()` when you need the data written to actually make it to the client. ```js var compression = require('compression'); var express = require('express'); var app = express(); // compress responses app.use(compression()); // server-sent event stream app.get('/events', function (req, res) { res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); // send a ping approx every 2 seconds var timer = setInterval(function () { res.write('data: ping\n\n'); // !!! this is the important part res.flush(); }, 2000); res.on('close', function () { clearInterval(timer); }); }); ``` ## Contributing The Express.js project welcomes all constructive contributions. Contributions take many forms, from code for bug fixes and enhancements, to additions and fixes to documentation, additional tests, triaging incoming pull requests and issues, and more! See the [Contributing Guide](https://github.com/expressjs/.github/blob/HEAD/CONTRIBUTING.md) for more technical details on contributing. ## License [MIT](https://github.com/expressjs/compression/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/compression [downloads-url]: https://npmcharts.com/compare/compression?minimal=true [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/compression/badge [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/compression [funding-url]: https://opencollective.com/express --- ## cookie-parser middleware URL: https://expressjs.com/en/resources/middleware/cookie-parser Parse `Cookie` header and populate `req.cookies` with an object keyed by the cookie names. Optionally you may enable signed cookie support by passing a `secret` string, which assigns `req.secret` so it may be used by other middleware. ## Installation `cookie-parser` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var cookieParser = require('cookie-parser'); ``` ### cookieParser(secret, options) Create a new cookie parser middleware function using the given `secret` and `options`. - `secret` a string or array used for signing cookies. This is optional and if not specified, will not parse signed cookies. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order. - `options` an object that is passed to `cookie.parse` as the second option. See [cookie](https://www.npmjs.org/package/cookie) for more information. - `decode` a function to decode the value of the cookie The middleware will parse the `Cookie` header on the request and expose the cookie data as the property `req.cookies` and, if a `secret` was provided, as the property `req.signedCookies`. These properties are name value pairs of the cookie name to cookie value. When `secret` is provided, this module will unsign and validate any signed cookie values and move those name value pairs from `req.cookies` into `req.signedCookies`. A signed cookie is a cookie that has a value prefixed with `s:`. Signed cookies that fail signature validation will have the value `false` instead of the tampered value. In addition, this module supports special "JSON cookies". These are cookie where the value is prefixed with `j:`. When these values are encountered, the value will be exposed as the result of `JSON.parse`. If parsing fails, the original value will remain. ### cookieParser.JSONCookie(str) Parse a cookie value as a JSON cookie. This will return the parsed JSON value if it was a JSON cookie, otherwise, it will return the passed value. ### cookieParser.JSONCookies(cookies) Given an object, this will iterate over the keys and call `JSONCookie` on each value, replacing the original value with the parsed value. This returns the same object that was passed in. ### cookieParser.signedCookie(str, secret) Parse a cookie value as a signed cookie. This will return the parsed unsigned value if it was a signed cookie and the signature was valid. If the value was not signed, the original value is returned. If the value was signed but the signature could not be validated, `false` is returned. The `secret` argument can be an array or string. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order. ### cookieParser.signedCookies(cookies, secret) Given an object, this will iterate over the keys and check if any value is a signed cookie. If it is a signed cookie and the signature is valid, the key will be deleted from the object and added to the new object that is returned. The `secret` argument can be an array or string. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order. ## Example ```js var express = require('express'); var cookieParser = require('cookie-parser'); var app = express(); app.use(cookieParser()); app.get('/', function (req, res) { // Cookies that have not been signed console.log('Cookies: ', req.cookies); // Cookies that have been signed console.log('Signed Cookies: ', req.signedCookies); }); app.listen(8080); // curl command that sends an HTTP request with two cookies // curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello" ``` ## License [MIT](https://github.com/expressjs/cookie-parser/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/cookie-parser --- ## cookie-session middleware URL: https://expressjs.com/en/resources/middleware/cookie-session Simple cookie-based session middleware. A user session can be stored in two main ways with cookies: on the server or on the client. This module stores the session data on the client within a cookie, while a module like [express-session](https://www.npmjs.com/package/express-session) stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database. The following points can help you choose which to use: - `cookie-session` does not require any database / resources on the server side, though the total session data cannot exceed the browser's max cookie size. - `cookie-session` can simplify certain load-balanced scenarios. - `cookie-session` can be used to store a "light" session and include an identifier to look up a database-backed secondary store to reduce database lookups. **NOTE** This module does not encrypt the session contents in the cookie, only provides signing to prevent tampering. The client will be able to read the session data by examining the cookie's value. Secret data should not be set in `req.session` without encrypting it, or use a server-side session instead. **NOTE** This module does not prevent session replay, as the expiration set is that of the cookie only; if that is a concern of your application, you can store an expiration date in `req.session` object and validate it on the server, and implement any other logic to extend the session as your application needs. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `cookie-session` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var cookieSession = require('cookie-session'); var express = require('express'); var app = express(); app.use( cookieSession({ name: 'session', keys: [ /* secret keys */ ], // Cookie Options maxAge: 24 * 60 * 60 * 1000, // 24 hours }) ); ``` ### cookieSession(options) Create a new cookie session middleware with the provided options. This middleware will attach the property `session` to `req`, which provides an object representing the loaded session. This session is either a new session if no valid session was provided in the request, or a loaded session from the request. The middleware will automatically add a `Set-Cookie` header to the response if the contents of `req.session` were altered. _Note_ that no `Set-Cookie` header will be in the response (and thus no session created for a specific user) unless there are contents in the session, so be sure to add something to `req.session` as soon as you have identifying information to store for the session. #### Options Cookie session accepts these properties in the options object. ##### name The name of the cookie to set, defaults to `session`. ##### keys The list of keys to use to sign & verify cookie values, or a configured [`Keygrip`](https://www.npmjs.com/package/keygrip) instance. Set cookies are always signed with `keys[0]`, while the other keys are valid for verification, allowing for key rotation. If a `Keygrip` instance is provided, it can be used to change signature parameters like the algorithm of the signature. ##### secret A string which will be used as single key if `keys` is not provided. ##### Cookie Options Other options are passed to `cookies.get()` and `cookies.set()` allowing you to control security, domain, path, and signing among other settings. The options can also contain any of the following (for the full list, see [cookies module documentation](https://www.npmjs.org/package/cookies#readme): - `maxAge`: a number representing the milliseconds from `Date.now()` for expiry - `expires`: a `Date` object indicating the cookie's expiration date (expires at the end of session by default). - `path`: a string indicating the path of the cookie (`/` by default). - `domain`: a string indicating the domain of the cookie (no default). - `partitioned`: a boolean indicating whether to partition the cookie in Chrome for the [CHIPS Update](https://developers.google.com/privacy-sandbox/3pcd/chips) (`false` by default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created. - `priority`: a string indicating the cookie priority. This can be set to `'low'`, `'medium'`, or `'high'`. - `sameSite`: a boolean or string indicating whether the cookie is a "same site" cookie (`false` by default). This can be set to `'strict'`, `'lax'`, `'none'`, or `true` (which maps to `'strict'`). - `secure`: a boolean indicating whether the cookie is only to be sent over HTTPS (`false` by default for HTTP, `true` by default for HTTPS). If this is set to `true` and Node.js is not directly over a TLS connection, be sure to read how to [setup Express behind proxies](/guide/behind-proxies/) or the cookie may not ever set correctly. - `httpOnly`: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (`true` by default). - `signed`: a boolean indicating whether the cookie is to be signed (`true` by default). - `overwrite`: a boolean indicating whether to overwrite previously set cookies of the same name (`true` by default). ### req.session Represents the session for the given request. #### .isChanged Is `true` if the session has been changed during the request. #### .isNew Is `true` if the session is new. #### .isPopulated Determine if the session has been populated with data or is empty. ### req.sessionOptions Represents the session options for the current request. These options are a shallow clone of what was provided at middleware construction and can be altered to change cookie setting behavior on a per-request basis. ### Destroying a session To destroy a session simply set it to `null`: ```js req.session = null; ``` ### Saving a session Since the entire contents of the session is kept in a client-side cookie, the session is "saved" by writing a cookie out in a `Set-Cookie` response header. This is done automatically if there has been a change made to the session when the Node.js response headers are being written to the client and the session was not destroyed. ## Examples ### Simple view counter example ```js var cookieSession = require('cookie-session'); var express = require('express'); var app = express(); app.set('trust proxy', 1); // trust first proxy app.use( cookieSession({ name: 'session', keys: ['key1', 'key2'], }) ); app.get('/', function (req, res, next) { // Update views req.session.views = (req.session.views || 0) + 1; // Write response res.end(req.session.views + ' views'); }); app.listen(3000); ``` ### Per-user sticky max age ```js var cookieSession = require('cookie-session'); var express = require('express'); var app = express(); app.set('trust proxy', 1); // trust first proxy app.use( cookieSession({ name: 'session', keys: ['key1', 'key2'], }) ); // This allows you to set req.session.maxAge to let certain sessions // have a different value than the default. app.use(function (req, res, next) { req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge; next(); }); // ... your logic here ... ``` ### Extending the session expiration This module does not send a `Set-Cookie` header if the contents of the session have not changed. This means that to extend the expiration of a session in the user's browser (in response to user activity, for example) some kind of modification to the session needs be made. ```js var cookieSession = require('cookie-session'); var express = require('express'); var app = express(); app.use( cookieSession({ name: 'session', keys: ['key1', 'key2'], }) ); // Update a value in the cookie so that the set-cookie will be sent. // Only changes every minute so that it's not sent with every request. app.use(function (req, res, next) { req.session.nowInMinutes = Math.floor(Date.now() / 60e3); next(); }); // ... your logic here ... ``` ### Using a custom signature algorithm This example shows creating a custom `Keygrip` instance as the `keys` option to provide keys and additional signature configuration. ```js var cookieSession = require('cookie-session'); var express = require('express'); var Keygrip = require('keygrip'); var app = express(); app.use( cookieSession({ name: 'session', keys: new Keygrip(['key1', 'key2'], 'SHA384', 'base64'), }) ); // ... your logic here ... ``` ## Usage Limitations ### Max Cookie Size Because the entire session object is encoded and stored in a cookie, it is possible to exceed the maximum cookie size limits on different browsers. The [RFC6265 specification](https://tools.ietf.org/html/rfc6265#section-6.1) recommends that a browser **SHOULD** allow > At least 4096 bytes per cookie (as measured by the sum of the length of > the cookie's name, value, and attributes) In practice this limit differs slightly across browsers. See a list of [browser limits here](http://browsercookielimits.iain.guru). As a rule of thumb **don't exceed 4093 bytes per domain**. If your session object is large enough to exceed a browser limit when encoded, in most cases the browser will refuse to store the cookie. This will cause the following requests from the browser to either a) not have any session information or b) use old session information that was small enough to not exceed the cookie limit. If you find your session object is hitting these limits, it is best to consider if data in your session should be loaded from a database on the server instead of transmitted to/from the browser with every request. Or move to an [alternative session strategy](https://github.com/expressjs/session#compatible-session-stores) ## License [MIT](https://github.com/expressjs/cookie-session/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/cookie-session --- ## cors middleware URL: https://expressjs.com/en/resources/middleware/cors CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server. **How CORS Works:** This package sets response headers—it doesn't block requests. CORS is enforced by browsers: they check the headers and decide if JavaScript can read the response. Non-browser clients (curl, Postman, other servers) ignore CORS entirely. See the [MDN CORS guide](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) for details. - [Installation](#installation) - [Usage](#usage) - [Simple Usage](#simple-usage-enable-all-cors-requests) - [Enable CORS for a Single Route](#enable-cors-for-a-single-route) - [Configuring CORS](#configuring-cors) - [Configuring CORS w/ Dynamic Origin](#configuring-cors-w-dynamic-origin) - [Enabling CORS Pre-Flight](#enabling-cors-pre-flight) - [Customizing CORS Settings Dynamically per Request](#customizing-cors-settings-dynamically-per-request) - [Configuration Options](#configuration-options) - [Common Misconceptions](#common-misconceptions) - [License](#license) - [Original Author](#original-author) ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/downloading-and-installing-packages-locally): `cors` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## Usage ### Simple Usage (Enable _All_ CORS Requests) ```javascript var express = require('express'); var cors = require('cors'); var app = express(); // Adds headers: Access-Control-Allow-Origin: * app.use(cors()); app.get('/products/:id', function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ### Enable CORS for a Single Route ```javascript var express = require('express'); var cors = require('cors'); var app = express(); // Adds headers: Access-Control-Allow-Origin: * app.get('/products/:id', cors(), function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ### Configuring CORS See the [configuration options](#configuration-options) for details. ```javascript var express = require('express'); var cors = require('cors'); var app = express(); var corsOptions = { origin: 'http://example.com', optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204 }; // Adds headers: Access-Control-Allow-Origin: http://example.com, Vary: Origin app.get('/products/:id', cors(corsOptions), function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ### Configuring CORS w/ Dynamic Origin This module supports validating the origin dynamically using a function provided to the `origin` option. This function will be passed a string that is the origin (or `undefined` if the request has no origin), and a `callback` with the signature `callback(error, origin)`. The `origin` argument to the callback can be any value allowed for the `origin` option of the middleware, except a function. See the [configuration options](#configuration-options) section for more information on all the possible value types. This function is designed to allow the dynamic loading of allowed origin(s) from a backing datasource, like a database. ```javascript var express = require('express'); var cors = require('cors'); var app = express(); var corsOptions = { origin: function (origin, callback) { // db.loadOrigins is an example call to load // a list of origins from a backing database db.loadOrigins(function (error, origins) { callback(error, origins); }); }, }; // Adds headers: Access-Control-Allow-Origin: , Vary: Origin app.get('/products/:id', cors(corsOptions), function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ### Enabling CORS Pre-Flight Certain CORS requests are considered 'complex' and require an initial `OPTIONS` request (called the "pre-flight request"). An example of a 'complex' CORS request is one that uses an HTTP verb other than GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable pre-flighting, you must add a new OPTIONS handler for the route you want to support: ```javascript var express = require('express'); var cors = require('cors'); var app = express(); app.options('/products/:id', cors()); // preflight for DELETE app.delete('/products/:id', cors(), function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` You can also enable pre-flight across-the-board like so: ```javascript app.options('*', cors()); // include before other routes ``` NOTE: When using this middleware as an application level middleware (for example, `app.use(cors())`), pre-flight requests are already handled for all routes. ### Customizing CORS Settings Dynamically per Request For APIs that require different CORS configurations for specific routes or requests, you can dynamically generate CORS options based on the incoming request. The `cors` middleware allows you to achieve this by passing a function instead of static options. This function is called for each incoming request and must use the callback pattern to return the appropriate CORS options. The function accepts: 1. **`req`**: - The incoming request object. 2. **`callback(error, corsOptions)`**: - A function used to return the computed CORS options. - **Arguments**: - **`error`**: Pass `null` if there’s no error, or an error object to indicate a failure. - **`corsOptions`**: An object specifying the CORS policy for the current request. Here’s an example that handles both public routes and restricted, credential-sensitive routes: ```javascript var dynamicCorsOptions = function (req, callback) { var corsOptions; if (req.path.startsWith('/auth/connect/')) { // Access-Control-Allow-Origin: http://mydomain.com, Access-Control-Allow-Credentials: true, Vary: Origin corsOptions = { origin: 'http://mydomain.com', credentials: true, }; } else { // Access-Control-Allow-Origin: * corsOptions = { origin: '*' }; } callback(null, corsOptions); }; app.use(cors(dynamicCorsOptions)); app.get('/auth/connect/twitter', function (req, res) { res.send('Hello'); }); app.get('/public', function (req, res) { res.send('Hello'); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ## Configuration Options - `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Possible values: - `Boolean` - set `origin` to `true` to reflect the [request origin](https://datatracker.ietf.org/doc/html/draft-abarth-origin-09), as defined by `req.header('Origin')`, or set it to `false` to disable CORS. - `String` - set `origin` to a specific origin. For example, if you set it to - `"http://example.com"` only requests from "http://example.com" will be allowed. - `"*"` for all domains to be allowed. - `RegExp` - set `origin` to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern `/example\.com$/` will reflect any request that is coming from an origin ending with "example.com". - `Array` - set `origin` to an array of valid origins. Each origin can be a `String` or a `RegExp`. For example `["http://example1.com", /\.example2\.com$/]` will accept any request from "http://example1.com" or from a subdomain of "example2.com". - `Function` - set `origin` to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (called as `callback(err, origin)`, where `origin` is a non-function value of the `origin` option) as the second. - `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: `['GET', 'PUT', 'POST']`). - `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: `['Content-Type', 'Authorization']`). If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header. - `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: `['Content-Range', 'X-Content-Range']`). If not specified, no custom headers are exposed. - `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted. - `maxAge`: Configures the **Access-Control-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted. - `preflightContinue`: Pass the CORS preflight response to the next handler. - `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`. The default configuration is the equivalent of: ```json { "origin": "*", "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", "preflightContinue": false, "optionsSuccessStatus": 204 } ``` ## Common Misconceptions ### "CORS blocks requests from disallowed origins" **No.** Your server receives and processes every request. CORS headers tell the browser whether JavaScript can read the response—not whether the request is allowed. ### "CORS protects my API from unauthorized access" **No.** CORS is not access control. Any HTTP client (curl, Postman, another server) can call your API regardless of CORS settings. Use authentication and authorization to protect your API. ### "Setting `origin: 'http://example.com'` means only that domain can access my server" **No.** It means browsers will only let JavaScript from that origin read responses. The server still responds to all requests. ## License [MIT License](http://www.opensource.org/licenses/mit-license.php) ## Original Author [Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com)) [downloads-url]: https://npmjs.com/package/cors [github-actions-ci-url]: https://github.com/expressjs/cors?query=workflow%3Aci [npm-url]: https://npmjs.com/package/cors --- ## errorhandler middleware URL: https://expressjs.com/en/resources/middleware/errorhandler Development-only error handler middleware. This middleware is only intended to be used in a development environment, as the _full error stack traces and internal details of any object passed to this module_ will be sent back to the client when an error occurs. When an object is provided to Express as an error, this module will display as much about this object as possible, and will do so by using content negotiation for the response between HTML, JSON, and plain text. - When the object is a standard `Error` object, the string provided by the `stack` property will be returned in HTML/text responses. - When the object is a non-`Error` object, the result of [util.inspect](https://nodejs.org/api/util.html#util_util_inspect_object_options) will be returned in HTML/text responses. - For JSON responses, the result will be an object with all enumerable properties from the object in the response. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `errorhandler` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API {/* eslint-disable no-unused-vars */} ```js var errorhandler = require('errorhandler'); ``` ### errorhandler(options) Create new middleware to handle errors and respond with content negotiation. #### Options Error handler accepts these properties in the options object. ##### log Provide a function to be called with the error and a string representation of the error. Can be used to write the error to any desired location, or set to `false` to only send the error back in the response. Called as `log(err, str, req, res)` where `err` is the `Error` object, `str` is a string representation of the error, `req` is the request object and `res` is the response object (note, this function is invoked _after_ the response has been written). The default value for this option is `true` unless `process.env.NODE_ENV === 'test'`. Possible values: - `true`: Log errors using `console.error(str)`. - `false`: Only send the error back in the response. - A function: pass the error to a function for handling. ## Examples ### Simple example Basic example of adding this middleware as the error handler only in development with `connect` (`express` also can be used in this example). ```js var connect = require('connect'); var errorhandler = require('errorhandler'); var app = connect(); // assumes NODE_ENV is set by the user if (process.env.NODE_ENV === 'development') { // only use in development app.use(errorhandler()); } ``` ### Custom output location Sometimes you may want to output the errors to a different location than STDERR during development, like a system notification, for example. {/* eslint-disable handle-callback-err */} ```js var connect = require('connect'); var errorhandler = require('errorhandler'); var notifier = require('node-notifier'); var app = connect(); // assumes NODE_ENV is set by the user if (process.env.NODE_ENV === 'development') { // only use in development app.use(errorhandler({ log: errorNotification })); } function errorNotification(err, str, req) { var title = 'Error in ' + req.method + ' ' + req.url; notifier.notify({ title: title, message: str, }); } ``` ## License [MIT](https://github.com/expressjs/errorhandler/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/errorhandler --- ## method-override middleware URL: https://expressjs.com/en/resources/middleware/method-override Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `method-override` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API **NOTE** It is very important that this module is used **before** any module that needs to know the method of the request (for example, it _must_ be used prior to the `csurf` module). ### methodOverride(getter, options) Create a new middleware function to override the `req.method` property with a new value. This value will be pulled from the provided `getter`. - `getter` - The getter to use to look up the overridden request method for the request. (default: `X-HTTP-Method-Override`) - `options.methods` - The allowed methods the original request must be in to check for a method override value. (default: `['POST']`) If the found method is supported by node.js core, then `req.method` will be set to this value, as if it has originally been that value. The previous `req.method` value will be stored in `req.originalMethod`. #### getter This is the method of getting the override value from the request. If a function is provided, the `req` is passed as the first argument, the `res` as the second argument and the method is expected to be returned. If a string is provided, the string is used to look up the method with the following rules: - If the string starts with `X-`, then it is treated as the name of a header and that header is used for the method override. If the request contains the same header multiple times, the first occurrence is used. - All other strings are treated as a key in the URL query string. #### options.methods This allows the specification of what methods(s) the request _MUST_ be in in order to check for the method override value. This defaults to only `POST` methods, which is the only method the override should arrive in. More methods may be specified here, but it may introduce security issues and cause weird behavior when requests travel through caches. This value is an array of methods in upper-case. `null` can be specified to allow all methods. ## Examples ### override using a header To use a header to override the method, specify the header name as a string argument to the `methodOverride` function. To then make the call, send a `POST` request to a URL with the overridden method as the value of that header. This method of using a header would typically be used in conjunction with `XMLHttpRequest` on implementations that do not support the method you are trying to use. ```js const express = require('express'); const methodOverride = require('method-override'); const app = express(); // override with the X-HTTP-Method-Override header in the request app.use(methodOverride('X-HTTP-Method-Override')); ``` Example call with header override using `XMLHttpRequest`: {/* eslint-env browser */} ```js const xhr = new XMLHttpRequest(); xhr.onload = onload; xhr.open('post', '/resource', true); xhr.setRequestHeader('X-HTTP-Method-Override', 'DELETE'); xhr.send(); function onload() { alert('got response: ' + this.responseText); } ``` ### override using a query value To use a query string value to override the method, specify the query string key as a string argument to the `methodOverride` function. To then make the call, send a `POST` request to a URL with the overridden method as the value of that query string key. This method of using a query value would typically be used in conjunction with plain HTML `
` elements when trying to support legacy browsers but still use newer methods. ```js const express = require('express'); const methodOverride = require('method-override'); const app = express(); // override with POST having ?_method=DELETE app.use(methodOverride('_method')); ``` Example call with query override using HTML ``: ```html
``` ### multiple format support ```js const express = require('express'); const methodOverride = require('method-override'); const app = express(); // override with different headers; last one takes precedence app.use(methodOverride('X-HTTP-Method')); // Microsoft app.use(methodOverride('X-HTTP-Method-Override')); // Google/GData app.use(methodOverride('X-Method-Override')); // IBM ``` ### custom logic You can implement any kind of custom logic with a function for the `getter`. The following implements the logic for looking in `req.body` that was in `method-override@1`: ```js const bodyParser = require('body-parser'); const express = require('express'); const methodOverride = require('method-override'); const app = express(); // NOTE: when using req.body, you must fully parse the request body // before you call methodOverride() in your middleware stack, // otherwise req.body will not be populated. app.use(bodyParser.urlencoded()); app.use( methodOverride(function (req, res) { if (req.body && typeof req.body === 'object' && '_method' in req.body) { // look in urlencoded POST bodies and delete it const method = req.body._method; delete req.body._method; return method; } }) ); ``` Example call with query override using HTML `
`: ```html {/* enctype must be set to the type you will parse before methodOverride() */}
``` ## License [MIT](https://github.com/expressjs/method-override/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/method-override [downloads-url]: https://npmjs.org/package/method-override --- ## morgan middleware URL: https://expressjs.com/en/resources/middleware/morgan HTTP request logger middleware for node.js > Named after [Dexter](https://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion. ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `morgan` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API For ES Modules: {/* eslint-disable no-unused-vars */} ```js ``` For CommonJS: {/* eslint-disable no-unused-vars */} ```js var morgan = require('morgan'); ``` ### morgan(format, options) Create a new morgan logger middleware function using the given `format` and `options`. The `format` argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry. The `format` function will be called with three arguments `tokens`, `req`, and `res`, where `tokens` is an object with all defined tokens, `req` is the HTTP request and `res` is the HTTP response. The function is expected to return a string that will be the log line, or `undefined` / `null` to skip logging. #### Using a predefined format string {/* eslint-disable no-undef */} ```js morgan('tiny'); ``` #### Using format string of predefined tokens {/* eslint-disable no-undef */} ```js morgan(':method :url :status :res[content-length] - :response-time ms'); ``` #### Using a custom format function {/* eslint-disable no-undef */} ```js morgan(function (tokens, req, res) { return [ tokens.method(req, res), tokens.url(req, res), tokens.status(req, res), tokens.res(req, res, 'content-length'), '-', tokens['response-time'](req, res), 'ms', ].join(' '); }); ``` #### Options Morgan accepts these properties in the options object. ##### immediate Write log line on request instead of response. This means that requests will be logged even if the server crashes, _but data from the response (like the response code, content length, etc.) cannot be logged_. ##### skip Function to determine if logging is skipped, defaults to `false`. This function will be called as `skip(req, res)`. {/* eslint-disable no-undef */} ```js // EXAMPLE: only log error responses morgan('combined', { skip: function (req, res) { return res.statusCode < 400; }, }); ``` ##### stream Output stream for writing log lines, defaults to `process.stdout`. If the stream is in object mode (`stream.writableObjectMode` is `true`) and the format function returns an object, the object is written to the stream as-is, without a trailing newline. This allows passing structured log entries to loggers that accept objects: {/* eslint-disable no-undef */} ```js morgan( function (tokens, req, res) { return { method: tokens.method(req, res), url: tokens.url(req, res), status: Number(tokens.status(req, res)), }; }, { stream: { writableObjectMode: true, write: function (entry) { // entry is the object returned by the format function }, }, } ); ``` #### Predefined Formats There are various pre-defined formats provided: ##### combined Standard Apache combined log output. ``` :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" # will output ::1 - - [27/Nov/2024:06:21:42 +0000] "GET /combined HTTP/1.1" 200 2 "-" "curl/8.7.1" ``` ##### common Standard Apache common log output. ``` :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] # will output ::1 - - [27/Nov/2024:06:21:46 +0000] "GET /common HTTP/1.1" 200 2 ``` ##### dev Concise output colored by response status for development use. The `:status` token will be colored green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for information codes. ``` :method :url :status :response-time ms - :res[content-length] # will output GET /dev 200 0.224 ms - 2 ``` Coloring is disabled when the [`NO_COLOR`](https://no-color.org) environment variable is set to any non-empty value, in which case the output above is written without any escape sequences. The variable is read once, when `morgan` is first required. ##### short Shorter than default, also including response time. ``` :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms # will output ::1 - GET /short HTTP/1.1 200 2 - 0.283 ms ``` ##### tiny The minimal output. ``` :method :url :status :res[content-length] - :response-time ms # will output GET /tiny 200 2 - 0.188 ms ``` #### Tokens ##### Creating new tokens To define a token, simply invoke `morgan.token()` with the name and a callback function. This callback function is expected to return a string value. The value returned is then available as ":type" in this case: {/* eslint-disable no-undef */} ```js morgan.token('type', function (req, res) { return req.headers['content-type']; }); ``` Calling `morgan.token()` using the same name as an existing token will overwrite that token definition. The token function is expected to be called with the arguments `req` and `res`, representing the HTTP request and HTTP response. Additionally, the token can accept further arguments of its choosing to customize behavior. ##### :date[format] The current date and time in UTC. The available formats are: - `clf` for the common log format (`"10/Oct/2000:13:55:36 +0000"`) - `iso` for the common ISO 8601 date time format (`2000-10-10T13:55:36.000Z`) - `web` for the common RFC 1123 date time format (`Tue, 10 Oct 2000 13:55:36 GMT`) If no format is given, then the default is `web`. ##### :http-version The HTTP version of the request. ##### :method The HTTP method of the request. ##### :pid The process ID of the Node.js process handling the request. ##### :referrer The Referrer header of the request. This will use the standard mis-spelled Referer header if it exists, otherwise Referrer. ##### :remote-addr The remote address of the request. This will use `req.ip`, otherwise the standard `req.connection.remoteAddress` value (socket address). ##### :remote-user The user authenticated as part of Basic auth for the request. ##### :req[header] The given `header` of the request. If the header is not present, the value will be displayed as `"-"` in the log. ##### :res[header] The given `header` of the response. If the header is not present, the value will be displayed as `"-"` in the log. ##### :response-time[digits] The time between the request coming into `morgan` and when the response headers are written, in milliseconds. The `digits` argument is a number that specifies the number of digits to include on the number, defaulting to `3`, which provides microsecond precision. ##### :status The status code of the response. If the request/response cycle completes before a response was sent to the client (for example, the TCP socket closed prematurely by a client aborting the request), then the status will be empty (displayed as `"-"` in the log). ##### :total-time[digits] The time between the request coming into `morgan` and when the response has finished being written out to the connection, in milliseconds. The `digits` argument is a number that specifies the number of digits to include on the number, defaulting to `3`, which provides microsecond precision. ##### :url The URL of the request. This will use `req.originalUrl` if it exists, otherwise `req.url`. ##### :user-agent The contents of the User-Agent header of the request. ### morgan.compile(format) Compile a format string into a `format` function for use by `morgan`. A format string is a string that represents a single log line and can utilize token syntax. Tokens are referenced by `:token-name`. If tokens accept arguments, they can be passed using `[]`, for example: `:token-name[pretty]` would pass the string `'pretty'` as an argument to the token `token-name`. The function returned from `morgan.compile` takes three arguments `tokens`, `req`, and `res`, where `tokens` is an object with all defined tokens, `req` is the HTTP request and `res` is the HTTP response. The function will return a string that will be the log line, or `undefined` / `null` to skip logging. Normally formats are defined using `morgan.format(name, format)`, but for certain advanced uses, this compile function is directly available. ## Examples ### express/connect Sample app that will log all requests in the Apache combined format to STDOUT ```js var express = require('express'); var morgan = require('morgan'); var app = express(); app.use(morgan('combined')); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ### vanilla http server Sample app that will log all requests in the Apache combined format to STDOUT ```js var finalhandler = require('finalhandler'); var http = require('http'); var morgan = require('morgan'); // create "middleware" var logger = morgan('combined'); http.createServer(function (req, res) { var done = finalhandler(req, res); logger(req, res, function (err) { if (err) return done(err); // respond to request res.setHeader('content-type', 'text/plain'); res.end('hello, world!'); }); }); ``` ### write logs to a file #### single file Sample app that will log all requests in the Apache combined format to the file `access.log`. ```js var express = require('express'); var fs = require('fs'); var morgan = require('morgan'); var path = require('path'); var app = express(); // create a write stream (in append mode) var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }); // setup the logger app.use(morgan('combined', { stream: accessLogStream })); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` #### log file rotation Sample app that will log all requests in the Apache combined format to one log file per day in the `log/` directory using the [rotating-file-stream module](https://www.npmjs.com/package/rotating-file-stream). ```js var express = require('express'); var morgan = require('morgan'); var path = require('path'); var rfs = require('rotating-file-stream'); // version 2.x var app = express(); // create a rotating write stream var accessLogStream = rfs.createStream('access.log', { interval: '1d', // rotate daily path: path.join(__dirname, 'log'), }); // setup the logger app.use(morgan('combined', { stream: accessLogStream })); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ### split / dual logging The `morgan` middleware can be used as many times as needed, enabling combinations like: - Log entry on request and one on response - Log all requests to file, but errors to console - ... and more! Sample app that will log all requests to a file using Apache format, but error responses are logged to the console: ```js var express = require('express'); var fs = require('fs'); var morgan = require('morgan'); var path = require('path'); var app = express(); // log only 4xx and 5xx responses to console app.use( morgan('dev', { skip: function (req, res) { return res.statusCode < 400; }, }) ); // log all requests to access.log app.use( morgan('common', { stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }), }) ); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ### use custom token formats Sample app that will use custom token formats. This adds an ID to all requests and displays it using the `:id` token. ```js var express = require('express'); var morgan = require('morgan'); var uuid = require('uuid'); morgan.token('id', function getId(req) { return req.id; }); var app = express(); app.use(assignId); app.use(morgan(':id :method :url :response-time')); app.get('/', function (req, res) { res.send('hello, world!'); }); function assignId(req, res, next) { req.id = uuid.v4(); next(); } ``` ## License [MIT](https://github.com/expressjs/morgan/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/morgan --- ## multer middleware URL: https://expressjs.com/en/resources/middleware/multer Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written on top of [busboy](https://github.com/mscdex/busboy) for maximum efficiency. **NOTE**: Multer will not process any form which is not multipart (`multipart/form-data`). ## Installation `multer` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## Usage Multer adds a `body` object and a `file` or `files` object to the `request` object. The `body` object contains the values of the text fields of the form, the `file` or `files` object contains the files uploaded via the form. Basic usage example: Don't forget the `enctype="multipart/form-data"` in your form. ```html
``` ```javascript const express = require('express'); const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); const app = express(); app.post('/profile', upload.single('avatar'), function (req, res, next) { // req.file is the `avatar` file // req.body will hold the text fields, if there were any }); app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) { // req.files is array of `photos` files // req.body will contain the text fields, if there were any }); const uploadMiddleware = upload.fields([ { name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }, ]); app.post('/cool-profile', uploadMiddleware, function (req, res, next) { // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files // // e.g. // req.files['avatar'][0] -> File // req.files['gallery'] -> Array // // req.body will contain the text fields, if there were any }); ``` In case you need to handle a text-only multipart form, you should use the `.none()` method: ```javascript const express = require('express'); const app = express(); const multer = require('multer'); const upload = multer(); app.post('/profile', upload.none(), function (req, res, next) { // req.body contains the text fields }); ``` Here's an example on how multer is used in a HTML form. Take special note of the `enctype="multipart/form-data"` and `name="uploaded_file"` fields: ```html
``` Then in your javascript file you would add these lines to access both the file and the body. It is important that you use the `name` field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail: ```javascript const multer = require('multer'); const upload = multer({ dest: './public/data/uploads/' }); app.post('/stats', upload.single('uploaded_file'), function (req, res) { // req.file is the name of your file in the form above, here 'uploaded_file' // req.body will hold the text fields, if there were any console.log(req.file, req.body); }); ``` Complete client-side and server-side examples (browser `FormData` uploads of a blob and of an image) are in the [`examples/`](https://github.com/expressjs/multer/blob/HEAD/examples/) folder. ## API ### File information Each file contains the following information: | Key | Description | Note | | -------------- | ----------------------------------------------------------------------------------- | --------------- | | `fieldname` | Field name specified in the form | | `originalname` | Name of the file on the user's computer, or the full path when `preservePath: true` | | `encoding` | Encoding type of the file | | `mimetype` | Mime type of the file | | `size` | Size of the file in bytes | | `destination` | The folder to which the file has been saved | `DiskStorage` | | `filename` | The name of the file within the `destination` | `DiskStorage` | | `path` | The full path to the uploaded file | `DiskStorage` | | `buffer` | A `Buffer` of the entire file | `MemoryStorage` | ### `multer(opts)` Multer accepts an options object, the most basic of which is the `dest` property, which tells Multer where to upload the files. In case you omit the options object, the files will be kept in memory and never written to disk. By default, Multer will rename the files so as to avoid naming conflicts. The renaming function can be customized according to your needs. The following are the options that can be passed to Multer. | Key | Description | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `defCharset` | Default character set to use for text field values that do not declare one. Default: `'utf8'` | | `defParamCharset` | Default character set to use for values of part header parameters (e.g. filename) that are not extended parameters (that contain an explicit charset). Default: `'latin1'` | | `dest` or `storage` | Where to store the files | | `fileFilter` | Function to control which files are accepted | | `fileHwm` | `highWaterMark` of each file stream (`file.stream`). Default: busboy's default | | `highWaterMark` | `highWaterMark` of the multipart parser stream. Default: busboy's default | | `limits` | Limits of the uploaded data | | `preservePath` | Keep the full client-supplied path in `file.originalname` instead of just the base name | | `streamHandler` | Function that feeds the request body to busboy; defaults to `req.pipe(busboy)` | In an average web app, only `dest` might be required, and configured as shown in the following example. ```javascript const upload = multer({ dest: 'uploads/' }); ``` When `preservePath` is enabled, Multer passes the incoming filename through with any path segments provided by the client. This is exposed as `file.originalname`; it does not change the destination folder, create directories, or sanitize the path for you. `file.originalname` is always client-supplied and should be treated as untrusted; with `preservePath` it additionally contains the path segments the client sent. Normalize or validate it before using it in a custom `filename` or storage engine. If you want more control over your uploads, you'll want to use the `storage` option instead of `dest`. Multer ships with storage engines `DiskStorage` and `MemoryStorage`; More engines are available from third parties. #### `.single(fieldname)` Accept a single file with the name `fieldname`. The single file will be stored in `req.file`. #### `.array(fieldname[, maxCount])` Accept an array of files, all with the name `fieldname`. Optionally error out if more than `maxCount` files are uploaded. The array of files will be stored in `req.files`. Files skipped by `fileFilter` do not count towards `maxCount`. Use `limits.files` to bound how many files are read from a request. #### `.fields(fields)` Accept a mix of files, specified by `fields`. An object with arrays of files will be stored in `req.files`. `fields` should be an array of objects with `name` and optionally a `maxCount`. Example: ```javascript [ { name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }, ]; ``` #### `.none()` Accept only text fields. If any file upload is made, error with code `LIMIT_UNEXPECTED_FILE` will be issued. #### `.any()` Accepts all files that come over the wire. An array of files will be stored in `req.files`. **WARNING:** Make sure that you always handle the files that a user uploads. Never add multer as a global middleware since a malicious user could upload files to a route that you didn't anticipate. Only use this function on routes where you are handling the uploaded files. ### `storage` #### `DiskStorage` The disk storage engine gives you full control on storing files to disk. ```javascript const crypto = require('crypto'); const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, '/tmp/my-uploads'); }, filename: function (req, file, cb) { crypto.randomBytes(16, function (err, raw) { if (err) return cb(err); cb(null, file.fieldname + '-' + raw.toString('hex')); }); }, }); const upload = multer({ storage: storage }); ``` There are three options available: `destination`, `filename` and `flush`. All of them except `flush` are functions that determine where the file should be stored. `destination` is used to determine within which folder the uploaded files should be stored. This can also be given as a `string` (e.g. `'/tmp/uploads'`). If no `destination` is given, the operating system's default directory for temporary files is used. **Note:** You are responsible for creating the directory when providing `destination` as a function. When passing a string, multer will make sure that the directory is created for you. `filename` is used to determine what the file should be named inside the folder. If no `filename` is given, each file will be given a random name that doesn't include any file extension. **Note:** Multer will not append any file extension for you, your function should return a filename complete with a file extension. Each function gets passed both the request (`req`) and some information about the file (`file`) to aid with the decision. Note that `req.body` might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server. For understanding the calling convention used in the callback (needing to pass null as the first param), refer to [Node.js error handling](https://web.archive.org/web/20220417042018/https://www.joyent.com/node-js/production/design/errors) `flush` is an optional boolean. When set to `true`, the file data is flushed to disk with an `fsync` call before the upload handler runs, which prevents data loss if the process or the system crashes while the data is still sitting in the operating system's page cache. It is disabled by default because forcing a disk flush on every upload has a performance cost. Note that this syncs the file contents only; if the new directory entry must survive a crash as well, fsync the destination directory yourself. #### `MemoryStorage` The memory storage engine stores the files in memory as `Buffer` objects. It doesn't have any options. ```javascript const storage = multer.memoryStorage(); const upload = multer({ storage: storage }); ``` When using memory storage, the file info will contain a field called `buffer` that contains the entire file. **WARNING**: Uploading very large files, or relatively small files in large numbers very quickly, can cause your application to run out of memory when memory storage is used. ### `limits` An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found on [busboy's page](https://github.com/mscdex/busboy#exports). `limits` can also be a function that receives the request and returns such an object. It is called once per request, before parsing starts, so limits can depend on e.g. the authenticated user: ```javascript const upload = multer({ limits: function (req) { return { fileSize: req.user.maxUploadSize }; }, }); ``` Limits apply to the whole request; there is no per-file limit. To restrict individual files by type or name, use `fileFilter` or a custom storage engine. The following integer values are available: | Key | Description | Default | | ---------------------- | ------------------------------------------------------------------------------- | -------- | | `fieldNameSize` | Max field name size | Infinity | | `fieldSize` | Max field value size (in bytes) | 1MB | | `fields` | Max number of non-file fields | Infinity | | `fileSize` | For multipart forms, the max file size (in bytes) | Infinity | | `files` | For multipart forms, the max number of file fields | Infinity | | `parts` | For multipart forms, the max number of parts (fields + files) | Infinity | | `headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 | | `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinity | | `fieldArrayIndexLimit` | Max numeric array index accepted inside a field name (e.g. `a[3]` uses index 3) | Infinity | Specifying the limits can help protect your site against denial of service (DoS) attacks. ### `fileFilter` Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this: ```javascript function fileFilter(req, file, cb) { // The function should call `cb` with a boolean // to indicate if the file should be accepted // To reject this file pass `false`, like so: cb(null, false); // To accept the file pass `true`, like so: cb(null, true); // You can always pass an error if something goes wrong: cb(new Error("I don't have a clue!")); } ``` ### `streamHandler` By default Multer reads the request with `req.pipe(busboy)`. Some platforms consume the request body before your handlers run, so there is nothing left to pipe. Google Cloud Functions and Firebase Functions, for example, expose the already-read body as `req.rawBody`. Provide a `streamHandler` to feed busboy yourself in that case: ```javascript const upload = multer({ storage: multer.memoryStorage(), streamHandler: function (req, busboy) { if (req.rawBody) { busboy.end(req.rawBody); } else { req.pipe(busboy); } }, }); ``` The function receives the request and the busboy instance and must write the whole multipart body to busboy and end it. ## Security Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications: - `fileSize` -- set to the maximum expected file size for your use case - `files` -- set to the maximum number of files per request - `fields` -- set to the maximum number of text fields per request - `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`) - `fieldArrayIndexLimit` -- set to the largest array index your field names require (e.g. `100` for `a[99]`) ## Error handling When encountering an error, Multer will delegate the error to Express. You can display a nice error page using [the standard express way](/guide/error-handling/). If you want to catch errors specifically from Multer, you can call the middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/main/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`). Multer errors carry a `code` (e.g. `LIMIT_FILE_SIZE`) and, when the error concerns a specific field, its name in `field`. Errors about a specific file (`LIMIT_FILE_SIZE`, `LIMIT_UNEXPECTED_FILE`) also expose the client-supplied file name in `filename`; treat it as untrusted input, like `file.originalname`. ```javascript const multer = require('multer'); const upload = multer().single('avatar'); app.post('/profile', function (req, res) { upload(req, res, function (err) { if (err instanceof multer.MulterError) { // A Multer error occurred when uploading. } else if (err) { // An unknown error occurred when uploading. } // Everything went fine. }); }); ``` ## Custom storage engine For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/main/StorageEngine.md). ## License [MIT](https://github.com/expressjs/multer/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/multer [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/multer/badge [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/multer --- ## response-time middleware URL: https://expressjs.com/en/resources/middleware/response-time Response time for Node.js servers. This module creates a middleware that records the response time for requests in HTTP servers. The "response time" is defined here as the elapsed time from when a request enters this middleware to when the headers are written out to the client. ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `response-time` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API {/* eslint-disable no-unused-vars */} ```js var responseTime = require('response-time'); ``` ### responseTime([options]) Create a middleware that adds a `X-Response-Time` header to responses. If you don't want to use this module to automatically set a header, please see the section about [`responseTime(fn)`](#responsetimefn). #### Options The `responseTime` function accepts an optional `options` object that may contain any of the following keys: ##### digits The fixed number of digits to include in the output, which is always in milliseconds, defaults to `3` (ex: `2.300ms`). ##### header The name of the header to set, defaults to `X-Response-Time`. ##### suffix Boolean to indicate if units of measurement suffix should be added to the output, defaults to `true` (ex: `2.300ms` vs `2.300`). ### responseTime(fn) Create a new middleware that records the response time of a request and makes this available to your own function `fn`. The `fn` argument will be invoked as `fn(req, res, time)`, where `time` is a number in milliseconds. ## Examples ### express/connect ```js var express = require('express'); var responseTime = require('response-time'); var app = express(); app.use(responseTime()); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ### vanilla http server ```js var finalhandler = require('finalhandler'); var http = require('http'); var responseTime = require('response-time'); // create "middleware" var _responseTime = responseTime(); http.createServer(function (req, res) { var done = finalhandler(req, res); _responseTime(req, res, function (err) { if (err) return done(err); // respond to request res.setHeader('content-type', 'text/plain'); res.end('hello, world!'); }); }); ``` ### response time metrics ```js var express = require('express'); var responseTime = require('response-time'); var StatsD = require('node-statsd'); var app = express(); var stats = new StatsD(); stats.socket.on('error', function (error) { console.error(error.stack); }); app.use( responseTime(function (req, res, time) { var stat = (req.method + req.url).toLowerCase().replace(/[:.]/g, '').replace(/\//g, '_'); stats.timing(stat, time); }) ); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ## License [MIT](https://github.com/expressjs/response-time/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/response-time [node-url]: https://nodejs.org/en/download --- ## serve-favicon middleware URL: https://expressjs.com/en/resources/middleware/serve-favicon Node.js middleware for serving a favicon. A favicon is a visual cue that client software, like browsers, use to identify a site. For an example and more information, please visit [the Wikipedia article on favicons](https://en.wikipedia.org/wiki/Favicon). Why use this module? - User agents request `favicon.ico` frequently and indiscriminately, so you may wish to exclude these requests from your logs by using this middleware before your logger middleware. - This module caches the icon in memory to improve performance by skipping disk access. - This module provides an `ETag` based on the contents of the icon, rather than file system properties. - This module will serve with the most compatible `Content-Type`. **Note** This module is exclusively for serving the "default, implicit favicon", which is `GET /favicon.ico`. For additional vendor-specific icons that require HTML markup, additional middleware is required to serve the relevant files, for example [serve-static](https://npmjs.org/package/serve-static). ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `serve-favicon` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ### favicon(path, options) Create new middleware to serve a favicon from the given `path` to a favicon file. `path` may also be a `Buffer` of the icon to serve. #### Options Serve favicon accepts these properties in the options object. ##### maxAge The `cache-control` `max-age` directive in `ms`, defaulting to 1 year. This can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) module. ## Examples Typically this middleware will come very early in your stack (maybe even first) to avoid processing any other middleware if we already know the request is for `/favicon.ico`. ### express ```javascript var express = require('express'); var favicon = require('serve-favicon'); var path = require('path'); var app = express(); app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); // Add your routes here, etc. app.listen(3000); ``` ### connect ```javascript var connect = require('connect'); var favicon = require('serve-favicon'); var path = require('path'); var app = connect(); app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); // Add your middleware here, etc. app.listen(3000); ``` ### vanilla http server This middleware can be used anywhere, even outside express/connect. It takes `req`, `res`, and `callback`. ```javascript var http = require('http'); var favicon = require('serve-favicon'); var finalhandler = require('finalhandler'); var path = require('path'); var _favicon = favicon(path.join(__dirname, 'public', 'favicon.ico')); var server = http.createServer(function onRequest(req, res) { var done = finalhandler(req, res); _favicon(req, res, function onNext(err) { if (err) return done(err); // continue to process the request here, etc. res.statusCode = 404; res.end('oops'); }); }); server.listen(3000); ``` ## License [MIT](https://github.com/expressjs/serve-favicon/blob/HEAD/LICENSE) [downloads-url]: https://npmjs.org/package/serve-favicon [npm-url]: https://npmjs.org/package/serve-favicon [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/serve-favicon/badge [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/serve-favicon --- ## serve-index middleware URL: https://expressjs.com/en/resources/middleware/serve-index Serves pages that contain directory listings for a given path. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `serve-index` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var serveIndex = require('serve-index'); ``` ### serveIndex(path, options) Returns middleware that serves an index of the directory in the given `path`. The `path` is based off the `req.url` value, so a `req.url` of `'/some/dir` with a `path` of `'public'` will look at `'public/some/dir'`. If you are using something like `express`, you can change the URL "base" with `app.use` (see the express example). #### Options Serve index accepts these properties in the options object. ##### filter Apply this filter function to files. Defaults to `false`. The `filter` function is called for each file, with the signature `filter(filename, index, files, dir)` where `filename` is the name of the file, `index` is the array index, `files` is the array of files and `dir` is the absolute path the file is located (and thus, the directory the listing is for). ##### hidden Display hidden (dot) files. Defaults to `false`. ##### icons Display icons. Defaults to `false`. ##### stylesheet Optional path to a CSS stylesheet. Defaults to a built-in stylesheet. ##### template Optional path to an HTML template or a function that will render a HTML string. Defaults to a built-in template. When given a string, the string is used as a file path to load and then the following tokens are replaced in templates: - `{directory}` with the name of the directory. - `{files}` with the HTML of an unordered list of file links. - `{linked-path}` with the HTML of a link to the directory. - `{style}` with the specified stylesheet and embedded images. When given as a function, the function is called as `template(locals, callback)` and it needs to invoke `callback(error, htmlString)`. The following are the provided locals: - `directory` is the directory being displayed (where `/` is the root). - `displayIcons` is a Boolean for if icons should be rendered or not. - `fileList` is a sorted array of files in the directory. The array contains objects with the following properties: - `name` is the relative name for the file. - `stat` is a `fs.Stats` object for the file. - `path` is the full filesystem path to `directory`. - `style` is the default stylesheet or the contents of the `stylesheet` option. - `viewName` is the view name provided by the `view` option. ##### view Display mode. `tiles` and `details` are available. Defaults to `tiles`. ## Examples ### Serve directory indexes with vanilla node.js http server ```js var finalhandler = require('finalhandler'); var http = require('http'); var serveIndex = require('serve-index'); var serveStatic = require('serve-static'); // Serve directory indexes for public/ftp folder (with icons) var index = serveIndex('public/ftp', { icons: true }); // Serve up public/ftp folder files var serve = serveStatic('public/ftp'); // Create server var server = http.createServer(function onRequest(req, res) { var done = finalhandler(req, res); serve(req, res, function onNext(err) { if (err) return done(err); index(req, res, done); }); }); // Listen server.listen(3000); ``` ### Serve directory indexes with express ```js var express = require('express'); var serveIndex = require('serve-index'); var app = express(); // Serve URLs like /ftp/thing as public/ftp/thing // The express.static serves the file contents // The serveIndex is this module serving the directory app.use('/ftp', express.static('public/ftp'), serveIndex('public/ftp', { icons: true })); // Listen app.listen(3000); ``` ## License [MIT](https://github.com/expressjs/serve-index/blob/HEAD/LICENSE). The [Silk](https://web.archive.org/web/20230105212205/http://www.famfamfam.com/lab/icons/silk/) icons are created by/copyright of [FAMFAMFAM](https://web.archive.org/web/20230109095739/http://www.famfamfam.com/). [appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-index [downloads-url]: https://npmjs.org/package/serve-index [npm-url]: https://npmjs.org/package/serve-index --- ## serve-static middleware URL: https://expressjs.com/en/resources/middleware/serve-static ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `serve-static` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js const serveStatic = require('serve-static'); ``` ### serveStatic(root, options) Create a new middleware function to serve files from within a given root directory. The file to serve will be determined by combining `req.url` with the provided root directory. When a file is not found, instead of sending a 404 response, this module will instead call `next()` to move on to the next middleware, allowing for stacking and fall-backs. #### Options ##### acceptRanges Enable or disable accepting ranged requests, defaults to true. Disabling this will not send `Accept-Ranges` and ignore the contents of the `Range` request header. ##### cacheControl Enable or disable setting `Cache-Control` response header, defaults to true. Disabling this will ignore the `immutable` and `maxAge` options. ##### dotfiles Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). Note this check is done on the path itself without checking if the path actually exists on the disk. If `root` is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when set to "deny"). - `'allow'` No special treatment for dotfiles. - `'deny'` Deny a request for a dotfile and 403/`next()`. - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. The default value is `'ignore'`. ##### etag Enable or disable etag generation, defaults to true. ##### extensions Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for. The first that exists will be served. Example: `['html', 'htm']`. The default value is `false`. ##### fallthrough Set the middleware to have client errors fall-through as just unhandled requests, otherwise forward a client error. The difference is that client errors like a bad request or a request to a non-existent file will cause this middleware to simply `next()` to your next middleware when this value is `true`. When this value is `false`, these errors (even 404s), will invoke `next(err)`. Typically `true` is desired such that multiple physical directories can be mapped to the same web address or for routes to fill in non-existent files. The value `false` can be used if this middleware is mounted at a path that is 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. The default value is `true`. ##### immutable Enable or disable the `immutable` directive in the `Cache-Control` response header, defaults to `false`. If set to `true`, 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. ##### index By default this module will send "index.html" files in response to a request on a directory. To disable this set `false` or to supply a new index pass a string or an array in preferred order. ##### lastModified Enable or disable `Last-Modified` header, defaults to true. Uses the file system's last modified value. ##### maxAge Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) module. ##### redirect Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. ##### setHeaders Function to set custom headers on response. Alterations to the headers need to occur synchronously. The function is called as `fn(res, path, stat)`, where the arguments are: - `res` the response object - `path` the file path that is being sent - `stat` the stat object of the file that is being sent ## Examples ### Serve files with vanilla node.js http server ```js const finalhandler = require('finalhandler'); const http = require('http'); const serveStatic = require('serve-static'); // Serve up public/ftp folder const serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] }); // Create server const server = http.createServer((req, res) => { serve(req, res, finalhandler(req, res)); }); // Listen server.listen(3000); ``` ### Serve all files as downloads ```js const contentDisposition = require('content-disposition'); const finalhandler = require('finalhandler'); const http = require('http'); const serveStatic = require('serve-static'); // Serve up public/ftp folder const serve = serveStatic('public/ftp', { index: false, setHeaders: setHeaders, }); // Set header to force download function setHeaders(res, path) { res.setHeader('Content-Disposition', contentDisposition(path)); } // Create server const server = http.createServer((req, res) => { serve(req, res, finalhandler(req, res)); }); // Listen server.listen(3000); ``` ### Serving using express #### Simple This is a simple example of using Express. ```js const express = require('express'); const serveStatic = require('serve-static'); const app = express(); app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] })); app.listen(3000); ``` #### Multiple roots This example shows a simple way to search through multiple directories. Files are searched for in `public-optimized/` first, then `public/` second as a fallback. ```js const express = require('express'); const path = require('path'); const serveStatic = require('serve-static'); const app = express(); app.use(serveStatic(path.join(__dirname, 'public-optimized'))); app.use(serveStatic(path.join(__dirname, 'public'))); app.listen(3000); ``` #### Different settings for paths This example shows how to set a different max age depending on the served file. In this example, HTML files are not cached, while everything else is for 1 day. ```js const express = require('express'); const path = require('path'); const serveStatic = require('serve-static'); const app = express(); app.use( serveStatic(path.join(__dirname, 'public'), { maxAge: '1d', setHeaders: setCustomCacheControl, }) ); app.listen(3000); function setCustomCacheControl(res, file) { if (path.extname(file) === '.html') { // Custom Cache-Control for HTML files res.setHeader('Cache-Control', 'public, max-age=0'); } } ``` ## License [MIT](https://github.com/expressjs/serve-static/blob/HEAD/LICENSE) [node-url]: https://nodejs.org/en/download/ [npm-url]: https://npmjs.org/package/serve-static --- ## session middleware URL: https://expressjs.com/en/resources/middleware/session ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `express-session` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var session = require('express-session'); ``` ### session(options) Create a session middleware with the given `options`. **Note** Session data is _not_ saved in the cookie itself, just the session ID. Session data is stored server-side. **Note** Since version 1.5.0, the [`cookie-parser` middleware](https://www.npmjs.com/package/cookie-parser) no longer needs to be used for this module to work. This module now directly reads and writes cookies on `req`/`res`. Using `cookie-parser` may result in issues if the `secret` is not the same between this module and `cookie-parser`. **Warning** The default server-side session storage, `MemoryStore`, is _purposely_ not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing. For a list of stores, see [compatible session stores](#compatible-session-stores). #### Options `express-session` accepts these properties in the options object. ##### cookie Settings object for the session ID cookie. The default value is `{ path: '/', httpOnly: true, secure: false, maxAge: null }`. In addition to providing a static object, you can also pass a callback function to dynamically generate the cookie options for each request. The callback receives the `req` object as its argument and should return an object containing the cookie settings. ```js var app = express(); app.use( session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: function (req) { var match = req.url.match(/^\/([^/]+)/); return { path: match ? '/' + match[1] : '/', httpOnly: true, secure: req.secure || false, maxAge: 60000, }; }, }) ); ``` The following are options that can be set in this object. ##### cookie.domain Specifies the value for the `Domain` `Set-Cookie` attribute. By default, no domain is set, and most clients will consider the cookie to apply to only the current domain. ##### cookie.expires Specifies the `Date` object to be the value for the `Expires` `Set-Cookie` attribute. By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application. **Note** If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used. **Note** The `expires` option should not be set directly; instead only use the `maxAge` option. ##### cookie.httpOnly Specifies the `boolean` value for the `HttpOnly` `Set-Cookie` attribute. When truthy, the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is set. **Note** be careful when setting this to `true`, as compliant clients will not allow client-side JavaScript to see the cookie in `document.cookie`. ##### cookie.maxAge Specifies the `number` (in milliseconds) to use when calculating the `Expires` `Set-Cookie` attribute. This is done by taking the current server time and adding `maxAge` milliseconds to the value to calculate an `Expires` datetime. By default, no maximum age is set. **Note** If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used. ##### cookie.partitioned Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`][rfc-cutler-httpbis-partitioned-cookies] attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the `Partitioned` attribute is not set. **Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it. More information about can be found in [the proposal](https://github.com/privacycg/CHIPS). ##### cookie.path Specifies the value for the `Path` `Set-Cookie`. By default, this is set to `'/'`, which is the root path of the domain. Since 1.19.1, path matching follows [RFC 6265 section 5.1.4][rfc-6265-5.1.4]. This means the session middleware will only activate when the request path is an exact match or falls under a segment boundary of the cookie path. For example, a cookie path of `/admin` will match `/admin` and `/admin/users` but will **not** match `/administrator`. Prior versions used a simple prefix check that did not enforce segment boundaries. ##### cookie.priority Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1]. - `'low'` will set the `Priority` attribute to `Low`. - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. - `'high'` will set the `Priority` attribute to `High`. More information about the different priority levels can be found in [the specification][rfc-west-cookie-priority-00-4.1]. **Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it. ##### cookie.sameSite Specifies the `boolean` or `string` to be the value for the `SameSite` `Set-Cookie` attribute. By default, this is `false`. - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. - `false` will not set the `SameSite` attribute. - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. - `'auto'` will set the `SameSite` attribute to `None` for secure connections and `Lax` for non-secure connections. More information about the different enforcement levels can be found in [the specification][rfc-6265bis-03-4.1.2.7]. **Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it. **Note** There is a [draft spec](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01) that requires that the `Secure` attribute be set to `true` when the `SameSite` attribute has been set to `'none'`. Some web browsers or other clients may be adopting this specification. The `cookie.sameSite` option can also be set to the special value `'auto'` to have this setting automatically match the determined security of the connection. When the connection is secure (HTTPS), the `SameSite` attribute will be set to `None` to enable cross-site usage. When the connection is not secure (HTTP), the `SameSite` attribute will be set to `Lax` for better security while maintaining functionality. This is useful when the Express `"trust proxy"` setting is properly setup to simplify development vs production configuration, particularly for SAML authentication scenarios. ##### cookie.secure Specifies the `boolean` value for the `Secure` `Set-Cookie` attribute. When truthy, the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. **Note** be careful when setting this to `true`, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection. Please note that `secure: true` is a **recommended** option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If `secure` is set, and you access your site over HTTP, the cookie will not be set. If you have your node.js behind a proxy and are using `secure: true`, you need to set "trust proxy" in express: ```js var app = express(); app.set('trust proxy', 1); // trust first proxy app.use( session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true }, }) ); ``` For using secure cookies in production, but allowing for testing in development, the following is an example of enabling this setup based on `NODE_ENV` in express: ```js var app = express(); var sess = { secret: 'keyboard cat', cookie: {}, }; if (app.get('env') === 'production') { app.set('trust proxy', 1); // trust first proxy sess.cookie.secure = true; // serve secure cookies } app.use(session(sess)); ``` The `cookie.secure` option can also be set to the special value `'auto'` to have this setting automatically match the determined security of the connection. Be careful when using this setting if the site is available both as HTTP and HTTPS, as once the cookie is set on HTTPS, it will no longer be visible over HTTP. This is useful when the Express `"trust proxy"` setting is properly setup to simplify development vs production configuration. ##### genid Function to call to generate a new session ID. Provide a function that returns a string that will be used as a session ID. The function is given `req` as the first argument if you want to use some value attached to `req` when generating the ID. The default value is a function which uses the `uid-safe` library to generate IDs. **NOTE** be careful to generate unique IDs so your sessions do not conflict. ```js app.use( session({ genid: function (req) { return genuuid(); // use UUIDs for session IDs }, secret: 'keyboard cat', }) ); ``` ##### name The name of the session ID cookie to set in the response (and read from in the request). The default value is `'connect.sid'`. **Note** if you have multiple apps running on the same hostname (this is just the name, i.e. `localhost` or `127.0.0.1`; different schemes and ports do not name a different hostname), then you need to separate the session cookies from each other. The simplest method is to simply set different `name`s per app. ##### proxy Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto" header). The default value is `undefined`. - `true` The "X-Forwarded-Proto" header will be used. - `false` All headers are ignored and the connection is considered secure only if there is a direct TLS/SSL connection. - `undefined` Uses the "trust proxy" setting from express ##### resave Forces the session to be saved back to the session store, even if the session was never modified during the request. Depending on your store this may be necessary, but it can also create race conditions where a client makes two parallel requests to your server and changes made to the session in one request may get overwritten when the other request ends, even if it made no changes (this behavior also depends on what store you're using). The default value is `true`, but using the default has been deprecated, as the default will change in the future. Please research into this setting and choose what is appropriate to your use-case. Typically, you'll want `false`. How do I know if this is necessary for my store? The best way to know is to check with your store if it implements the `touch` method. If it does, then you can safely set `resave: false`. If it does not implement the `touch` method and your store sets an expiration date on stored sessions, then you likely need `resave: true`. ##### rolling Force the session identifier cookie to be set on every response. The expiration is reset to the original [`maxAge`](#cookiemaxage), resetting the expiration countdown. The default value is `false`. With this enabled, the session identifier cookie will expire in [`maxAge`](#cookiemaxage) since the last response was sent instead of in [`maxAge`](#cookiemaxage) since the session was last modified by the server. This is typically used in conjunction with short, non-session-length [`maxAge`](#cookiemaxage) values to provide a quick timeout of the session data with reduced potential of it occurring during on going server interactions. **Note** When this option is set to `true` but the `saveUninitialized` option is set to `false`, the cookie will not be set on a response with an uninitialized session. This option only modifies the behavior when an existing session was loaded for the request. ##### saveUninitialized Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified. Choosing `false` is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie. Choosing `false` will also help with race conditions where a client makes multiple parallel requests without a session. The default value is `true`, but using the default has been deprecated, as the default will change in the future. Please research into this setting and choose what is appropriate to your use-case. **Note** if you are using Session in conjunction with PassportJS, Passport will add an empty Passport object to the session for use after a user is authenticated, which will be treated as a modification to the session, causing it to be saved. _This has been fixed in PassportJS 0.3.0_ ##### secret **Required option** This is the secret used to sign the session ID cookie. The secret can be any type of value that is supported by Node.js `crypto.createHmac` (like a string or a `Buffer`). This can be either a single secret, or an array of multiple secrets. If an array of secrets is provided, only the first element will be used to sign the session ID cookie, while all the elements will be considered when verifying the signature in requests. The secret itself should be not easily parsed by a human and would best be a random set of characters. A best practice may include: - The use of environment variables to store the secret, ensuring the secret itself does not exist in your repository. - Periodic updates of the secret, while ensuring the previous secret is in the array. Using a secret that cannot be guessed will reduce the ability to hijack a session to only guessing the session ID (as determined by the `genid` option). Changing the secret value will invalidate all existing sessions. In order to rotate the secret without invalidating sessions, provide an array of secrets, with the new secret as first element of the array, and including previous secrets as the later elements. **Note** HMAC-256 is used to sign the session ID. For this reason, the secret should contain at least 32 bytes of entropy. ##### store The session store instance, defaults to a new `MemoryStore` instance. ##### unset Control the result of unsetting `req.session` (through `delete`, setting to `null`, etc.). The default value is `'keep'`. - `'destroy'` The session will be destroyed (deleted) when the response ends. - `'keep'` The session in the store will be kept, but modifications made during the request are ignored and not saved. ### req.session To store or access session data, simply use the request property `req.session`, which is (generally) serialized as JSON by the store, so nested objects are typically fine. For example below is a user-specific view counter: ```js // Use the session middleware app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 } })); // Access the session as req.session app.get('/', function (req, res, next) { if (req.session.views) { req.session.views++; res.setHeader('Content-Type', 'text/html'); res.write('

views: ' + req.session.views + '

'); res.write('

expires in: ' + req.session.cookie.maxAge / 1000 + 's

'); res.end(); } else { req.session.views = 1; res.end('welcome to the session demo. refresh!'); } }); ``` #### Session.regenerate(callback) To regenerate the session simply invoke the method. Once complete, a new SID and `Session` instance will be initialized at `req.session` and the `callback` will be invoked. ```js req.session.regenerate(function (err) { // will have a new session here }); ``` #### Session.destroy(callback) Destroys the session and will unset the `req.session` property. Once complete, the `callback` will be invoked. ```js req.session.destroy(function (err) { // cannot access session here }); ``` #### Session.reload(callback) Reloads the session data from the store and re-populates the `req.session` object. Once complete, the `callback` will be invoked. ```js req.session.reload(function (err) { // session updated }); ``` #### Session.save(callback) Save the session back to the store, replacing the contents on the store with the contents in memory (though a store may do something else--consult the store's documentation for exact behavior). This method is automatically called at the end of the HTTP response if the session data has been altered (though this behavior can be altered with various options in the middleware constructor). Because of this, typically this method does not need to be called. There are some cases where it is useful to call this method, for example, redirects, long-lived requests or in WebSockets. ```js req.session.save(function (err) { // session saved }); ``` #### Session.touch() Updates the `.maxAge` property. Typically this is not necessary to call, as the session middleware does this for you. ### req.session.id Each session has a unique ID associated with it. This property is an alias of [`req.sessionID`](#reqsessionid-1) and cannot be modified. It has been added to make the session ID accessible from the `session` object. ### req.session.cookie Each session has a unique cookie object accompany it. This allows you to alter the session cookie per visitor. For example we can set `req.session.cookie.expires` to `false` to enable the cookie to remain for only the duration of the user-agent. #### Cookie.maxAge Alternatively `req.session.cookie.maxAge` will return the time remaining in milliseconds, which we may also re-assign a new value to adjust the `.expires` property appropriately. The following are essentially equivalent ```js var hour = 3600000; req.session.cookie.expires = new Date(Date.now() + hour); req.session.cookie.maxAge = hour; ``` For example when `maxAge` is set to `60000` (one minute), and 30 seconds has elapsed it will return `30000` until the current request has completed, at which time `req.session.touch()` is called to reset `req.session.cookie.maxAge` to its original value. ```js req.session.cookie.maxAge; // => 30000 ``` #### Cookie.originalMaxAge The `req.session.cookie.originalMaxAge` property returns the original `maxAge` (time-to-live), in milliseconds, of the session cookie. ### req.sessionID To get the ID of the loaded session, access the request property `req.sessionID`. This is simply a read-only value set when a session is loaded/created. ## Session Store Implementation Every session store _must_ be an `EventEmitter` and implement specific methods. The following methods are the list of **required**, **recommended**, and **optional**. - Required methods are ones that this module will always call on the store. - Recommended methods are ones that this module will call on the store if available. - Optional methods are ones this module does not call at all, but helps present uniform stores to users. For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. ### store.all(callback) **Optional** This optional method is used to get all sessions in the store as an array. The `callback` should be called as `callback(error, sessions)`. ### store.destroy(sid, callback) **Required** This required method is used to destroy/delete a session from the store given a session ID (`sid`). The `callback` should be called as `callback(error)` once the session is destroyed. ### store.clear(callback) **Optional** This optional method is used to delete all sessions from the store. The `callback` should be called as `callback(error)` once the store is cleared. ### store.length(callback) **Optional** This optional method is used to get the count of all sessions in the store. The `callback` should be called as `callback(error, len)`. ### store.get(sid, callback) **Required** This required method is used to get a session from the store given a session ID (`sid`). The `callback` should be called as `callback(error, session)`. The `session` argument should be a session if found, otherwise `null` or `undefined` if the session was not found (and there was no error). A special case is made when `error.code === 'ENOENT'` to act like `callback(null, null)`. ### store.set(sid, session, callback) **Required** This required method is used to upsert a session into the store given a session ID (`sid`) and session (`session`) object. The callback should be called as `callback(error)` once the session has been set in the store. ### store.touch(sid, session, callback) **Recommended** This recommended method is used to "touch" a given session given a session ID (`sid`) and session (`session`) object. The `callback` should be called as `callback(error)` once the session has been touched. This is primarily used when the store will automatically delete idle sessions and this method is used to signal to the store the given session is active, potentially resetting the idle timer. ## Compatible Session Stores The following modules implement a session store that is compatible with this module. Please make a PR to add additional modules :) [![★][aerospike-session-store-image] aerospike-session-store][aerospike-session-store-url] A session store using [Aerospike](http://www.aerospike.com/). [aerospike-session-store-url]: https://www.npmjs.com/package/aerospike-session-store [![★][better-sqlite3-session-store-image] better-sqlite3-session-store][better-sqlite3-session-store-url] A session store based on [better-sqlite3](https://github.com/JoshuaWise/better-sqlite3). [better-sqlite3-session-store-url]: https://www.npmjs.com/package/better-sqlite3-session-store [![★][cassandra-store-image] cassandra-store][cassandra-store-url] An Apache Cassandra-based session store. [cassandra-store-url]: https://www.npmjs.com/package/cassandra-store [![★][cluster-store-image] cluster-store][cluster-store-url] A wrapper for using in-process / embedded stores - such as SQLite (via knex), leveldb, files, or memory - with node cluster (desirable for Raspberry Pi 2 and other multi-core embedded devices). [cluster-store-url]: https://www.npmjs.com/package/cluster-store [![★][connect-arango-image] connect-arango][connect-arango-url] An ArangoDB-based session store. [connect-arango-url]: https://www.npmjs.com/package/connect-arango [![★][connect-azuretables-image] connect-azuretables][connect-azuretables-url] An [Azure Table Storage](https://azure.microsoft.com/en-gb/services/storage/tables/)-based session store. [connect-azuretables-url]: https://www.npmjs.com/package/connect-azuretables [![★][connect-cloudant-store-image] connect-cloudant-store][connect-cloudant-store-url] An [IBM Cloudant](https://cloudant.com/)-based session store. [connect-cloudant-store-url]: https://www.npmjs.com/package/connect-cloudant-store [![★][connect-cosmosdb-image] connect-cosmosdb][connect-cosmosdb-url] An Azure [Cosmos DB](https://azure.microsoft.com/en-us/products/cosmos-db/)-based session store. [connect-cosmosdb-url]: https://www.npmjs.com/package/connect-cosmosdb [![★][connect-couchbase-image] connect-couchbase][connect-couchbase-url] A [couchbase](http://www.couchbase.com/)-based session store. [connect-couchbase-url]: https://www.npmjs.com/package/connect-couchbase [![★][connect-datacache-image] connect-datacache][connect-datacache-url] An [IBM Bluemix Data Cache](http://www.ibm.com/cloud-computing/bluemix/)-based session store. [connect-datacache-url]: https://www.npmjs.com/package/connect-datacache [![★][@google-cloud/connect-datastore-image] @google-cloud/connect-datastore][@google-cloud/connect-datastore-url] A [Google Cloud Datastore](https://cloud.google.com/datastore/docs/concepts/overview)-based session store. [@google-cloud/connect-datastore-url]: https://www.npmjs.com/package/@google-cloud/connect-datastore [![★][connect-db2-image] connect-db2][connect-db2-url] An IBM DB2-based session store built using [ibm_db](https://www.npmjs.com/package/ibm_db) module. [connect-db2-url]: https://www.npmjs.com/package/connect-db2 [![★][connect-dynamodb-image] connect-dynamodb][connect-dynamodb-url] A DynamoDB-based session store. [connect-dynamodb-url]: https://www.npmjs.com/package/connect-dynamodb [![★][@google-cloud/connect-firestore-image] @google-cloud/connect-firestore][@google-cloud/connect-firestore-url] A [Google Cloud Firestore](https://cloud.google.com/firestore/docs/overview)-based session store. [@google-cloud/connect-firestore-url]: https://www.npmjs.com/package/@google-cloud/connect-firestore [![★][connect-hazelcast-image] connect-hazelcast][connect-hazelcast-url] Hazelcast session store for Connect and Express. [connect-hazelcast-url]: https://www.npmjs.com/package/connect-hazelcast [![★][connect-loki-image] connect-loki][connect-loki-url] A Loki.js-based session store. [connect-loki-url]: https://www.npmjs.com/package/connect-loki [![★][connect-lowdb-image] connect-lowdb][connect-lowdb-url] A lowdb-based session store. [connect-lowdb-url]: https://www.npmjs.com/package/connect-lowdb [![★][connect-memcached-image] connect-memcached][connect-memcached-url] A memcached-based session store. [connect-memcached-url]: https://www.npmjs.com/package/connect-memcached [![★][connect-memjs-image] connect-memjs][connect-memjs-url] A memcached-based session store using [memjs](https://www.npmjs.com/package/memjs) as the memcached client. [connect-memjs-url]: https://www.npmjs.com/package/connect-memjs [![★][connect-ml-image] connect-ml][connect-ml-url] A MarkLogic Server-based session store. [connect-ml-url]: https://www.npmjs.com/package/connect-ml [![★][connect-monetdb-image] connect-monetdb][connect-monetdb-url] A MonetDB-based session store. [connect-monetdb-url]: https://www.npmjs.com/package/connect-monetdb [![★][connect-mongo-image] connect-mongo][connect-mongo-url] A MongoDB-based session store. [connect-mongo-url]: https://www.npmjs.com/package/connect-mongo [![★][connect-mongodb-session-image] connect-mongodb-session][connect-mongodb-session-url] Lightweight MongoDB-based session store built and maintained by MongoDB. [connect-mongodb-session-url]: https://www.npmjs.com/package/connect-mongodb-session [![★][connect-mssql-v2-image] connect-mssql-v2][connect-mssql-v2-url] A Microsoft SQL Server-based session store based on [connect-mssql](https://www.npmjs.com/package/connect-mssql). [connect-mssql-v2-url]: https://www.npmjs.com/package/connect-mssql-v2 [![★][connect-neo4j-image] connect-neo4j][connect-neo4j-url] A [Neo4j](https://neo4j.com)-based session store. [connect-neo4j-url]: https://www.npmjs.com/package/connect-neo4j [![★][connect-ottoman-image] connect-ottoman][connect-ottoman-url] A [couchbase ottoman](http://www.couchbase.com/)-based session store. [connect-ottoman-url]: https://www.npmjs.com/package/connect-ottoman [![★][connect-pg-simple-image] connect-pg-simple][connect-pg-simple-url] A PostgreSQL-based session store. [connect-pg-simple-url]: https://www.npmjs.com/package/connect-pg-simple [![★][connect-redis-image] connect-redis][connect-redis-url] A Redis-based session store. [connect-redis-url]: https://www.npmjs.com/package/connect-redis [![★][connect-session-firebase-image] connect-session-firebase][connect-session-firebase-url] A session store based on the [Firebase Realtime Database](https://firebase.google.com/docs/database/) [connect-session-firebase-url]: https://www.npmjs.com/package/connect-session-firebase [![★][connect-session-knex-image] connect-session-knex][connect-session-knex-url] A session store using [Knex.js](http://knexjs.org/), which is a SQL query builder for PostgreSQL, MySQL, MariaDB, SQLite3, and Oracle. [connect-session-knex-url]: https://www.npmjs.com/package/connect-session-knex [![★][connect-session-sequelize-image] connect-session-sequelize][connect-session-sequelize-url] A session store using [Sequelize.js](https://sequelize.org/), which is a Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL. [connect-session-sequelize-url]: https://www.npmjs.com/package/connect-session-sequelize [![★][connect-sqlite3-image] connect-sqlite3][connect-sqlite3-url] A [SQLite3](https://github.com/mapbox/node-sqlite3) session store modeled after the TJ's `connect-redis` store. [connect-sqlite3-url]: https://www.npmjs.com/package/connect-sqlite3 [![★][connect-typeorm-image] connect-typeorm][connect-typeorm-url] A [TypeORM](https://github.com/typeorm/typeorm)-based session store. [connect-typeorm-url]: https://www.npmjs.com/package/connect-typeorm [![★][couchdb-expression-image] couchdb-expression][couchdb-expression-url] A [CouchDB](https://couchdb.apache.org/)-based session store. [couchdb-expression-url]: https://www.npmjs.com/package/couchdb-expression [![★][dynamodb-store-image] dynamodb-store][dynamodb-store-url] A DynamoDB-based session store. [dynamodb-store-url]: https://www.npmjs.com/package/dynamodb-store [![★][express-etcd-image] express-etcd][express-etcd-url] An [etcd](https://github.com/stianeikeland/node-etcd) based session store. [express-etcd-url]: https://www.npmjs.com/package/express-etcd [![★][express-mysql-session-image] express-mysql-session][express-mysql-session-url] A session store using native [MySQL](https://www.mysql.com/) via the [node-mysql](https://github.com/felixge/node-mysql) module. [express-mysql-session-url]: https://www.npmjs.com/package/express-mysql-session [![★][express-nedb-session-image] express-nedb-session][express-nedb-session-url] A NeDB-based session store. [express-nedb-session-url]: https://www.npmjs.com/package/express-nedb-session [![★][express-oracle-session-image] express-oracle-session][express-oracle-session-url] A session store using native [oracle](https://www.oracle.com/) via the [node-oracledb](https://www.npmjs.com/package/oracledb) module. [express-oracle-session-url]: https://www.npmjs.com/package/express-oracle-session [![★][express-session-cache-manager-image] express-session-cache-manager][express-session-cache-manager-url] A store that implements [cache-manager](https://www.npmjs.com/package/cache-manager), which supports a [variety of storage types](https://www.npmjs.com/package/cache-manager#store-engines). [express-session-cache-manager-url]: https://www.npmjs.com/package/express-session-cache-manager [![★][express-session-etcd3-image] express-session-etcd3][express-session-etcd3-url] An [etcd3](https://github.com/mixer/etcd3) based session store. [express-session-etcd3-url]: https://www.npmjs.com/package/express-session-etcd3 [![★][express-session-level-image] express-session-level][express-session-level-url] A [LevelDB](https://github.com/Level/levelup) based session store. [express-session-level-url]: https://www.npmjs.com/package/express-session-level [![★][express-session-rsdb-image] express-session-rsdb][express-session-rsdb-url] Session store based on Rocket-Store: A very simple, super fast and yet powerful, flat file database. [express-session-rsdb-url]: https://www.npmjs.com/package/express-session-rsdb [![★][express-sessions-image] express-sessions][express-sessions-url] A session store supporting both MongoDB and Redis. [express-sessions-url]: https://www.npmjs.com/package/express-sessions [![★][firestore-store-image] firestore-store][firestore-store-url] A [Firestore](https://github.com/hendrysadrak/firestore-store)-based session store. [firestore-store-url]: https://www.npmjs.com/package/firestore-store [![★][fortune-session-image] fortune-session][fortune-session-url] A [Fortune.js](https://github.com/fortunejs/fortune) based session store. Supports all backends supported by Fortune (MongoDB, Redis, Postgres, NeDB). [fortune-session-url]: https://www.npmjs.com/package/fortune-session [![★][hazelcast-store-image] hazelcast-store][hazelcast-store-url] A Hazelcast-based session store built on the [Hazelcast Node Client](https://www.npmjs.com/package/hazelcast-client). [hazelcast-store-url]: https://www.npmjs.com/package/hazelcast-store [![★][level-session-store-image] level-session-store][level-session-store-url] A LevelDB-based session store. [level-session-store-url]: https://www.npmjs.com/package/level-session-store [![★][lowdb-session-store-image] lowdb-session-store][lowdb-session-store-url] A [lowdb](https://www.npmjs.com/package/lowdb)-based session store. [lowdb-session-store-url]: https://www.npmjs.com/package/lowdb-session-store [![★][medea-session-store-image] medea-session-store][medea-session-store-url] A Medea-based session store. [medea-session-store-url]: https://www.npmjs.com/package/medea-session-store [![★][memorystore-image] memorystore][memorystore-url] A memory session store made for production. [memorystore-url]: https://www.npmjs.com/package/memorystore [![★][mssql-session-store-image] mssql-session-store][mssql-session-store-url] A SQL Server-based session store. [mssql-session-store-url]: https://www.npmjs.com/package/mssql-session-store [![★][nedb-session-store-image] nedb-session-store][nedb-session-store-url] An alternate NeDB-based (either in-memory or file-persisted) session store. [nedb-session-store-url]: https://www.npmjs.com/package/nedb-session-store [![★][@quixo3/prisma-session-store-image] @quixo3/prisma-session-store][@quixo3/prisma-session-store-url] A session store for the [Prisma Framework](https://www.prisma.io). [@quixo3/prisma-session-store-url]: https://www.npmjs.com/package/@quixo3/prisma-session-store [![★][restsession-image] restsession][restsession-url] Store sessions utilizing a RESTful API [restsession-url]: https://www.npmjs.com/package/restsession [![★][sequelstore-connect-image] sequelstore-connect][sequelstore-connect-url] A session store using [Sequelize.js](https://sequelize.org/). [sequelstore-connect-url]: https://www.npmjs.com/package/sequelstore-connect [![★][session-file-store-image] session-file-store][session-file-store-url] A file system-based session store. [session-file-store-url]: https://www.npmjs.com/package/session-file-store [![★][session-pouchdb-store-image] session-pouchdb-store][session-pouchdb-store-url] Session store for PouchDB / CouchDB. Accepts embedded, custom, or remote PouchDB instance and realtime synchronization. [session-pouchdb-store-url]: https://www.npmjs.com/package/session-pouchdb-store [![★][@databunker/session-store-image] @databunker/session-store][@databunker/session-store-url] A [Databunker](https://databunker.org/)-based encrypted session store. [@databunker/session-store-url]: https://www.npmjs.com/package/@databunker/session-store [![★][sessionstore-image] sessionstore][sessionstore-url] A session store that works with various databases. [sessionstore-url]: https://www.npmjs.com/package/sessionstore [![★][tch-nedb-session-image] tch-nedb-session][tch-nedb-session-url] A file system session store based on NeDB. [tch-nedb-session-url]: https://www.npmjs.com/package/tch-nedb-session ## Examples ### View counter A simple example using `express-session` to store page views for a user. ```js var express = require('express'); var parseurl = require('parseurl'); var session = require('express-session'); var app = express(); app.use( session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, }) ); app.use(function (req, res, next) { if (!req.session.views) { req.session.views = {}; } // get the url pathname var pathname = parseurl(req).pathname; // count the views req.session.views[pathname] = (req.session.views[pathname] || 0) + 1; next(); }); app.get('/foo', function (req, res, next) { res.send('you viewed this page ' + req.session.views['/foo'] + ' times'); }); app.get('/bar', function (req, res, next) { res.send('you viewed this page ' + req.session.views['/bar'] + ' times'); }); app.listen(3000); ``` ### User login A simple example using `express-session` to keep a user log in session. ```js var escapeHtml = require('escape-html'); var express = require('express'); var session = require('express-session'); var app = express(); app.use( session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, }) ); // middleware to test if authenticated function isAuthenticated(req, res, next) { if (req.session.user) next(); else next('route'); } app.get('/', isAuthenticated, function (req, res) { // this is only called when there is an authentication user due to isAuthenticated res.send('hello, ' + escapeHtml(req.session.user) + '!' + ' Logout'); }); app.get('/', function (req, res) { res.send( '
' + 'Username:
' + 'Password:
' + '
' ); }); app.post('/login', express.urlencoded({ extended: false }), function (req, res) { // login logic to validate req.body.user and req.body.pass // would be implemented here. for this example any combo works // regenerate the session, which is good practice to help // guard against forms of session fixation req.session.regenerate(function (err) { if (err) next(err); // store user information in session, typically a user id req.session.user = req.body.user; // save the session before redirection to ensure page // load does not happen before session is saved req.session.save(function (err) { if (err) return next(err); res.redirect('/'); }); }); }); app.get('/logout', function (req, res, next) { // logout logic // clear the user from the session object and save. // this will ensure that re-using the old session id // does not have a logged in user req.session.user = null; req.session.save(function (err) { if (err) next(err); // regenerate the session, which is good practice to help // guard against forms of session fixation req.session.regenerate(function (err) { if (err) next(err); res.redirect('/'); }); }); }); app.listen(3000); ``` ## Debugging This module uses the [debug](https://www.npmjs.com/package/debug) module internally to log information about session operations. To see all the internal logs, set the `DEBUG` environment variable to `express-session` when launching your app (`npm start`, in this example): ```sh $ DEBUG=express-session npm start ``` On Windows, use the corresponding command; ```sh > set DEBUG=express-session & npm start ``` ## License [MIT](https://github.com/expressjs/session/blob/HEAD/LICENSE) [rfc-6265-5.1.4]: https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4 [rfc-6265bis-03-4.1.2.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7 [rfc-cutler-httpbis-partitioned-cookies]: https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/ [rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1 [node-url]: https://nodejs.org/en/download [npm-url]: https://npmjs.org/package/express-session --- ## timeout middleware URL: https://expressjs.com/en/resources/middleware/timeout Times out a request in the Connect/Express application framework. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `connect-timeout` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API **NOTE** This module is not recommend as a "top-level" middleware (i.e. `app.use(timeout('5s'))`) unless you take precautions to halt your own middleware processing. See [as top-level middleware](#as-top-level-middleware) for how to use as a top-level middleware. While the library will emit a 'timeout' event when requests exceed the given timeout, node will continue processing the slow request until it terminates. Slow requests will continue to use CPU and memory, even if you are returning a HTTP response in the timeout callback. For better control over CPU/memory, you may need to find the events that are taking a long time (3rd party HTTP requests, disk I/O, database calls) and find a way to cancel them, and/or close the attached sockets. ### timeout(time, [options]) Returns middleware that times out in `time` milliseconds. `time` can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) module. On timeout, `req` will emit `"timeout"`. #### Options The `timeout` function takes an optional `options` object that may contain any of the following keys: ##### respond Controls if this module will "respond" in the form of forwarding an error. If `true`, the timeout error is passed to `next()` so that you may customize the response behavior. This error has a `.timeout` property as well as `.status == 503`. This defaults to `true`. ### req.clearTimeout() Clears the timeout on the request. The timeout is completely removed and will not fire for this request in the future. ### req.timedout `true` if timeout fired; `false` otherwise. ## Examples ### as top-level middleware Because of the way middleware processing works, once this module passes the request to the next middleware (which it has to do in order for you to do work), it can no longer stop the flow, so you must take care to check if the request has timedout before you continue to act on the request. ```javascript var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var express = require('express'); var timeout = require('connect-timeout'); // example of using this top-level; note the use of haltOnTimedout // after every middleware; it will stop the request flow on a timeout var app = express(); app.use(timeout('5s')); app.use(bodyParser()); app.use(haltOnTimedout); app.use(cookieParser()); app.use(haltOnTimedout); // Add your routes here, etc. function haltOnTimedout(req, res, next) { if (!req.timedout) next(); } app.listen(3000); ``` ### express 3.x ```javascript var express = require('express'); var bodyParser = require('body-parser'); var timeout = require('connect-timeout'); var app = express(); app.post('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function (req, res, next) { savePost(req.body, function (err, id) { if (err) return next(err); if (req.timedout) return; res.send('saved as id ' + id); }); }); function haltOnTimedout(req, res, next) { if (!req.timedout) next(); } function savePost(post, cb) { setTimeout( function () { cb(null, (Math.random() * 40000) >>> 0); }, (Math.random() * 7000) >>> 0 ); } app.listen(3000); ``` ### connect ```javascript var bodyParser = require('body-parser'); var connect = require('connect'); var timeout = require('connect-timeout'); var app = connect(); app.use('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function (req, res, next) { savePost(req.body, function (err, id) { if (err) return next(err); if (req.timedout) return; res.send('saved as id ' + id); }); }); function haltOnTimedout(req, res, next) { if (!req.timedout) next(); } function savePost(post, cb) { setTimeout( function () { cb(null, (Math.random() * 40000) >>> 0); }, (Math.random() * 7000) >>> 0 ); } app.listen(3000); ``` ## License [MIT](https://github.com/expressjs/timeout/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/connect-timeout [travis-url]: https://travis-ci.org/expressjs/timeout [downloads-url]: https://npmjs.org/package/connect-timeout --- ## vhost middleware URL: https://expressjs.com/en/resources/middleware/vhost ## Install `vhost` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var vhost = require('vhost'); ``` ### vhost(hostname, handle) Create a new middleware function to hand off request to `handle` when the incoming host for the request matches `hostname`. The function is called as `handle(req, res, next)`, like a standard middleware. `hostname` can be a string or a RegExp object. When `hostname` is a string it can contain `*` to match 1 or more characters in that section of the hostname. When `hostname` is a RegExp, it will be forced to case-insensitive (since hostnames are) and will be forced to match based on the start and end of the hostname. When host is matched and the request is sent down to a vhost handler, the `req.vhost` property will be populated with an object. This object will have numeric properties corresponding to each wildcard (or capture group if RegExp object provided) and the `hostname` that was matched. ```js var connect = require('connect'); var vhost = require('vhost'); var app = connect(); app.use( vhost('*.*.example.com', function handle(req, res, next) { // for match of "foo.bar.example.com:8080" against "*.*.example.com": console.dir(req.vhost.host); // => 'foo.bar.example.com:8080' console.dir(req.vhost.hostname); // => 'foo.bar.example.com' console.dir(req.vhost.length); // => 2 console.dir(req.vhost[0]); // => 'foo' console.dir(req.vhost[1]); // => 'bar' }) ); ``` ## Examples ### using with connect for static serving ```js var connect = require('connect'); var serveStatic = require('serve-static'); var vhost = require('vhost'); var mailapp = connect(); // add middlewares to mailapp for mail.example.com // create app to serve static files on subdomain var staticapp = connect(); staticapp.use(serveStatic('public')); // create main app var app = connect(); // add vhost routing to main app for mail app.use(vhost('mail.example.com', mailapp)); // route static assets for "assets-*" subdomain to get // around max host connections limit on browsers app.use(vhost('assets-*.example.com', staticapp)); // add middlewares and main usage to app app.listen(3000); ``` ### using with connect for user subdomains ```js var connect = require('connect'); var serveStatic = require('serve-static'); var vhost = require('vhost'); var mainapp = connect(); // add middlewares to mainapp for the main web site // create app that will server user content from public/{username}/ var userapp = connect(); userapp.use(function (req, res, next) { var username = req.vhost[0]; // username is the "*" // pretend request was for /{username}/* for file serving req.originalUrl = req.url; req.url = '/' + username + req.url; next(); }); userapp.use(serveStatic('public')); // create main app var app = connect(); // add vhost routing for main app app.use(vhost('userpages.local', mainapp)); app.use(vhost('www.userpages.local', mainapp)); // listen on all subdomains for user pages app.use(vhost('*.userpages.local', userapp)); app.listen(3000); ``` ### using with any generic request handler ```js var connect = require('connect'); var http = require('http'); var vhost = require('vhost'); // create main app var app = connect(); app.use( vhost('mail.example.com', function (req, res) { // handle req + res belonging to mail.example.com res.setHeader('Content-Type', 'text/plain'); res.end('hello from mail!'); }) ); // an external api server in any framework var httpServer = http.createServer(function (req, res) { res.setHeader('Content-Type', 'text/plain'); res.end('hello from the api!'); }); app.use( vhost('api.example.com', function (req, res) { // handle req + res belonging to api.example.com // pass the request to a standard Node.js HTTP server httpServer.emit('request', req, res); }) ); app.listen(3000); ``` ## License [MIT](https://github.com/expressjs/vhost/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/vhost [downloads-url]: https://npmjs.org/package/vhost