, 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
`
```
### 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 `
```
## 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(
''
);
});
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