# Express.js — Full Documentation > Fast, unopinionated, minimalist web framework for Node.js --- ## Developing template engines for Express URL: https://expressjs.com/en/5x/advanced/developing-template-engines Use the `app.engine(ext, callback)` method to create your own template engine. `ext` refers to the file extension, and `callback` is the template engine function, which accepts the following items as parameters: the location of the file, the options object, and the callback function. The following code is an example of implementing a very simple template engine for rendering `.ntl` files. ```js const fs = require('fs'); // this engine requires the fs module app.engine('ntl', (filePath, options, callback) => { // define the template engine fs.readFile(filePath, (err, content) => { if (err) return callback(err); // this is an extremely simple template engine const rendered = content .toString() .replace('#title#', `
| Type | Value |
|---|---|
| Boolean | If `true`, the client's IP address is understood as the left-most entry in the `X-Forwarded-For` header. If `false`, the app is understood as directly facing the client and the client's IP address is derived from `req.socket.remoteAddress`. This is the default setting. When setting to `true`, it is important to ensure that the last reverse proxy trusted is removing/overwriting all of the following HTTP headers: `X-Forwarded-For`, `X-Forwarded-Host`, and `X-Forwarded-Proto`, otherwise it may be possible for the client to provide any value. |
| IP addresses | An IP address, subnet, or an array of IP addresses and subnets to trust as being a reverse proxy. The following list shows the pre-configured subnet names: - loopback - `127.0.0.1/8`, `::1/128` - linklocal - `169.254.0.0/16`, `fe80::/10` - uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7` You can set IP addresses in any of the following ways: ```js app.set('trust proxy', 'loopback'); // specify a single subnet app.set('trust proxy', 'loopback, 123.123.123.123'); // specify a subnet and an address app.set('trust proxy', 'loopback, linklocal, uniquelocal'); // specify multiple subnets as CSV app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']); // specify multiple subnets as an array ``` When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client's IP address. This works by checking if `req.socket.remoteAddress` is trusted. If so, then each address in `X-Forwarded-For` is checked from right to left until the first non-trusted address. |
| Number | Use the address that is at most `n` number of hops away from the Express application. `req.socket.remoteAddress` is the first hop, and the rest are looked for in the `X-Forwarded-For` header from right to left. A value of `0` means that the first untrusted address would be `req.socket.remoteAddress`, i.e. there is no reverse proxy. When using this setting, it is important to ensure there are not multiple, different-length paths to the Express application such that the client can be less than the configured number of hops away, otherwise it may be possible for the client to provide any value. |
| Function | Custom trust implementation. ```js app.set('trust proxy', (ip) => { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true; // trusted IPs else return false; }); ``` ```ts app.set('trust proxy', (ip: string) => { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true; // trusted IPs else return false; }); ``` |
hey
'); }, 'application/json'() { res.send({ message: 'hey' }); }, default() { // log the request and respond with 406 res.status(406).send('Not Acceptable'); }, }); ``` In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation: ```js res.format({ text() { res.send('hey'); }, html() { res.send('hey
'); }, json() { res.send({ message: 'hey' }); }, }); ``` ### res.get() Returns: String. Arguments: - field (String): The name of the response header to read (case-insensitive). Returns the HTTP response header specified by `field`. The match is case-insensitive. ```js res.get('Content-Type'); // => 'text/plain' ``` ### res.json() Returns: Response. Arguments: - body (any, optional): The value to send as JSON. Can be any JSON type: object, array, string, Boolean, number, or null. Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON. ```js res.json(null); res.json({ user: 'tobi' }); res.status(500).json({ error: 'message' }); ``` ### res.jsonp() Returns: Response. Arguments: - body (any, optional): The value to send as a JSONP response. Can be any JSON type. Sends a JSON response with JSONP support. This method is identical to `res.json()`, except that it opts-in to JSONP callback support. ```js res.jsonp(null); // => callback(null) res.jsonp({ user: 'tobi' }); // => callback({ "user": "tobi" }) res.status(500).jsonp({ error: 'message' }); // => callback({ "error": "message" }) ``` By default, the JSONP callback name is simply `callback`. Override this with the [jsonp callback name](/api/application/#application-settings) setting. The following are some examples of JSONP responses using the same code: ```js // ?callback=foo res.jsonp({ user: 'tobi' }); // => foo({ "user": "tobi" }) app.set('jsonp callback name', 'cb'); // ?cb=foo res.status(500).jsonp({ error: 'message' }); // => foo({ "error": "message" }) ``` ### res.links() Returns: Response. Arguments: - links (Record): An object whose properties (such as `next` and `last`) populate the `Link` response header. Each value can be a single URL string, or an array of URL strings to emit multiple links for the same relation. Joins the `links` provided as properties of the parameter to populate the response's `Link` HTTP header field. For example, the following call: ```js res.links({ next: 'http://api.example.com/users?page=2', last: 'http://api.example.com/users?page=5', }); ``` Yields the following results: ``` Link:some html
'); res.status(404).send('Sorry, we cannot find that!'); res.status(500).send({ error: 'something blew up' }); ``` This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the `Content-Length` HTTP response header field and provides automatic HEAD and HTTP cache freshness support. When the parameter is a `Buffer` object, the method sets the `Content-Type` response header field to "application/octet-stream", unless previously defined as shown below: ```js res.set('Content-Type', 'text/html'); res.send(Buffer.from('some html
')); ``` When the parameter is a `String`, the method sets the `Content-Type` to "text/html": ```js res.send('some html
'); ``` When the parameter is an `Array` or `Object`, Express responds with the JSON representation: ```js res.send({ user: 'tobi' }); res.send([1, 2, 3]); ``` ### res.sendFile() Arguments: - path (String): The path to the file to transfer. Must be absolute unless the `root` option is set. - options (Object, optional): Options for serving the file. Properties: - maxAge (Number | String, default: 0): Sets the max-age property of the `Cache-Control` header in milliseconds, or a string in [ms format](https://www.npmjs.com/package/ms). - root (String): Root directory for relative file names. - lastModified (Boolean, default: true): Sets the `Last-Modified` header to the last modified date of the file on the OS. Set `false` to disable it. - headers (Object): Object containing HTTP headers to serve with the file. - dotfiles (String, default: "ignore"): Option for serving dotfiles. Possible values are `"allow"`, `"deny"`, and `"ignore"`. - acceptRanges (Boolean, default: true): Enable or disable accepting ranged requests. - cacheControl (Boolean, default: true): Enable or disable setting the `Cache-Control` response header. - immutable (Boolean, default: false): Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. - fn (Function, optional): Callback `fn(err)` invoked when the transfer completes or an error occurs. Transfers the file at the given `path`. Sets the `Content-Type` response HTTP header field based on the filename's extension. Unless the `root` option is set in the options object, `path` must be an absolute path to the file. This API provides access to data on the running file system. Ensure that either (a) the way in which the `path` argument was constructed into an absolute path is secure if it contains user input or (b) set the `root` option to the absolute path of a directory to contain access within. When the `root` option is provided, the `path` argument is allowed to be a relative path, including containing `..`. Express will validate that the relative path provided as `path` will resolve within the given `root` option. The method invokes the callback function `fn(err)` when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route. Here is an example of using `res.sendFile` with all its arguments. ```js app.get('/file/:name', (req, res, next) => { const options = { root: path.join(__dirname, 'public'), dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true, }, }; const fileName = req.params.name; res.sendFile(fileName, options, (err) => { if (err) { next(err); } else { console.log('Sent:', fileName); } }); }); ``` ```ts app.get('/file/:name', (req: Request, res: Response, next: NextFunction) => { const options = { root: path.join(__dirname, 'public'), dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true, }, }; const fileName = req.params.name; res.sendFile(fileName, options, (err) => { if (err) { next(err); } else { console.log('Sent:', fileName); } }); }); ``` The following example illustrates using `res.sendFile` to provide fine-grained support for serving files: ```js app.get('/user/:uid/photos/:file', (req, res) => { const uid = req.params.uid; const file = req.params.file; req.user.mayViewFilesFrom(uid, (yes) => { if (yes) { res.sendFile(`/uploads/${uid}/${file}`); } else { res.status(403).send("Sorry! You can't see that."); } }); }); ``` ```ts app.get('/user/:uid/photos/:file', (req: Request, res: Response) => { const uid = req.params.uid; const file = req.params.file; req.user.mayViewFilesFrom(uid, (yes) => { if (yes) { res.sendFile(`/uploads/${uid}/${file}`); } else { res.status(403).send("Sorry! You can't see that."); } }); }); ``` For more information, or if you have issues or concerns, see [send](https://github.com/pillarjs/send). ### res.sendStatus() Returns: Response. Arguments: - statusCode (Number): The HTTP status code to set; its registered status message becomes the response body. Sets the response HTTP status code to `statusCode` and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number. ```js res.sendStatus(404); ``` Some versions of Node.js will throw when `res.statusCode` is set to an invalid HTTP status code (outside of the range `100` to `599`). Consult the HTTP server documentation for the Node.js version being used. [More about HTTP Status Codes](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) ### res.set() Returns: Response. Arguments: - field (String | Object): The header name, or an object of header name/value pairs to set multiple headers at once. - value (String | String[], optional): The header value (when `field` is a string). Sets the response's HTTP header `field` to `value`. To set multiple fields at once, pass an object as the parameter. ```js res.set('Content-Type', 'text/plain'); res.set({ 'Content-Type': 'text/plain', 'Content-Length': '123', ETag: '12345', }); ``` Aliased as `res.header(field [, value])`. ### res.status() Returns: Response. Arguments: - code (Number): The HTTP status code for the response. Sets the HTTP status for the response. It is a chainable alias of Node's [response.statusCode](https://nodejs.org/api/http.html#responsestatuscode). ```js res.status(403).end(); res.status(400).send('Bad Request'); res.status(404).sendFile('/absolute/path/to/404.png'); ``` ### res.type() Returns: Response. Arguments: - type (String): The MIME type, or a file extension that is looked up to a MIME type. If it contains `/`, it is used as-is. Sets the `Content-Type` HTTP header to the MIME type as determined by the specified `type`. If `type` contains the "/" character, then it sets the `Content-Type` to the exact value of `type`, otherwise it is assumed to be a file extension and the MIME type is looked up using the `contentType()` method of the `mime-types` package. ```js res.type('.html'); // => 'text/html' res.type('html'); // => 'text/html' res.type('json'); // => 'application/json' res.type('application/json'); // => 'application/json' res.type('png'); // => 'image/png' ``` Aliased as `res.contentType(type)`. ### res.vary() Returns: Response. Arguments: - field (String): The header field name to add to the `Vary` response header. Adds the field to the `Vary` response header, if it is not there already. ```js res.vary('User-Agent').render('docs'); ``` --- ## Router URL: https://expressjs.com/en/5x/api/router A `router` object is an instance of middleware and routes. You can think of it as a "mini-application," capable only of performing middleware and routing functions. Every Express application has a built-in app router. A router behaves like middleware itself, so you can use it as an argument to [app.use()](/api/application/#appuse) or as the argument to another router's [use()](#routeruse) method. The top-level `express` object has a [Router()](/api/express/#expressrouter) method that creates a new `router` object. Once you've created a router object, you can add middleware and HTTP method routes (such as `get`, `put`, `post`, and so on) to it just like an application. For example: ```js // invoked for any requests passed to this router router.use((req, res, next) => { // .. some logic here .. like any other middleware next(); }); // will handle any request that ends in /events // depends on where the router is "use()'d" router.get('/events', (req, res, next) => { // .. }); ``` ```ts // invoked for any requests passed to this router router.use((req: Request, res: Response, next: NextFunction) => { // .. some logic here .. like any other middleware next(); }); // will handle any request that ends in /events // depends on where the router is "use()'d" router.get('/events', (req: Request, res: Response, next: NextFunction) => { // .. }); ``` You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps. ```js // only requests to /calendar/* will be sent to our "router" app.use('/calendar', router); ``` ## Methods ### Router() Returns: Router. Arguments: - options (Object, optional): Options that configure the router's behavior. Properties: - caseSensitive (Boolean, default: false): Enable case sensitivity. Disabled by default, treating `/Foo` and `/foo` as the same. - mergeParams (Boolean, default: false): Preserve the `req.params` values from the parent router. If the parent and the child have conflicting param names, the child's value takes precedence. - strict (Boolean, default: false): Enable strict routing. Disabled by default, `/foo` and `/foo/` are treated the same by the router. Creates a new router object. ```cjs title="index.cjs" ins={2} const express = require('express'); const router = express.Router({ caseSensitive: true, strict: true }); router.get('/events', (req, res) => { res.send('events'); }); // mount the router on an app app.use('/calendar', router); ``` ```mjs title="index.mjs" ins={3} const router = express.Router({ caseSensitive: true, strict: true }); router.get('/events', (req, res) => { res.send('events'); }); // mount the router on an app app.use('/calendar', router); ``` ```ts title="index.ts" const router = express.Router({ caseSensitive: true, strict: true }); router.get('/events', (req: Request, res: Response) => { res.send('events'); }); // mount the router on an app app.use('/calendar', router); ``` ### router.all() Returns: Router. Arguments: - path (String | RegExp | Array): The path for which the route callbacks are invoked. - callback (Function | Function[]): One or more middleware/handler functions. Each may call `next('route')` to skip the remaining callbacks. This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs). This method is extremely useful for mapping "global" logic for specific path prefixes or arbitrary matches. For example, if you placed the following route at the top of all other route definitions, it would require that all routes from that point on would require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end points; `loadUser` can perform a task, then call `next()` to continue matching subsequent routes. ```js router.all('{*splat}', requireAuthentication, loadUser); ``` Or the equivalent: ```js router.all('{*splat}', requireAuthentication); router.all('{*splat}', loadUser); ``` Another example of this is white-listed "global" functionality. Here, the example is much like before, but it only restricts paths prefixed with "/api": ```js router.all('/api/{*splat}', requireAuthentication); ``` ### router.METHOD() Returns: Router. Arguments: - path (String | RegExp | Array): The path for which the route callbacks are invoked. - callback (Function | Function[]): One or more middleware/handler functions. Each may call `next('route')` to skip the remaining callbacks. The `router.METHOD()` methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are `router.get()`, `router.post()`, `router.put()`, and so on. The `router.get()` function is automatically called for the HTTP `HEAD` method in addition to the `GET` method if `router.head()` was not called for the path before `router.get()`. `router.query()` routes HTTP `QUERY` requests, mirroring [`app.query()`](/api/application/#appquery). The `QUERY` method is gated by the runtime and requires Node.js `>=20.19.3 <21 || >=22.2.0`. You can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to perform pre-conditions on a route then pass control to subsequent routes when there is no reason to proceed with the route matched. The following snippet illustrates the most simple route definition possible. Express translates the path strings to regular expressions, used internally to match incoming requests. Query strings are _not_ considered when performing these matches, for example "GET /" would match the following route, as would "GET /?name=tobi". ```js router.get('/', (req, res) => { res.send('hello world'); }); ``` ```ts router.get('/', (req: Request, res: Response) => { res.send('hello world'); }); ``` You can also use regular expressions—useful if you have very specific constraints, for example the following would match "GET /commits/71dbb9c" as well as "GET /commits/71dbb9c..4c084f9". ```js router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, (req, res) => { const from = req.params[0]; const to = req.params[1] || 'HEAD'; res.send(`commit range ${from}..${to}`); }); ``` ```ts router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, (req: Request, res: Response) => { const from = req.params[0]; const to = req.params[1] || 'HEAD'; res.send(`commit range ${from}..${to}`); }); ``` You can use `next` primitive to implement a flow control between different middleware functions, based on a specific program state. Invoking `next` with the string `'router'` will cause all the remaining route callbacks on that router to be bypassed. The following example illustrates `next('router')` usage. ```js function fn(req, res, next) { console.log('I come here'); next('router'); } router.get('/foo', fn, (req, res, next) => { console.log("I don't come here"); }); router.get('/foo', (req, res, next) => { console.log("I don't come here"); }); app.get('/foo', (req, res) => { console.log(' I come here too'); res.end('good'); }); ``` ```ts function fn(req: Request, res: Response, next: NextFunction) { console.log('I come here'); next('router'); } router.get('/foo', fn, (req: Request, res: Response, next: NextFunction) => { console.log("I don't come here"); }); router.get('/foo', (req: Request, res: Response, next: NextFunction) => { console.log("I don't come here"); }); app.get('/foo', (req: Request, res: Response) => { console.log(' I come here too'); res.end('good'); }); ``` ### router.param() Returns: Router. Arguments: - name (String): The name of the route parameter to attach the trigger to. Unlike `app.param()`, this does not accept an array. - callback (Function): The trigger called as `callback(req, res, next, value, name)`. Adds callback triggers to route parameters, where `name` is the name of the parameter and `callback` is the callback function. The `name` parameter is required. The parameters of the callback function are: - `req`, the request object. - `res`, the response object. - `next`, indicating the next middleware function. - The value of the `name` parameter. - The name of the parameter. Unlike `app.param()`, `router.param()` does not accept an array of route parameters. For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input. ```js router.param('user', (req, res, next, id) => { // try to get the user details from the User model and attach it to the request object User.find(id, (err, user) => { if (err) { next(err); } else if (user) { req.user = user; next(); } else { next(new Error('failed to load user')); } }); }); ``` ```ts router.param('user', (req: Request, res: Response, next: NextFunction, id: string) => { // try to get the user details from the User model and attach it to the request object User.find(id, (err, user) => { if (err) { next(err); } else if (user) { req.user = user; next(); } else { next(new Error('failed to load user')); } }); }); ``` Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on `router` will be triggered only by route parameters defined on `router` routes. A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples. ```js router.param('id', (req, res, next, id) => { console.log('CALLED ONLY ONCE'); next(); }); router.get('/user/:id', (req, res, next) => { console.log('although this matches'); next(); }); router.get('/user/:id', (req, res) => { console.log('and this matches too'); res.end(); }); ``` ```ts router.param('id', (req: Request, res: Response, next: NextFunction, id: string) => { console.log('CALLED ONLY ONCE'); next(); }); router.get('/user/:id', (req: Request, res: Response, next: NextFunction) => { console.log('although this matches'); next(); }); router.get('/user/:id', (req: Request, res: Response) => { console.log('and this matches too'); res.end(); }); ``` On `GET /user/42`, the following is printed: ``` CALLED ONLY ONCE although this matches and this matches too ``` ### router.route() Returns: Route. Arguments: - path (String): The path of the route to create. Returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use `router.route()` to avoid duplicate route naming and thus typing errors. Building on the `router.param()` example above, the following code shows how to use `router.route()` to specify various HTTP method handlers. ```js const router = express.Router(); router.param('user_id', (req, res, next, id) => { // sample user, would actually fetch from DB, etc... req.user = { id, name: 'TJ', }; next(); }); router .route('/users/:user_id') .all((req, res, next) => { // runs for all HTTP verbs first // think of it as route specific middleware! next(); }) .get((req, res, next) => { res.json(req.user); }) .put((req, res, next) => { // just an example of maybe updating the user req.user.name = req.params.name; // save user ... etc res.json(req.user); }) .post((req, res, next) => { next(new Error('not implemented')); }) .delete((req, res, next) => { next(new Error('not implemented')); }); ``` ```ts title="index.ts" const router = express.Router(); router.param('user_id', (req: Request, res: Response, next: NextFunction, id: string) => { // sample user, would actually fetch from DB, etc... req.user = { id, name: 'TJ', }; next(); }); router .route('/users/:user_id') .all((req: Request, res: Response, next: NextFunction) => { // runs for all HTTP verbs first // think of it as route specific middleware! next(); }) .get((req: Request, res: Response, next: NextFunction) => { res.json(req.user); }) .put((req: Request, res: Response, next: NextFunction) => { // just an example of maybe updating the user req.user.name = req.params.name; // save user ... etc res.json(req.user); }) .post((req: Request, res: Response, next: NextFunction) => { next(new Error('not implemented')); }) .delete((req: Request, res: Response, next: NextFunction) => { next(new Error('not implemented')); }); ``` This approach re-uses the single `/users/:user_id` path and adds handlers for various HTTP methods. When you use `router.route()`, middleware ordering is based on when the _route_ is created, not when method handlers are added to the route. For this purpose, you can consider method handlers to belong to the route to which they were added. ### router.use() Returns: Router. Arguments: - path (String | RegExp | Array, optional): The mount path for the middleware. Defaults to `/`. - callback (Function | Function[]): One or more middleware functions to mount. Uses the specified middleware function or functions, with optional mount path `path`, that defaults to "/". This method is similar to [app.use()](/api/application/#appuse). A simple example and use case is described below. See [app.use()](/api/application/#appuse) for more information. Middleware is like a plumbing pipe: requests start at the first middleware function defined and work their way "down" the middleware stack processing for each path they match. ```cjs title="index.cjs" const express = require('express'); const app = express(); const router = express.Router(); // simple logger for this router's requests // all requests to this router will first hit this middleware router.use((req, res, next) => { console.log('%s %s %s', req.method, req.url, req.path); next(); }); // this will only be invoked if the path starts with /bar from the mount point router.use('/bar', (req, res, next) => { // ... maybe some additional /bar logging ... next(); }); // always invoked router.use((req, res, next) => { res.send('Hello World'); }); app.use('/foo', router); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); const router = express.Router(); // simple logger for this router's requests // all requests to this router will first hit this middleware router.use((req, res, next) => { console.log('%s %s %s', req.method, req.url, req.path); next(); }); // this will only be invoked if the path starts with /bar from the mount point router.use('/bar', (req, res, next) => { // ... maybe some additional /bar logging ... next(); }); // always invoked router.use((req, res, next) => { res.send('Hello World'); }); app.use('/foo', router); app.listen(3000); ``` ```ts title="index.ts" const app = express(); const router = express.Router(); // simple logger for this router's requests // all requests to this router will first hit this middleware router.use((req: Request, res: Response, next: NextFunction) => { console.log('%s %s %s', req.method, req.url, req.path); next(); }); // this will only be invoked if the path starts with /bar from the mount point router.use('/bar', (req: Request, res: Response, next: NextFunction) => { // ... maybe some additional /bar logging ... next(); }); // always invoked router.use((req: Request, res: Response, next: NextFunction) => { res.send('Hello World'); }); app.use('/foo', router); app.listen(3000); ``` The "mount" path is stripped and is _not_ visible to the middleware function. The main effect of this feature is that a mounted middleware function may operate without code changes regardless of its "prefix" pathname. The order in which you define middleware with `router.use()` is very important. They are invoked sequentially, thus the order defines middleware precedence. For example, usually a logger is the very first middleware you would use, so that every request gets logged. ```cjs title="index.cjs" const logger = require('morgan'); router.use(logger()); router.use(express.static(path.join(__dirname, 'public'))); router.use((req, res) => { res.send('Hello'); }); ``` ```mjs title="index.mjs" router.use(logger()); router.use(express.static(path.join(__dirname, 'public'))); router.use((req, res) => { res.send('Hello'); }); ``` ```ts title="index.ts" router.use(logger()); router.use(express.static(path.join(__dirname, 'public'))); router.use((req: Request, res: Response) => { res.send('Hello'); }); ``` Now suppose you wanted to ignore logging requests for static files, but to continue logging routes and middleware defined after `logger()`. You would simply move the call to `express.static()` to the top, before adding the logger middleware: ```js router.use(express.static(path.join(__dirname, 'public'))); router.use(logger()); router.use((req, res) => { res.send('Hello'); }); ``` ```ts router.use(express.static(path.join(__dirname, 'public'))); router.use(logger()); router.use((req: Request, res: Response) => { res.send('Hello'); }); ``` Another example is serving files from multiple directories, giving precedence to "./public" over the others: ```js app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'files'))); app.use(express.static(path.join(__dirname, 'uploads'))); ``` The `router.use()` method also supports named parameters so that your mount points for other routers can benefit from preloading using named parameters. Although these middleware functions are added via a particular router, _when_ they run is defined by the path they are attached to (not the router). Therefore, middleware added via one router may run for other routers if its routes match. For example, this code shows two different routers mounted on the same path: ```js const authRouter = express.Router(); const openRouter = express.Router(); authRouter.use(require('./authenticate').basic(usersdb)); authRouter.get('/:user_id/edit', (req, res, next) => { // ... Edit user UI ... }); openRouter.get('/', (req, res, next) => { // ... List users ... }); openRouter.get('/:user_id', (req, res, next) => { // ... View user ... }); app.use('/users', authRouter); app.use('/users', openRouter); ``` ```ts const authRouter = express.Router(); const openRouter = express.Router(); authRouter.use(basic(usersdb)); authRouter.get('/:user_id/edit', (req: Request, res: Response, next: NextFunction) => { // ... Edit user UI ... }); openRouter.get('/', (req: Request, res: Response, next: NextFunction) => { // ... List users ... }); openRouter.get('/:user_id', (req: Request, res: Response, next: NextFunction) => { // ... View user ... }); app.use('/users', authRouter); app.use('/users', openRouter); ``` Even though the authentication middleware was added via the `authRouter` it will run on the routes defined by the `openRouter` as well since both routers were mounted on `/users`. To avoid this behavior, use different paths for each router. --- ## Production best practices: performance and reliability URL: https://expressjs.com/en/advanced/best-practice-performance This article discusses performance and reliability best practices for Express applications deployed to production. This topic clearly falls into the "devops" world, spanning both traditional development and operations. Accordingly, the information is divided into two parts: [things to do in your code](#things-to-do-in-your-code) (the dev part), and [things to do in your environment / setup](#things-to-do-in-your-environment--setup) (the ops part). ## Things to do in your code Here are some things you can do in your code to improve your application's performance. ### Use gzip compression Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the [compression](https://www.npmjs.com/package/compression) middleware for gzip compression in your Express app. For example: ```cjs title="index.cjs" const compression = require('compression'); const express = require('express'); const app = express(); app.use(compression()); ``` ```mjs title="index.mjs" const app = express(); app.use(compression()); ``` For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation. ### Don't use synchronous functions Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production. Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup. You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#--trace-sync-io) for more information. ### Do logging correctly In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. #### For debugging If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like [debug](https://www.npmjs.com/package/debug). This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you? #### For app activity If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like [Pino](https://www.npmjs.com/package/pino), which is the fastest and most efficient option available. ### Handle exceptions properly Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in [Ensure your app automatically restarts](#ensure-your-app-automatically-restarts) below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly. To ensure you handle all exceptions, use the following techniques: - [Use try-catch](#use-try-catch) - [Use promises](#use-promises) Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain. For more on the fundamentals of error handling, see: - [Error Handling in Node.js](https://web.archive.org/web/20210619211351/https://www.joyent.com/node-js/production/design/errors) #### Use try-catch Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below. Here is an example of using try-catch to handle a potential process-crashing exception. This middleware function accepts a query field parameter named "params" that is a JSON object. ```js app.get('/search', (req, res) => { // Simulating async operation setImmediate(() => { const jsonStr = req.query.params; try { const jsonObj = JSON.parse(jsonStr); res.send('Success'); } catch (e) { res.status(400).send('Invalid JSON string'); } }); }); ``` However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions. #### Use promises When an error is thrown in an `async` function or a rejected promise is awaited inside an `async` function, those errors will be passed to the error handler as if calling `next(err)` ```js app.get('/', async (req, res, next) => { const data = await userData(); // If this promise fails, it will automatically call `next(err)` to handle the error. res.send(data); }); app.use((err, req, res, next) => { res.status(err.status ?? 500).send({ error: err.message }); }); ``` Also, you can use asynchronous functions for your middleware, and the router will handle errors if the promise fails, for example: ```js app.use(async (req, res, next) => { req.locals.user = await getUser(req); next(); // This will be called if the promise does not throw an error. }); ``` Best practice is to handle errors as close to the site as possible. So while this is now handled in the router, it’s best to catch the error in the middleware and handle it without relying on separate error-handling middleware. #### What not to do One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable. Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module. ### Use worker threads for CPU-intensive tasks Node.js runs your JavaScript on a single thread, so a CPU-intensive operation (such as image processing, parsing or transforming large payloads, or cryptographic operations) can block the event loop and slow down every request your Express app is handling. If your app does CPU-bound work, you can run it in [worker threads](https://nodejs.org/api/worker_threads.html), which execute JavaScript in parallel within the same process, keeping the main thread free to serve requests. Each worker thread runs in its own JavaScript engine instance, so the data you pass to it through `workerData` or `postMessage` is copied, not shared. Copying large payloads has a cost of its own, which you can avoid by transferring objects such as `ArrayBuffer`s or by sharing memory explicitly with `SharedArrayBuffer`. Worker threads are not a replacement for [running your app in a cluster](#run-your-app-in-a-cluster), which scales your app across CPU cores by running multiple instances of it in separate processes. This example offloads an image-resizing task to a worker, where `resize-worker.js` receives the image via `workerData` and posts the result back when it's done: ```js const { Worker } = require('node:worker_threads'); app.post('/resize', (req, res, next) => { const worker = new Worker('./resize-worker.js', { workerData: req.body.image }); worker.once('message', (result) => res.send(result)); worker.once('error', next); }); ``` Note that this example is kept simple for illustration: creating a worker thread is relatively expensive, so [the Node.js documentation recommends using a pool of workers](https://nodejs.org/api/worker_threads.html#worker-threads) instead of spawning a new one for every request. Create a fixed pool of workers at startup and dispatch tasks to them as requests come in, for example with a library like [piscina](https://www.npmjs.com/package/piscina): ```js const path = require('node:path'); const Piscina = require('piscina'); const pool = new Piscina({ filename: path.resolve(__dirname, 'resize-worker.js') }); app.post('/resize', async (req, res, next) => { try { res.send(await pool.run(req.body.image)); } catch (err) { next(err); } }); ``` Here `resize-worker.js` simply exports the function to run in the pool, and piscina takes care of creating the workers, queueing tasks, and reusing threads across requests. For more guidance on keeping the event loop responsive, including when offloading work is worth its communication costs, see [Don't Block the Event Loop](https://nodejs.org/learn/asynchronous-work/dont-block-the-event-loop) in the Node.js documentation. ## Things to do in your environment / setup Here are some things you can do in your system environment to improve your app's performance. ### Set NODE_ENV to "production" The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to `production`. Setting NODE_ENV to "production" makes Express: - Cache view templates. - Cache CSS files generated from CSS extensions. - Generate less verbose error messages. [Tests indicate](https://web.archive.org/web/20250814011110/https://www.dynatrace.com/news/blog/the-drastic-effects-of-omitting-node-env-in-your-express-js-applications/) that just doing this can improve app performance by a factor of three! If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly. In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general, you shouldn't do that on a production server; instead, use your OS's init system (systemd). The next section provides more details about using your init system in general, but setting `NODE_ENV` is so important for performance (and easy to do), that it's highlighted here. With systemd, use the `Environment` directive in your unit file. For example: ```sh Environment=NODE_ENV=production ``` For more information, see [Using Environment Variables In systemd Units](https://www.flatcar.org/docs/latest/setup/systemd/environment-variables/). ### Use the latest LTS version of Node.js Running your app on a recent Node.js release is one of the easiest ways to improve performance. Each new version of Node.js ships with cumulative improvements to the V8 JavaScript engine and the runtime itself, so the same Express app can handle significantly more requests simply by upgrading. Benchmarks such as NodeSource's [Node.js Performance Report](https://nodesource.com/pages/content-node-performance-report-wb.html) show how much throughput can improve from one Node.js version to the next. For production, use the latest [LTS release](https://nodejs.org/en/about/previous-releases) of Node.js, and keep it up to date as new versions come out. ### Ensure your app automatically restarts In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by: - Using a process manager to restart the app (and Node) when it crashes. - Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager. Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see [handle exceptions properly](#handle-exceptions-properly) for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart. #### Use a process manager In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime. In addition to restarting your app when it crashes, a process manager can enable you to: - Gain insights into runtime performance and resource consumption. - Modify settings dynamically to improve performance. - Control clustering (pm2). Historically, it was popular to use a Node.js process manager like [PM2](https://github.com/Unitech/pm2). See their documentation if you wish to do this. However, we recommend using your init system for process management. #### Use an init system The next layer of reliability is to ensure that your app restarts when the server restarts. Systems can still go down for a variety of reasons. To ensure that your app restarts if the server crashes, use the init system built into your OS. The main init system in use today is [systemd](https://wiki.debian.org/systemd). There are two ways to use init systems with your Express app: - Run your app in a process manager, and install the process manager as a service with the init system. The process manager will restart your app when the app crashes, and the init system will restart the process manager when the OS restarts. This is the recommended approach. - Run your app (and Node) directly with the init system. This is somewhat simpler, but you don't get the additional advantages of using a process manager. ##### Systemd Systemd is a Linux system and service manager. Most major Linux distributions have adopted systemd as their default init system. A systemd service configuration file is called a _unit file_, with a filename ending in `.service`. Here's an example unit file to manage a Node app directly. Replace the values enclosed in `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 --- ## Express utilities URL: https://expressjs.com/en/resources/utils ## Express utility functions The [pillarjs](https://github.com/pillarjs) GitHub organization contains a number of modules for utility functions that may be generally useful. | Utility modules | Description | | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | [cookies](https://www.npmjs.com/package/cookies) | Get and set HTTP(S) cookies that can be signed to prevent tampering, using Keygrip. Can be used with the Node.js HTTP library or as Express middleware. | | [csrf](https://www.npmjs.com/package/csrf) | Contains the logic behind CSRF token creation and verification. Use this module to create custom CSRF middleware. | | [finalhandler](https://www.npmjs.com/package/finalhandler) | Function to invoke as the final step to respond to HTTP request. | | [parseurl](https://www.npmjs.com/package/parseurl) | Parse a URL with caching. | | [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) | Turn an Express-style path string such as ``/user/:name` into a regular expression. | | [resolve-path](https://www.npmjs.com/package/resolve-path) | Resolves a relative path against a root path with validation. | | [router](https://www.npmjs.com/package/router) | Simple middleware-style router. | | [send](https://www.npmjs.com/package/send) | Library for streaming files as a HTTP response, with support for partial responses (ranges), conditional-GET negotiation, and granular events. | For additional low-level HTTP-related modules, see [jshttp](https://github.com/jshttp). --- ## Version Support URL: https://expressjs.com/en/support Only the latest version of any given major release line is supported. Versions that are EOL (end-of-life) _may_ receive updates for critical security vulnerabilities, but the Express team offers no guarantee and does not plan to address or release fixes for any issues found. | Major Version | Minimum Node.js Version | Support Start Date | Support End Date | | -------------------------------------------------------------- | ----------------------- | ------------------ | ---------------- | | [**v5.x**](/5x/api) | 18 | September 2024 | **ongoing** | | [**v4.x**](/4x/api) | 0.10.0 | April 2014 | **ongoing** | | [**v3.x**](/3x/api) | 0.8.0 | October 2012 | July 2015 | | [**v2.x**](https://github.com/expressjs/expressjs.com/tree/2x) | 0.4.1 | March 2011 | July 2012 | | **v1.x** | 0.2.0 | December 2010 | March 2011 | | **v0.14.x** | 0.1.98 | December 2010 | December 2010 | ## Commercial Support Options If you are unable to update to a supported version of Express, please contact one of our partners to receive security updates: - [HeroDevs Never-Ending Support](https://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page)