# 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#', `${options.title}`) .replace('#message#', `

${options.message}

`); return callback(null, rendered); }); }); app.set('views', './views'); // specify the views directory app.set('view engine', 'ntl'); // register the template engine ``` ```ts app.engine( 'ntl', ( filePath: string, options: Record, callback: (e: any, rendered?: string) => void ) => { // 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#', `${options.title}`) .replace('#message#', `

${options.message}

`); return callback(null, rendered); }); } ); app.set('views', './views'); // specify the views directory app.set('view engine', 'ntl'); // register the template engine ``` Your app will now be able to render `.ntl` files. Create a file named `index.ntl` in the `views` directory with the following content. ```pug #title# #message# ``` Then, create the following route in your app. ```js app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }); }); ``` When you make a request to the home page, `index.ntl` will be rendered as HTML. --- ## Express behind proxies URL: https://expressjs.com/en/5x/guide/behind-proxies When running an Express app behind a reverse proxy, some of the Express APIs may return different values than expected. In order to adjust for this, the `trust proxy` application setting may be used to expose information provided by the reverse proxy in the Express APIs. The most common issue is express APIs that expose the client's IP address may instead show an internal IP address of the reverse proxy. When configuring the `trust proxy` setting, it is important to understand the exact setup of the reverse proxy. Since this setting will trust values provided in the request, it is important that the combination of the setting in Express matches how the reverse proxy operates. The application setting `trust proxy` may be set to one of the values listed in the following table.
TypeValue
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; }); ```
Enabling `trust proxy` will have the following impact: The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation. --- ## Debugging Express URL: https://expressjs.com/en/5x/guide/debugging To see all the internal logs used in Express, set the `DEBUG` environment variable to `express:*,router,router:*` when launching your app. Routing is handled by the separate [router](https://github.com/pillarjs/router) package, so its logs live under the `router` namespace and are not included in `express:*`. ```bash $ DEBUG=express:*,router,router:* node index.js ``` On Windows, use the corresponding command. ```bash > $env:DEBUG = "express:*,router,router:*"; node index.js ``` Running this command on a small app with a JSON body parser and a mounted router prints the following output: ```cjs title="index.cjs" const express = require('express'); const app = express(); app.use(express.json()); const users = express.Router(); users.get('/', (req, res) => { res.json([]); }); app.use('/users', users); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); app.use(express.json()); const users = express.Router(); users.get('/', (req, res) => { res.json([]); }); app.use('/users', users); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000); ``` ```bash $ DEBUG=express:*,router,router:* node index.js express:application set "x-powered-by" to true +0ms express:application set "etag" to 'weak' +3ms express:application set "etag fn" to [Function: generateETag] +0ms express:application set "env" to 'development' +1ms express:application set "query parser" to 'simple' +0ms express:application set "query parser fn" to [Function: parse] +0ms express:application set "subdomain offset" to 2 +1ms express:application set "trust proxy" to false +0ms express:application set "trust proxy fn" to [Function: trustNone] +1ms express:application booting in development mode +0ms express:application set "view" to [Function: View] +0ms express:application set "views" to '/projects/example/views' +1ms express:application set "jsonp callback name" to 'callback' +0ms router use '/' jsonParser +0ms router:layer new '/' +0ms router:route new '/' +0ms router:layer new '/' +3ms router:route get / +0ms router:layer new '/' +1ms router use '/users' router +4ms router:layer new '/users' +0ms router:route new '/' +1ms router:layer new '/' +0ms router:route get / +1ms router:layer new '/' +1ms ``` When a request is then made to the app, you will see the logs specified in the Express code: ```bash router dispatching GET /users +712ms router jsonParser : /users +1ms router trim prefix (/users) from url /users +2ms router router /users : /users +0ms router dispatching GET / +0ms ``` To see the logs only from the router implementation, set the value of `DEBUG` to `router,router:*`. Likewise, to see logs only from the application implementation, set the value of `DEBUG` to `express:application`, and so on. ## Using `debug` in your own code The same [debug](https://www.npmjs.com/package/debug) module that Express uses internally is available for your application code. Install it, create one or more loggers scoped to a namespace of your choosing, and call them wherever you would otherwise use `console.log`: ```cjs title="index.cjs" const express = require('express'); const debug = require('debug')('myapp:server'); const app = express(); app.get('/', (req, res) => { debug('handling request from %s', req.ip); res.send('Hello World!'); }); app.listen(3000, () => { debug('listening on port 3000'); }); ``` ```mjs title="index.mjs" const debug = debugModule('myapp:server'); const app = express(); app.get('/', (req, res) => { debug('handling request from %s', req.ip); res.send('Hello World!'); }); app.listen(3000, () => { debug('listening on port 3000'); }); ``` These statements print nothing by default. Enable them through the same `DEBUG` environment variable, using your own namespace: ```bash $ DEBUG=myapp:* node index.js ``` You can specify more than one debug namespace by assigning a comma-separated list of names: ```bash $ DEBUG=myapp:*,router node index.js ``` ## Setting DEBUG in your IDE The `DEBUG` environment variable can be set by any process launcher that supports environment variables, including the run and debug configurations of your IDE. For example, in VS Code you can set it in the `env` property of a launch configuration: ```json title=".vscode/launch.json" { "type": "node", "request": "launch", "name": "Launch Express app", "program": "${workspaceFolder}/index.js", "env": { "DEBUG": "express:*,router,router:*" } } ``` See [Node.js debugging in VS Code](https://code.visualstudio.com/docs/nodejs/nodejs-debugging) for the full list of launch options. ## Using the Node.js inspector Debug logs show what the app did; for stepping through your code with breakpoints, use the built-in Node.js inspector. Start your app with the `--inspect` flag: ```bash $ node --inspect index.js ``` Then attach a debugging client, such as Chrome DevTools (open `chrome://inspect`), VS Code, or any other inspector-capable tool, to set breakpoints in your route handlers and middleware, step through code, and inspect variables. If you need to debug something that happens during startup, use `--inspect-brk` instead, which pauses execution on the first line until a debugger attaches. See the [Node.js debugging guide](https://nodejs.org/learn/getting-started/debugging) for details. ## Debugging the HTTP layer Express runs on top of the Node.js `http` module, which has its own debugging facilities that work with any Express app. Setting the `NODE_DEBUG` environment variable to `http` makes Node.js print internal logs from the HTTP layer, such as connection handling and socket events: ```bash $ NODE_DEBUG=http node index.js ``` You can combine it with other subsystems, such as `net` or `stream`, in a comma-separated list. Be aware that this output can expose sensitive data such as authentication headers, so use it only in development. ## Diagnostics channels Node.js publishes an event for every HTTP request through the [diagnostics_channel](https://nodejs.org/api/diagnostics_channel.html#http) module, which you can subscribe to without patching Express or adding middleware: ```cjs title="index.cjs" const { subscribe } = require('node:diagnostics_channel'); subscribe('http.server.request.start', ({ request }) => { console.log(`${request.method} ${request.url}`); }); ``` ```mjs title="index.mjs" subscribe('http.server.request.start', ({ request }) => { console.log(`${request.method} ${request.url}`); }); ``` Other built-in channels cover the rest of the request lifecycle, such as `http.server.response.finish`, and the client side of `http.request` calls. See the [diagnostics_channel documentation](https://nodejs.org/api/diagnostics_channel.html#http) for the full list. ## Advanced options When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | | ------------------- | ------------------------------------------------- | | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_COLORS` | Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_FD` | File descriptor to write debug output to. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#utilinspectobject-options) for the complete list. --- ## Error Handling URL: https://expressjs.com/en/5x/guide/error-handling _Error Handling_ refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don't need to write your own to get started. ## Catching Errors It's important to ensure that Express catches all errors that occur while running route handlers and middleware. ### Errors in synchronous code Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it. For example: ```js app.get('/', (req, res) => { throw new Error('BROKEN'); // Express will catch this on its own. }); ``` ```ts app.get('/', (req: Request, res: Response) => { throw new Error('BROKEN'); // Express will catch this on its own. }); ``` ### Errors in asynchronous code The recommended way to write asynchronous handlers is with `async` functions. Route handlers and middleware that return a Promise call `next(value)` automatically when they reject or throw an error, and `async` functions always return a Promise, so their errors reach Express with no extra work. For example: ```js app.get('/user/:id', async (req, res) => { const user = await getUserById(req.params.id); res.send(user); }); ``` ```ts app.get('/user/:id', async (req: Request, res: Response) => { const user = await getUserById(req.params.id); res.send(user); }); ``` If `getUserById` throws an error or rejects, `next` will be called with either the thrown error or the rejected value. If no rejected value is provided, `next` will be called with a default Error object provided by the Express router. If you pass anything to the `next()` function (except the string `'route'`), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions. ### Working with promise chains If you build a promise chain instead of using an `async` function, return the promise from the handler and Express will likewise call `next` automatically when it rejects: ```js app.get('/', (req, res) => { return Promise.resolve().then(() => { throw new Error('BROKEN'); // Express will catch this and call next. }); }); ``` ```ts app.get('/', (req: Request, res: Response) => { return Promise.resolve().then(() => { throw new Error('BROKEN'); // Express will catch this and call next. }); }); ``` If the promise is not returned, Express does not know it exists, and you must route the error yourself by providing `next` as the final catch handler. Without it, the rejection would be unhandled and crash the process: ```js app.get('/', (req, res, next) => { Promise.resolve() .then(() => { throw new Error('BROKEN'); }) .catch(next); // Errors will be passed to Express. }); ``` ```ts app.get('/', (req: Request, res: Response, next: NextFunction) => { Promise.resolve() .then(() => { throw new Error('BROKEN'); }) .catch(next); // Errors will be passed to Express. }); ``` This works because if a callback in the promise chain throws, the chain turns that exception into a rejection, which travels down to the final `.catch`. There, `.catch` calls its handler with the error as the first argument, which is exactly the argument `next` expects, so the error reaches Express. ### Working with callback APIs Errors produced by callback-based APIs, such as those in `node:fs`, are not thrown and are not part of any promise. The callback receives them as its first argument, and you must pass them to the `next()` function yourself, where Express will catch and process them. For example: ```js app.get('/', (req, res, next) => { fs.readFile('/file-does-not-exist', (err, data) => { if (err) { next(err); // Pass errors to Express. } else { res.send(data); } }); }); ``` ```ts app.get('/', (req: Request, res: Response, next: NextFunction) => { fs.readFile('/file-does-not-exist', (err, data) => { if (err) { next(err); // Pass errors to Express. } else { res.send(data); } }); }); ``` If the callback in a sequence provides no data, only errors, you can simplify this code as follows: ```js app.get('/', [ function (req, res, next) { fs.writeFile('/inaccessible-path', 'data', next); }, function (req, res) { res.send('OK'); }, ]); ``` ```ts app.get('/', [ function (req: Request, res: Response, next: NextFunction) { fs.writeFile('/inaccessible-path', 'data', next); }, function (req: Request, res: Response) { res.send('OK'); }, ]); ``` In the above example, `next` is provided as the callback for `fs.writeFile`, which is called with or without errors. If there is no error, the second handler is executed, otherwise Express catches and processes the error. You could also use a chain of handlers to rely on synchronous error catching, by reducing the asynchronous code to something trivial. For example: ```js app.get('/', [ function (req, res, next) { fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { res.locals.data = data; next(err); }); }, function (req, res) { res.locals.data = res.locals.data.split(',')[1]; res.send(res.locals.data); }, ]); ``` ```ts app.get('/', [ function (req: Request, res: Response, next: NextFunction) { fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { res.locals.data = data; next(err); }); }, function (req: Request, res: Response) { res.locals.data = res.locals.data.split(',')[1]; res.send(res.locals.data); }, ]); ``` The above example contains a couple of trivial statements following the `readFile` call. If `readFile` causes an error, then it passes the error to Express, otherwise you quickly return to the world of synchronous error handling in the next handler in the chain. Then, the example above tries to process the data. If this fails, then the synchronous error handler will catch it. If you had done this processing inside the `readFile` callback, then the application might exit and the Express error handlers would not run. Finally, for asynchronous code that provides no error-first callback, such as a timer, catch errors inside the asynchronous code itself and pass them to Express: ```js app.get('/', (req, res, next) => { setTimeout(() => { try { throw new Error('BROKEN'); } catch (err) { next(err); } }, 100); }); ``` ```ts app.get('/', (req: Request, res: Response, next: NextFunction) => { setTimeout(() => { try { throw new Error('BROKEN'); } catch (err) { next(err); } }, 100); }); ``` The above example uses a `try...catch` block to catch errors in the asynchronous code and pass them to Express. If the `try...catch` block were omitted, Express would not catch the error since it is not part of the synchronous handler code. Whichever method you use, if you want Express error handlers to be called in and the application to survive, you must ensure that Express receives the error. ## The default error handler Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to `next()` and you do not handle it in a custom error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment. Set the environment variable `NODE_ENV` to `production`, to run the app in production mode. When an error is written, the following information is added to the response: - The `res.statusCode` is set from `err.status` (or `err.statusCode`). If this value is outside the 4xx or 5xx range, it will be set to 500. - The `res.statusMessage` is set according to the status code. - The body will be the HTML of the status code message when in production environment, otherwise will be `err.stack`. - Any headers specified in an `err.headers` object. If you call `next()` with an error after you have started writing the response (for example, if you encounter an error while streaming the response to the client), the Express default error handler closes the connection and fails the request. So when you add a custom error handler, you must delegate to the default Express error handler, when the headers have already been sent to the client: ```js function errorHandler(err, req, res, next) { if (res.headersSent) { return next(err); } res.status(500); res.render('error', { error: err }); } ``` ```ts function errorHandler(err: Error, req: Request, res: Response, next: NextFunction) { if (res.headersSent) { return next(err); } res.status(500); res.render('error', { error: err }); } ``` Note that the default error handler can get triggered if you call `next()` with an error in your code more than once, even if custom error handling middleware is in place. Other error handling middleware can be found at [Express middleware](/resources/middleware). ## Writing error handlers Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: `(err, req, res, next)`. For example: ```js app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); ``` ```ts app.use((err: Error, req: Request, res: Response, next: NextFunction) => { console.error(err.stack); res.status(500).send('Something broke!'); }); ``` You define error-handling middleware last, after other `app.use()` and routes calls; for example: ```cjs title="index.cjs" const bodyParser = require('body-parser'); const methodOverride = require('method-override'); app.use( bodyParser.urlencoded({ extended: true, }) ); app.use(bodyParser.json()); app.use(methodOverride()); app.use((err, req, res, next) => { // logic }); ``` ```mjs title="index.mjs" app.use( bodyParser.urlencoded({ extended: true, }) ); app.use(bodyParser.json()); app.use(methodOverride()); app.use((err, req, res, next) => { // logic }); ``` ```ts title="index.ts" app.use( bodyParser.urlencoded({ extended: true, }) ); app.use(bodyParser.json()); app.use(methodOverride()); app.use((err: Error, req: Request, res: Response, next: NextFunction) => { // logic }); ``` Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string. For organizational (and higher-level framework) purposes, you can define several error-handling middleware functions, much as you would with regular middleware functions. For example, to define an error-handler for requests made by using `XHR` and those without: ```cjs title="index.cjs" const bodyParser = require('body-parser'); const methodOverride = require('method-override'); app.use( bodyParser.urlencoded({ extended: true, }) ); app.use(bodyParser.json()); app.use(methodOverride()); app.use(logErrors); app.use(clientErrorHandler); app.use(errorHandler); ``` ```mjs title="index.mjs" app.use( bodyParser.urlencoded({ extended: true, }) ); app.use(bodyParser.json()); app.use(methodOverride()); app.use(logErrors); app.use(clientErrorHandler); app.use(errorHandler); ``` In this example, the generic `logErrors` might write request and error information to `stderr`, for example: ```js function logErrors(err, req, res, next) { console.error(err.stack); next(err); } ``` ```ts function logErrors(err: Error, req: Request, res: Response, next: NextFunction) { console.error(err.stack); next(err); } ``` Also in this example, `clientErrorHandler` is defined as follows; in this case, the error is explicitly passed along to the next one. Notice that when you do not call `next` in an error-handling function, you are responsible for writing (and ending) the response. Otherwise, those requests will "hang" and will not be eligible for garbage collection. ```js function clientErrorHandler(err, req, res, next) { if (req.xhr) { res.status(500).send({ error: 'Something failed!' }); } else { next(err); } } ``` ```ts function clientErrorHandler(err: Error, req: Request, res: Response, next: NextFunction) { if (req.xhr) { res.status(500).send({ error: 'Something failed!' }); } else { next(err); } } ``` Implement the "catch-all" `errorHandler` function as follows (for example): ```js function errorHandler(err, req, res, next) { res.status(500); res.render('error', { error: err }); } ``` ```ts function errorHandler(err: Error, req: Request, res: Response, next: NextFunction) { res.status(500); res.render('error', { error: err }); } ``` If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. For example: ```js app.get( '/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { // continue handling this request next('route'); } else { next(); } }, (req, res, next) => { PaidContent.find((err, doc) => { if (err) return next(err); res.json(doc); }); } ); ``` ```ts app.get( '/a_route_behind_paywall', (req: Request, res: Response, next: NextFunction) => { if (!req.user.hasPaid) { // continue handling this request next('route'); } else { next(); } }, (req: Request, res: Response, next: NextFunction) => { PaidContent.find((err, doc) => { if (err) return next(err); res.json(doc); }); } ); ``` In this example, the `getPaidContent` handler will be skipped but any remaining handlers in `app` for `/a_route_behind_paywall` would continue to be executed. Calls to `next()` and `next(err)` indicate that the current handler is complete and in what state. `next(err)` will skip all remaining handlers in the chain except for those that are set up to handle errors as described above. --- ## Overriding the Express API URL: https://expressjs.com/en/5x/guide/overriding-express-api The Express API consists of various methods and properties on the [request](/api/request) and [response](/api/response) objects. These are inherited by prototype. There are two extension points for the Express API: 1. The global prototypes at `express.request` and `express.response`. 2. App-specific prototypes at `app.request` and `app.response`. Altering the global prototypes will affect all loaded Express apps in the same process. If desired, alterations can be made app-specific by only altering the app-specific prototypes after creating a new app. ## Methods You can override the signature and behavior of existing methods with your own, by assigning a custom function. Following is an example of overriding the behavior of [res.sendStatus](/api/response/#ressendstatus). ```js app.response.sendStatus = function (statusCode, type, message) { // code is intentionally kept simple for demonstration purpose return this.contentType(type).status(statusCode).send(message); }; ``` ```ts // Broaden the type of sendStatus so call sites accept the new arguments. declare module 'express-serve-static-core' { interface Response { sendStatus(statusCode: number, type: string, message: string): this; } } app.response.sendStatus = function ( this: Response, statusCode: number, type: string, message: string ) { // code is intentionally kept simple for demonstration purpose return this.contentType(type).status(statusCode).send(message); } as Response['sendStatus']; ``` The above implementation completely changes the original signature of `res.sendStatus`. It now accepts a status code, encoding type, and the message to be sent to the client. In TypeScript, augmenting `express-serve-static-core` adds the new overload to the `Response` type so call sites such as `res.sendStatus(404, 'application/json', body)` type-check. The assignment is cast with `as Response['sendStatus']` because replacing a method with a different signature cannot be checked against the original declaration. The overridden method may now be used this way: ```js res.sendStatus(404, 'application/json', '{"error":"resource not found"}'); ``` ## Properties Properties in the Express API are either: 1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) 2. Defined as getters (ex: `req.secure`, `req.ip`) Since properties under category 1 are dynamically assigned on the `request` and `response` objects in the context of the current request-response cycle, their behavior cannot be overridden. Properties under category 2 can be overwritten using the Express API extensions API. The following code rewrites how the value of `req.ip` is to be derived. Now, it simply returns the value of the `Client-IP` request header. ```js Object.defineProperty(app.request, 'ip', { configurable: true, enumerable: true, get() { return this.get('Client-IP'); }, }); ``` ```ts Object.defineProperty(app.request, 'ip', { configurable: true, enumerable: true, get(this: Request) { return this.get('Client-IP'); }, }); ``` ## Extending the API in TypeScript The sections above override members that Express already provides. To add your own properties or methods to the request or response, describe them to TypeScript with [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) on the `Express` namespace. Put the augmentation in a `.d.ts` file that is part of your project. No `tsconfig.json` change is needed unless a custom `include` does not cover its location. For example, an authentication middleware may attach a `user` to the request, and you might add a `sendError` helper to the response: ```ts title="types/express.d.ts" interface User { id: string; name: string; } declare global { namespace Express { interface Request { user?: User; } interface Response { sendError(status: number, message: string): this; } } } export {}; ``` The additions are now known throughout the application: ```ts app.use((req: Request, res: Response, next: NextFunction) => { req.user = { id: '1', name: 'Tobi' }; next(); }); app.response.sendError = function (this: Response, status: number, message: string) { return this.status(status).json({ error: message }); }; app.get('/', (req: Request, res: Response) => { if (!req.user) { res.sendError(401, 'unauthorized'); return; } res.send(req.user.name); }); ``` Declare custom request properties as optional (`user?`). The type applies to every request, but TypeScript cannot know which middleware ran before a given handler, so a required property would be a false guarantee. Check for the value (as with `if (!req.user)` above) before relying on it. Adding a new method needs no cast, unlike [overriding](#methods) an existing method with a different signature, because the method did not previously exist on the type. ## Prototype In order to provide the Express API, the request/response objects passed to Express (via `app(req, res)`, for example) need to inherit from the same prototype chain. By default, this is `http.IncomingRequest.prototype` for the request and `http.ServerResponse.prototype` for the response. Unless necessary, it is recommended that this be done only at the application level, rather than globally. Also, take care that the prototype that is being used matches the functionality as closely as possible to the default prototypes. ```js // Use FakeRequest and FakeResponse in place of http.IncomingRequest and http.ServerResponse // for the given app reference Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype); Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype); ``` --- ## Routing URL: https://expressjs.com/en/5x/guide/routing _Routing_ refers to how an application's endpoints (URIs) respond to client requests. For an introduction to routing, see [Basic routing](/starter/basic-routing). You define routing using methods of the Express `app` object that correspond to HTTP methods; for example, `app.get()` to handle GET requests and `app.post` to handle POST requests. For a full list, see [app.METHOD](/api/application#appmethod). You can also use [app.all()](/api/application#appall) to handle all HTTP methods and [app.use()](/api/application#appuse) to specify middleware as the callback function (See [Using middleware](/guide/using-middleware) for details). These routing methods specify a callback function (sometimes called a "handler function") that Express automatically runs when the application receives a request matching the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function. In fact, the routing methods can have more than one callback function as arguments. With multiple callback functions, it is important to provide `next` as an argument to the callback function and then call `next()` within the body of the function to hand off control to the next callback. The following code is an example of a very basic route. ```cjs title="index.cjs" const express = require('express'); const app = express(); // respond with "hello world" when a GET request is made to the homepage app.get('/', (req, res) => { res.send('hello world'); }); ``` ```mjs title="index.mjs" const app = express(); // respond with "hello world" when a GET request is made to the homepage app.get('/', (req, res) => { res.send('hello world'); }); ``` ```ts title="index.ts" const app: Express = express(); // respond with "hello world" when a GET request is made to the homepage app.get('/', (req: Request, res: Response) => { res.send('hello world'); }); ``` ## Route methods A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class. The following code is an example of routes that are defined for the `GET` and the `POST` methods to the root of the app. ```js // GET method route app.get('/', (req, res) => { res.send('GET request to the homepage'); }); // POST method route app.post('/', (req, res) => { res.send('POST request to the homepage'); }); ``` ```ts // GET method route app.get('/', (req: Request, res: Response) => { res.send('GET request to the homepage'); }); // POST method route app.post('/', (req: Request, res: Response) => { res.send('POST request to the homepage'); }); ``` Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on. For a full list, see [app.METHOD](/api/application#appmethod). There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `QUERY`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#httpmethods). ```js app.all('/secret', (req, res, next) => { console.log('Accessing the secret section ...'); next(); // pass control to the next handler }); ``` ```ts app.all('/secret', (req: Request, res: Response, next: NextFunction) => { console.log('Accessing the secret section ...'); next(); // pass control to the next handler }); ``` ## Route paths Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings or regular expressions. They can also capture values from the URL, as described in [Route parameters](#route-parameters) below. Express uses [path-to-regexp](https://www.npmjs.com/package/path-to-regexp) v8 for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. [Express Playground Router](https://bjohansebas.github.io/playground-router/) is a handy tool for testing basic Express routes, although it does not support pattern matching. ### String paths String paths match requests exactly. The dot (`.`) and hyphen (`-`) are interpreted literally. Query strings are not part of the route path. ```js app.get('/', (req, res) => { res.send('root'); }); app.get('/about', (req, res) => { res.send('about'); }); app.get('/random.text', (req, res) => { res.send('random.text'); }); ``` ```ts app.get('/', (req: Request, res: Response) => { res.send('root'); }); app.get('/about', (req: Request, res: Response) => { res.send('about'); }); app.get('/random.text', (req: Request, res: Response) => { res.send('random.text'); }); ``` The characters `?`, `+`, `*`, `[]`, `()`, and `!` are reserved and cannot be used as literal characters in route paths, and braces are reserved for [optional segments](#optional-segments). Use `\` to escape them if needed. ### Regular expressions You can also use regular expressions as route paths. This is useful when you need more complex matching logic. ```js // Matches any path containing "a" app.get(/a/, (req, res) => { res.send('/a/'); }); // Matches paths ending with "fly" (butterfly, dragonfly, etc.) app.get(/.*fly$/, (req, res) => { res.send('/.*fly$/'); }); ``` ```ts // Matches any path containing "a" app.get(/a/, (req: Request, res: Response) => { res.send('/a/'); }); // Matches paths ending with "fly" (butterfly, dragonfly, etc.) app.get(/.*fly$/, (req: Request, res: Response) => { res.send('/.*fly$/'); }); ``` ## Route parameters Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the `req.params` object, with the name of the route parameter specified in the path as their respective keys. They come in three forms: [named parameters](#named-parameters) (`:name`), [wildcards](#wildcards) (`*name`), and [optional segments](#optional-segments), which wrap either of them in braces. ### Named parameters Named parameters capture a single path segment at their position in the URL, or part of one when combined with literal characters, as shown further below. ``` Route path: /users/:userId/books/:bookId Request URL: http://localhost:3000/users/34/books/8989 req.params: { "userId": "34", "bookId": "8989" } ``` To define routes with route parameters, simply specify the route parameters in the path of the route as shown below. ```js app.get('/users/:userId/books/:bookId', (req, res) => { res.send(req.params); }); ``` In TypeScript, `@types/express` infers the parameters from the route path, so in the handler above `req.params.userId` and `req.params.bookId` are already typed as `string` with no extra annotation. Reading a name that is not in the route (such as `req.params.other`) is a type error. You only need to annotate the parameters when the handler is defined separately from the route, because the type checker can no longer see the path. In that case, pass them as the first type argument of `Request`: ```ts const sendParams = (req: Request<{ userId: string; bookId: string }>, res: Response) => { res.send(req.params); }; app.get('/users/:userId/books/:bookId', sendParams); ``` The name of route parameters must be a valid JavaScript identifier. Other names can be used by quoting them, for example `:"user-name"`. Since the hyphen (`-`) and the dot (`.`) are interpreted literally, they can be used along with route parameters for useful purposes. ``` Route path: /flights/:from-:to Request URL: http://localhost:3000/flights/LAX-SFO req.params: { "from": "LAX", "to": "SFO" } ``` ``` Route path: /plantae/:genus.:species Request URL: http://localhost:3000/plantae/Prunus.persica req.params: { "genus": "Prunus", "species": "persica" } ``` Regexp characters are not supported inside string paths, so a parameter cannot be restricted with a suffix such as `:userId(\d+)`. Use an array of paths or a full regular expression instead. See the [path route matching syntax](/guide/migrating-5#path-route-matching-syntax) for more information. ### Wildcards Wildcards match any path after a prefix. Like other route parameters they must have a name, but they are captured as an array of path segments instead of a string. ```js app.get('/files/*filepath', (req, res) => { // GET /files/images/logo.png console.dir(req.params.filepath); // => [ 'images', 'logo.png' ] res.send(`File: ${req.params.filepath.join('/')}`); }); ``` ```ts app.get('/files/*filepath', (req: Request<{ filepath: string[] }>, res: Response) => { // GET /files/images/logo.png console.dir(req.params.filepath); // => [ 'images', 'logo.png' ] res.send(`File: ${req.params.filepath.join('/')}`); }); ``` To also match the root path, wrap the wildcard in braces: ```js // Matches / , /foo , /foo/bar , etc. app.get('/{*splat}', (req, res) => { // GET / => req.params = {}, splat is omitted // GET /foo/bar => req.params.splat = [ 'foo', 'bar' ] res.send('ok'); }); ``` ```ts // Matches / , /foo , /foo/bar , etc. app.get('/{*splat}', (req: Request, res: Response) => { // GET / => req.params = {}, splat is omitted // GET /foo/bar => req.params.splat = [ 'foo', 'bar' ] res.send('ok'); }); ``` ### Optional segments Use braces to define optional segments in a route path. When the segment is not present, the parameter is omitted from `req.params`. ```js app.get('/:file{.:ext}', (req, res) => { // GET /image.png => req.params = { file: 'image', ext: 'png' } // GET /image => req.params = { file: 'image' } res.send('ok'); }); ``` ```ts app.get('/:file{.:ext}', (req: Request, res: Response) => { // GET /image.png => req.params = { file: 'image', ext: 'png' } // GET /image => req.params = { file: 'image' } res.send('ok'); }); ``` The braces can also wrap a whole parameter to make it optional. Note that everything inside the braces is optional, so the position of the slash matters: ```js app.get('/user/{:id}', (req, res) => { // GET /user/42 => req.params = { id: '42' } // GET /user/ => req.params = {} // GET /user => 404, only the parameter is optional res.send('ok'); }); app.get('/order{/:id}', (req, res) => { // GET /order/42 => req.params = { id: '42' } // GET /order => req.params = {}, the whole segment is optional res.send('ok'); }); ``` ```ts app.get('/user/{:id}', (req: Request, res: Response) => { // GET /user/42 => req.params = { id: '42' } // GET /user/ => req.params = {} // GET /user => 404, only the parameter is optional res.send('ok'); }); app.get('/order{/:id}', (req: Request, res: Response) => { // GET /order/42 => req.params = { id: '42' } // GET /order => req.params = {}, the whole segment is optional res.send('ok'); }); ``` Do not confuse the position of the slash in the route path with the [`strict routing` setting](/api/application/#application-settings), which is about the request URL: it controls whether a URL ending in a slash that the route path does not require still matches. For example, a request for `/order/` matches the `/order{/:id}` route by default, but returns a 404 error when strict routing is enabled; the trailing slash of `/user/` is unaffected because the `/user/{:id}` route requires it. All the requests commented in the examples above behave the same regardless of that setting. ## Route handlers You can provide multiple callback functions that behave like [middleware](/guide/using-middleware) to handle a request. The only exception is that these callbacks might invoke `next('route')` to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route. ```js app.get('/user/:id', (req, res, next) => { if (req.params.id === '0') { return next('route'); } res.send(`User ${req.params.id}`); }); app.get('/user/:id', (req, res) => { res.send('Special handler for user ID 0'); }); ``` ```ts app.get('/user/:id', (req: Request, res: Response, next: NextFunction) => { if (req.params.id === '0') { return next('route'); } res.send(`User ${req.params.id}`); }); app.get('/user/:id', (req: Request, res: Response) => { res.send('Special handler for user ID 0'); }); ``` In this example: - `GET /user/5` → handled by first route → sends "User 5" - `GET /user/0` → first route calls `next('route')`, skipping to the next matching `/user/:id` route Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples. A single callback function can handle a route. For example: ```js app.get('/example/a', (req, res) => { res.send('Hello from A!'); }); ``` ```ts app.get('/example/a', (req: Request, res: Response) => { res.send('Hello from A!'); }); ``` More than one callback function can handle a route (make sure you specify the `next` object). For example: ```js app.get( '/example/b', (req, res, next) => { console.log('the response will be sent by the next function ...'); next(); }, (req, res) => { res.send('Hello from B!'); } ); ``` ```ts app.get( '/example/b', (req: Request, res: Response, next: NextFunction) => { console.log('the response will be sent by the next function ...'); next(); }, (req: Request, res: Response) => { res.send('Hello from B!'); } ); ``` An array of callback functions can handle a route. For example: ```js const cb0 = function (req, res, next) { console.log('CB0'); next(); }; const cb1 = function (req, res, next) { console.log('CB1'); next(); }; const cb2 = function (req, res) { res.send('Hello from C!'); }; app.get('/example/c', [cb0, cb1, cb2]); ``` ```ts const cb0 = function (req: Request, res: Response, next: NextFunction) { console.log('CB0'); next(); }; const cb1 = function (req: Request, res: Response, next: NextFunction) { console.log('CB1'); next(); }; const cb2 = function (req: Request, res: Response) { res.send('Hello from C!'); }; app.get('/example/c', [cb0, cb1, cb2]); ``` A combination of independent functions and arrays of functions can handle a route. For example: ```js const cb0 = function (req, res, next) { console.log('CB0'); next(); }; const cb1 = function (req, res, next) { console.log('CB1'); next(); }; app.get( '/example/d', [cb0, cb1], (req, res, next) => { console.log('the response will be sent by the next function ...'); next(); }, (req, res) => { res.send('Hello from D!'); } ); ``` ```ts const cb0 = function (req: Request, res: Response, next: NextFunction) { console.log('CB0'); next(); }; const cb1 = function (req: Request, res: Response, next: NextFunction) { console.log('CB1'); next(); }; app.get( '/example/d', [cb0, cb1], (req: Request, res: Response, next: NextFunction) => { console.log('the response will be sent by the next function ...'); next(); }, (req: Request, res: Response) => { res.send('Hello from D!'); } ); ``` ## Response methods The methods on the [response object](/api/response) (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging. | Method | Description | | ----------------------------------------------- | ------------------------------------------------------------------------------------- | | [res.download()](/api/response#resdownload) | Prompt a file to be downloaded. | | [res.end()](/api/response#resend) | End the response process. | | [res.json()](/api/response#resjson) | Send a JSON response. | | [res.jsonp()](/api/response#resjsonp) | Send a JSON response with JSONP support. | | [res.redirect()](/api/response#resredirect) | Redirect a request. | | [res.render()](/api/response#resrender) | Render a view template. | | [res.send()](/api/response#ressend) | Send a response of various types. | | [res.sendFile()](/api/response#ressendfile) | Send a file as an octet stream. | | [res.sendStatus()](/api/response#ressendstatus) | Set the response status code and send its string representation as the response body. | ## app.route() You can create chainable route handlers for a route path by using `app.route()`. Because the path is specified in a single location, this helps to create modular routes and reduces redundancy and typos. For more information about routes, see the [Router() documentation](/api/router). Here is an example of chained route handlers that are defined by using `app.route()`. ```js app .route('/book') .get((req, res) => { res.send('Get a random book'); }) .post((req, res) => { res.send('Add a book'); }) .put((req, res) => { res.send('Update the book'); }); ``` ```ts app .route('/book') .get((req: Request, res: Response) => { res.send('Get a random book'); }) .post((req: Request, res: Response) => { res.send('Add a book'); }) .put((req: Request, res: Response) => { res.send('Update the book'); }); ``` ## express.Router Use the `express.Router` class to create modular, mountable route handlers. A `Router` instance is a complete middleware and routing system; for this reason, it is often referred to as a "mini-app". The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app. Create a router file named `birds.js` in the app directory, with the following content: ```cjs title="birds.cjs" const express = require('express'); const router = express.Router(); // middleware that is specific to this router const timeLog = (req, res, next) => { console.log('Time: ', Date.now()); next(); }; router.use(timeLog); // define the home page route router.get('/', (req, res) => { res.send('Birds home page'); }); // define the about route router.get('/about', (req, res) => { res.send('About birds'); }); module.exports = router; ``` ```mjs title="birds.mjs" const router = express.Router(); // middleware that is specific to this router const timeLog = (req, res, next) => { console.log('Time: ', Date.now()); next(); }; router.use(timeLog); // define the home page route router.get('/', (req, res) => { res.send('Birds home page'); }); // define the about route router.get('/about', (req, res) => { res.send('About birds'); }); export default router; ``` ```ts title="birds.ts" const router = express.Router(); // middleware that is specific to this router const timeLog = (req: Request, res: Response, next: NextFunction) => { console.log('Time: ', Date.now()); next(); }; router.use(timeLog); // define the home page route router.get('/', (req: Request, res: Response) => { res.send('Birds home page'); }); // define the about route router.get('/about', (req: Request, res: Response) => { res.send('About birds'); }); export default router; ``` Then, load the router module in the app: ```cjs title="index.cjs" const birds = require('./birds'); // ... app.use('/birds', birds); ``` ```mjs title="index.mjs" // ... app.use('/birds', birds); ``` The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route. But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the [Router constructor](/api/express/#expressrouter). ```js const router = express.Router({ mergeParams: true }); ``` --- ## Using middleware URL: https://expressjs.com/en/5x/guide/using-middleware Express is a routing and middleware web framework with minimal functionality of its own: an Express application is essentially a series of middleware function calls executed during the request-response cycle. _Middleware_ functions are functions that have access to: - The [request object](/api/request) (`req`) - The [response object](/api/response) (`res`) - The next middleware function in the application's request-response cycle, commonly named `next` Middleware functions can perform the following tasks: - Execute any code. - Modify the request and response objects. - End the request-response cycle. - Pass control to the next middleware function. If a middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging. An Express application can use the following types of middleware: - [Application-level middleware](#application-level-middleware) - [Router-level middleware](#router-level-middleware) - [Error-handling middleware](#error-handling-middleware) - [Built-in middleware](#built-in-middleware) - [Third-party middleware](#third-party-middleware) You can load application-level and router-level middleware with an optional mount path. Multiple middleware functions can also be loaded together, which creates a middleware sub-stack at a mount point. ## Application-level middleware Bind application-level middleware to an instance of the [app object](/api/application) by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the lowercase HTTP method of the request that the middleware function handles, such as `get`, `post`, `put`, or `delete`. ### Middleware without a mount path The following middleware function runs every time the app receives a request: ```cjs title="index.cjs" const express = require('express'); const app = express(); app.use((req, res, next) => { console.log('Time:', Date.now()); next(); }); ``` ```mjs title="index.mjs" const app = express(); app.use((req, res, next) => { console.log('Time:', Date.now()); next(); }); ``` ```ts title="index.ts" const app: Express = express(); app.use((req: Request, res: Response, next: NextFunction) => { console.log('Time:', Date.now()); next(); }); ``` ### Middleware mounted on a path The following middleware function runs for any type of HTTP request on the `/user/:id` path: ```js app.use('/user/:id', (req, res, next) => { console.log('Request Type:', req.method); next(); }); ``` ```ts app.use('/user/:id', (req: Request, res: Response, next: NextFunction) => { console.log('Request Type:', req.method); next(); }); ``` ### Route handlers This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path: ```js app.get('/user/:id', (req, res) => { res.send('USER'); }); ``` ```ts app.get('/user/:id', (req: Request, res: Response) => { res.send('USER'); }); ``` ### Middleware sub-stacks Multiple middleware functions can be loaded together at a mount point to form a middleware sub-stack. This example prints request info for any type of HTTP request to the `/user/:id` path: ```js app.use( '/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl); next(); }, (req, res, next) => { console.log('Request Type:', req.method); next(); } ); ``` ```ts app.use( '/user/:id', (req: Request, res: Response, next: NextFunction) => { console.log('Request URL:', req.originalUrl); next(); }, (req: Request, res: Response, next: NextFunction) => { console.log('Request Type:', req.method); next(); } ); ``` ### Multiple route handlers Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the `/user/:id` path. The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle. ```js app.get( '/user/:id', (req, res, next) => { console.log('ID:', req.params.id); next(); }, (req, res) => { res.send('User Info'); } ); // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res) => { res.send(req.params.id); }); ``` ```ts app.get( '/user/:id', (req: Request, res: Response, next: NextFunction) => { console.log('ID:', req.params.id); next(); }, (req: Request, res: Response) => { res.send('User Info'); } ); // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req: Request, res: Response) => { res.send(req.params.id); }); ``` ### Skipping to the next route Call `next('route')` to skip the remaining middleware functions in a router middleware stack and pass control to the next route. `next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. In the following example, if the user ID is `0`, the first handler skips to the next route, which sends a special response: ```js app.get( '/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route'); // otherwise pass the control to the next middleware function in this stack else next(); }, (req, res) => { // send a regular response res.send('regular'); } ); // handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res) => { res.send('special'); }); ``` ```ts app.get( '/user/:id', (req: Request, res: Response, next: NextFunction) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route'); // otherwise pass the control to the next middleware function in this stack else next(); }, (req: Request, res: Response) => { // send a regular response res.send('regular'); } ); // handler for the /user/:id path, which sends a special response app.get('/user/:id', (req: Request, res: Response) => { res.send('special'); }); ``` ### Reusable middleware arrays Middleware functions can also be grouped into arrays for better reusability. This example shows an array with a middleware sub-stack that handles GET requests to the `/user/:id` path: ```js function logOriginalUrl(req, res, next) { console.log('Request URL:', req.originalUrl); next(); } function logMethod(req, res, next) { console.log('Request Type:', req.method); next(); } const logStuff = [logOriginalUrl, logMethod]; app.get('/user/:id', logStuff, (req, res) => { res.send('User Info'); }); ``` ```ts function logOriginalUrl(req: Request, res: Response, next: NextFunction) { console.log('Request URL:', req.originalUrl); next(); } function logMethod(req: Request, res: Response, next: NextFunction) { console.log('Request Type:', req.method); next(); } const logStuff = [logOriginalUrl, logMethod]; app.get('/user/:id', logStuff, (req: Request, res: Response) => { res.send('User Info'); }); ``` ## Router-level middleware Router-level middleware works the same way as application-level middleware, except it is bound to an instance of `express.Router()`. ```js const router = express.Router(); ``` ```ts const router = express.Router(); ``` Load router-level middleware by using the `router.use()` and `router.METHOD()` functions. The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware: ```cjs title="index.cjs" const express = require('express'); const app = express(); const router = express.Router(); // a middleware function with no mount path. This code is executed for every request to the router router.use((req, res, next) => { console.log('Time:', Date.now()); next(); }); // a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path router.use( '/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl); next(); }, (req, res, next) => { console.log('Request Type:', req.method); next(); } ); // a middleware sub-stack that handles GET requests to the /user/:id path router.get( '/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route'); // otherwise pass control to the next middleware function in this stack else next(); }, (req, res) => { // render a regular page res.render('regular'); } ); // handler for the /user/:id path, which renders a special page router.get('/user/:id', (req, res) => { console.log(req.params.id); res.render('special'); }); // mount the router on the app app.use('/', router); ``` ```mjs title="index.mjs" const app = express(); const router = express.Router(); // a middleware function with no mount path. This code is executed for every request to the router router.use((req, res, next) => { console.log('Time:', Date.now()); next(); }); // a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path router.use( '/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl); next(); }, (req, res, next) => { console.log('Request Type:', req.method); next(); } ); // a middleware sub-stack that handles GET requests to the /user/:id path router.get( '/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route'); // otherwise pass control to the next middleware function in this stack else next(); }, (req, res) => { // render a regular page res.render('regular'); } ); // handler for the /user/:id path, which renders a special page router.get('/user/:id', (req, res) => { console.log(req.params.id); res.render('special'); }); // mount the router on the app app.use('/', router); ``` ```ts title="index.ts" const app: Express = express(); const router = express.Router(); // a middleware function with no mount path. This code is executed for every request to the router router.use((req: Request, res: Response, next: NextFunction) => { console.log('Time:', Date.now()); next(); }); // a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path router.use( '/user/:id', (req: Request, res: Response, next: NextFunction) => { console.log('Request URL:', req.originalUrl); next(); }, (req: Request, res: Response, next: NextFunction) => { console.log('Request Type:', req.method); next(); } ); // a middleware sub-stack that handles GET requests to the /user/:id path router.get( '/user/:id', (req: Request, res: Response, next: NextFunction) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route'); // otherwise pass control to the next middleware function in this stack else next(); }, (req: Request, res: Response) => { // render a regular page res.render('regular'); } ); // handler for the /user/:id path, which renders a special page router.get('/user/:id', (req: Request, res: Response) => { console.log(req.params.id); res.render('special'); }); // mount the router on the app app.use('/', router); ``` ### Skipping out of a router Use `next('router')` to skip the rest of the router's middleware functions and pass control back out of the router instance. In the following example, the router only responds when the request includes an `x-auth` header. Otherwise, `next('router')` exits the router and the app responds with a 401 status: ```cjs title="index.cjs" const express = require('express'); const app = express(); const router = express.Router(); // predicate the router with a check and bail out when needed router.use((req, res, next) => { if (!req.headers['x-auth']) return next('router'); next(); }); router.get('/user/:id', (req, res) => { res.send('hello, user!'); }); // use the router and 401 anything falling through app.use('/admin', router, (req, res) => { res.sendStatus(401); }); ``` ```mjs title="index.mjs" const app = express(); const router = express.Router(); // predicate the router with a check and bail out when needed router.use((req, res, next) => { if (!req.headers['x-auth']) return next('router'); next(); }); router.get('/user/:id', (req, res) => { res.send('hello, user!'); }); // use the router and 401 anything falling through app.use('/admin', router, (req, res) => { res.sendStatus(401); }); ``` ```ts title="index.ts" const app: Express = express(); const router = express.Router(); // predicate the router with a check and bail out when needed router.use((req: Request, res: Response, next: NextFunction) => { if (!req.headers['x-auth']) return next('router'); next(); }); router.get('/user/:id', (req: Request, res: Response) => { res.send('hello, user!'); }); // use the router and 401 anything falling through app.use('/admin', router, (req: Request, res: Response) => { res.sendStatus(401); }); ``` ## Error-handling middleware Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`: ```js app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); ``` ```ts app.use((err: Error, req: Request, res: Response, next: NextFunction) => { console.error(err.stack); res.status(500).send('Something broke!'); }); ``` Error-handling middleware always takes _four_ arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don't need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors. For more information, see the [Error handling](/guide/error-handling) guide. ## Built-in middleware Express has the following built-in middleware functions: - [express.static](/api/express/#expressstatic) serves static assets such as HTML files, images, and so on. - [express.json](/api/express/#expressjson) parses incoming requests with JSON payloads. - [express.raw](/api/express/#expressraw) parses incoming requests with Buffer payloads. - [express.text](/api/express/#expresstext) parses incoming requests with text payloads. - [express.urlencoded](/api/express/#expressurlencoded) parses incoming requests with URL-encoded payloads. ## Third-party middleware Use third-party middleware to add functionality to Express apps. Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level. The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`: ```cjs title="index.cjs" const express = require('express'); const app = express(); const cookieParser = require('cookie-parser'); // load the cookie-parsing middleware app.use(cookieParser()); ``` ```mjs title="index.mjs" const app = express(); // load the cookie-parsing middleware app.use(cookieParser()); ``` ```ts title="index.ts" const app: Express = express(); // load the cookie-parsing middleware app.use(cookieParser()); ``` For a partial list of third-party middleware functions that are commonly used with Express, see the [Third-party middleware](/resources/middleware) page. --- ## Using template engines with Express URL: https://expressjs.com/en/5x/guide/using-template-engines A _template engine_ enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page. The [Express application generator](/starter/generator) uses [Pug](https://pugjs.org/api/getting-started.html) as its default, but it can generate apps configured for Handlebars-compatible engines such as [hbs](https://www.npmjs.com/package/hbs), [EJS](https://www.npmjs.com/package/ejs), among others. For apps created by the generator, these settings are added to the generated `app.js`. For apps you create without the generator, set the following [application setting properties](/api/application/#appset) yourself: - `views`, the directory where the template files are located. Eg: `app.set('views', './views')`. This defaults to the `views` directory in the application root directory. - `view engine`, the template engine to use. For example, to use the Pug template engine: `app.set('view engine', 'pug')`. Then install the corresponding Express-compatible template engine npm package; for example to install Pug: Express-compliant template engines such as Pug export a function named `__express(filePath, options, callback)`, which `res.render()` calls to render the template code. Some template engines do not follow this convention. The [@ladjs/consolidate](https://www.npmjs.com/package/@ladjs/consolidate) library follows this convention by mapping all of the popular Node.js template engines, and therefore works seamlessly within Express. For example, install [hbs](https://www.npmjs.com/package/hbs) or any other Express-compatible Handlebars view engine instead of the raw `handlebars` package by itself. After the view engine is set, you don't have to specify the engine or load the template engine module in your app; Express loads the module internally, for example: ```js app.set('view engine', 'pug'); ``` Then, create a Pug template file named `index.pug` in the `views` directory, with the following content: ```pug html head title= title body h1= message ``` Create a route to render the `index.pug` file. If the `view engine` property is not set, you must specify the extension of the `view` file. Otherwise, you can omit it. ```js app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }); }); ``` ```ts app.get('/', (req: Request, res: Response) => { res.render('index', { title: 'Hey', message: 'Hello there!' }); }); ``` When you make a request to the home page, the `index.pug` file will be rendered as HTML. The view engine cache does not cache the contents of the template's output, only the underlying template itself. The view is still re-rendered with every request even when the cache is on. --- ## Writing middleware for use in Express apps URL: https://expressjs.com/en/5x/guide/writing-middleware _Middleware_ functions are functions that have access to the [request object](/api/request) (`req`), the [response object](/api/response) (`res`), and the `next` function in the application's request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. Middleware functions can perform the following tasks: - Execute any code. - Make changes to the request and the response objects. - End the request-response cycle. - Call the next middleware in the stack. If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging. The following figure shows the elements of a middleware function call: ![Elements of a middleware function call](/images/express-mw.png) Starting with Express 5, middleware functions that return a Promise will call `next(value)` when they reject or throw an error. `next` will be called with either the rejected value or the thrown Error. ## Example Here is an example of a simple "Hello World" Express application. The remainder of this article will define and add three middleware functions to the application: one called `myLogger` that prints a simple log message, one called `requestTime` that displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies. ```cjs title="index.cjs" const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000); ``` ```ts title="index.ts" const app: Express = express(); app.get('/', (req: Request, res: Response) => { res.send('Hello World!'); }); app.listen(3000); ``` ### Middleware function myLogger Here is a simple example of a middleware function called "myLogger". This function just prints "LOGGED" when a request to the app passes through it. The middleware function is assigned to a variable named `myLogger`. ```js const myLogger = function (req, res, next) { console.log('LOGGED'); next(); }; ``` ```ts const myLogger = function (req: Request, res: Response, next: NextFunction) { console.log('LOGGED'); next(); }; ``` Here `myLogger` is defined on its own rather than passed directly to `app.use()`, so TypeScript has no context to infer its parameters and they are annotated explicitly. You can instead type the whole function as `RequestHandler`, which types `req`, `res`, and `next` for you. When the middleware is written inline in the `app.use()` call, Express infers those three parameters and no annotations are needed. Notice the call above to `next()`. Calling this function invokes the next middleware function in the app. The `next()` function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The `next()` function could be named anything, but by convention it is always named "next". To avoid confusion, always use this convention. To load the middleware function, call `app.use()`, specifying the middleware function. For example, the following code loads the `myLogger` middleware function before the route to the root path (/). ```cjs title="index.cjs" const express = require('express'); const app = express(); const myLogger = function (req, res, next) { console.log('LOGGED'); next(); }; app.use(myLogger); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); const myLogger = function (req, res, next) { console.log('LOGGED'); next(); }; app.use(myLogger); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000); ``` ```ts title="index.ts" const app: Express = express(); const myLogger = function (req: Request, res: Response, next: NextFunction) { console.log('LOGGED'); next(); }; app.use(myLogger); app.get('/', (req: Request, res: Response) => { res.send('Hello World!'); }); app.listen(3000); ``` Every time the app receives a request, it prints the message "LOGGED" to the terminal. The order of middleware loading is important: middleware functions that are loaded first are also executed first. If `myLogger` is loaded after the route to the root path, the request never reaches it and the app doesn't print "LOGGED", because the route handler of the root path terminates the request-response cycle. The middleware function `myLogger` simply prints a message, then passes on the request to the next middleware function in the stack by calling the `next()` function. ### Middleware function requestTime Next, we'll create a middleware function called "requestTime" and add a property called `requestTime` to the [request object](/api/request). Because the middleware adds a property to `req`, extend the request type in TypeScript with [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html). Declare the property (as optional, since a middleware may not run for every request) in a `.d.ts` file that is part of your project: ```ts title="types/express.d.ts" declare global { namespace Express { interface Request { requestTime?: number; } } } export {}; ``` TypeScript picks up the file automatically, so no `tsconfig.json` change is needed unless you have set a custom `include` that does not cover its location. See [Extending the API in TypeScript](/guide/overriding-express-api#extending-the-api-in-typescript) for adding other custom properties and methods. ```js const requestTime = function (req, res, next) { req.requestTime = Date.now(); next(); }; ``` ```ts const requestTime = function (req: Request, res: Response, next: NextFunction) { req.requestTime = Date.now(); next(); }; ``` The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object). ```cjs title="index.cjs" const express = require('express'); const app = express(); const requestTime = function (req, res, next) { req.requestTime = Date.now(); next(); }; app.use(requestTime); app.get('/', (req, res) => { let responseText = 'Hello World!
'; responseText += `Requested at: ${req.requestTime}`; res.send(responseText); }); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); const requestTime = function (req, res, next) { req.requestTime = Date.now(); next(); }; app.use(requestTime); app.get('/', (req, res) => { let responseText = 'Hello World!
'; responseText += `Requested at: ${req.requestTime}`; res.send(responseText); }); app.listen(3000); ``` ```ts title="index.ts" const app: Express = express(); const requestTime = function (req: Request, res: Response, next: NextFunction) { req.requestTime = Date.now(); next(); }; app.use(requestTime); app.get('/', (req: Request, res: Response) => { let responseText = 'Hello World!
'; responseText += `Requested at: ${req.requestTime}`; res.send(responseText); }); app.listen(3000); ``` When you make a request to the root of the app, the app now displays the timestamp of your request in the browser. ### Middleware function validateCookies Finally, we'll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. Here's an example function that validates cookies with an external async service. ```js async function cookieValidator(cookies) { try { await externallyValidateCookie(cookies.testCookie); } catch { throw new Error('Invalid cookies'); } } ``` ```ts async function cookieValidator(cookies: Record) { try { await externallyValidateCookie(cookies.testCookie); } catch { throw new Error('Invalid cookies'); } } ``` Here, we use the [`cookie-parser`](/resources/middleware/cookie-parser) middleware to parse incoming cookies off the `req` object and pass them to our `cookieValidator` function. The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler. ```cjs title="index.cjs" const express = require('express'); const cookieParser = require('cookie-parser'); const cookieValidator = require('./cookieValidator'); const app = express(); async function validateCookies(req, res, next) { await cookieValidator(req.cookies); next(); } app.use(cookieParser()); app.use(validateCookies); // error handler app.use((err, req, res, next) => { res.status(400).send(err.message); }); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); async function validateCookies(req, res, next) { await cookieValidator(req.cookies); next(); } app.use(cookieParser()); app.use(validateCookies); // error handler app.use((err, req, res, next) => { res.status(400).send(err.message); }); app.listen(3000); ``` ```ts title="index.ts" const app: Express = express(); async function validateCookies(req: Request, res: Response, next: NextFunction) { await cookieValidator(req.cookies); next(); } app.use(cookieParser()); app.use(validateCookies); // error handler app.use((err: Error, req: Request, res: Response, next: NextFunction) => { res.status(400).send(err.message); }); app.listen(3000); ``` Note how `next()` is called after `await cookieValidator(req.cookies)`. This ensures that if `cookieValidator` resolves, the next middleware in the stack will get called. If you pass anything to the `next()` function (except the string `'route'` or `'router'`), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions. Because you have access to the [request object](/api/request), the [response object](/api/response), the next middleware function in the stack, and the whole [Node.js API](https://nodejs.org/api/), the possibilities with middleware functions are endless. For more information about Express middleware, see the [Using Express middleware](/guide/using-middleware) guide. ## Configurable middleware If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters. ```cjs title="my-middleware.cjs" module.exports = function (options) { return function (req, res, next) { // Implement the middleware function based on the options object next(); }; }; ``` ```mjs title="my-middleware.mjs" export default function (options) { return function (req, res, next) { // Implement the middleware function based on the options object next(); }; } ``` ```ts title="my-middleware.ts" export default function (options: Record) { return function (req: Request, res: Response, next: NextFunction) { // Implement the middleware function based on the options object next(); }; } ``` The middleware can now be used as shown below. ```cjs title="index.cjs" const mw = require('./my-middleware.cjs'); app.use(mw({ option1: '1', option2: '2' })); ``` ```mjs title="index.mjs" app.use(mw({ option1: '1', option2: '2' })); ``` Refer to [cookie-session](https://github.com/expressjs/cookie-session) and [compression](https://github.com/expressjs/compression) for examples of configurable middleware. --- ## Basic routing URL: https://expressjs.com/en/5x/starter/basic-routing _Routing_ refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). Each route can have one or more handler functions, which are executed when the route is matched. Route definition takes the following structure: ```js app.METHOD(PATH, HANDLER); ``` Where: - `app` is an instance of `express`. - `METHOD` is an [HTTP request method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods), in lowercase. - `PATH` is a path on the server. - `HANDLER` is the function executed when the route is matched. This tutorial assumes that an instance of `express` named `app` is created and the server is running. If you are not familiar with creating an app and starting it, see the [Hello world example](/starter/hello-world). The following examples illustrate defining simple routes. Respond with `Hello World!` on the homepage: ```js app.get('/', (req, res) => { res.send('Hello World!'); }); ``` ```ts app.get('/', (req: Request, res: Response) => { res.send('Hello World!'); }); ``` Respond to a POST request on the root route (`/`), the application's home page: ```js app.post('/', (req, res) => { res.send('Got a POST request'); }); ``` ```ts app.post('/', (req: Request, res: Response) => { res.send('Got a POST request'); }); ``` Respond to a PUT request to the `/user` route: ```js app.put('/user', (req, res) => { res.send('Got a PUT request at /user'); }); ``` ```ts app.put('/user', (req: Request, res: Response) => { res.send('Got a PUT request at /user'); }); ``` Respond to a DELETE request to the `/user` route: ```js app.delete('/user', (req, res) => { res.send('Got a DELETE request at /user'); }); ``` ```ts app.delete('/user', (req: Request, res: Response) => { res.send('Got a DELETE request at /user'); }); ``` For more details about routing, see the [Routing](/guide/routing) guide. --- ## Express examples URL: https://expressjs.com/en/5x/starter/examples This page contains list of examples using Express. - [auth](https://github.com/expressjs/express/tree/master/examples/auth) - Authentication with login and password - [content-negotiation](https://github.com/expressjs/express/tree/master/examples/content-negotiation) - HTTP content negotiation - [cookie-sessions](https://github.com/expressjs/express/tree/master/examples/cookie-sessions) - Working with cookie-based sessions - [cookies](https://github.com/expressjs/express/tree/master/examples/cookies) - Working with cookies - [downloads](https://github.com/expressjs/express/tree/master/examples/downloads) - Transferring files to client - [ejs](https://github.com/expressjs/express/tree/master/examples/ejs) - Working with Embedded JavaScript templating (ejs) - [error-pages](https://github.com/expressjs/express/tree/master/examples/error-pages) - Creating error pages - [error](https://github.com/expressjs/express/tree/master/examples/error) - Working with error middleware - [hello-world](https://github.com/expressjs/express/tree/master/examples/hello-world) - Simple request handler - [markdown](https://github.com/expressjs/express/tree/master/examples/markdown) - Markdown as template engine - [multi-router](https://github.com/expressjs/express/tree/master/examples/multi-router) - Working with multiple Express routers - [mvc](https://github.com/expressjs/express/tree/master/examples/mvc) - MVC-style controllers - [online](https://github.com/expressjs/express/tree/master/examples/online) - Tracking online user activity with `online` and `redis` packages - [params](https://github.com/expressjs/express/tree/master/examples/params) - Working with route parameters - [resource](https://github.com/expressjs/express/tree/master/examples/resource) - Multiple HTTP operations on the same resource - [route-map](https://github.com/expressjs/express/tree/master/examples/route-map) - Organizing routes using a map - [route-middleware](https://github.com/expressjs/express/tree/master/examples/route-middleware) - Working with route middleware - [route-separation](https://github.com/expressjs/express/tree/master/examples/route-separation) - Organizing routes per each resource - [search](https://github.com/expressjs/express/tree/master/examples/search) - Search API - [session](https://github.com/expressjs/express/tree/master/examples/session) - User sessions - [static-files](https://github.com/expressjs/express/tree/master/examples/static-files) - Serving static files - [vhost](https://github.com/expressjs/express/tree/master/examples/vhost) - Working with virtual hosts - [view-constructor](https://github.com/expressjs/express/tree/master/examples/view-constructor) - Rendering views dynamically - [view-locals](https://github.com/expressjs/express/tree/master/examples/view-locals) - Saving data in request object between middleware calls - [web-service](https://github.com/expressjs/express/tree/master/examples/web-service) - Simple API service ## Additional examples These are some additional examples with more extensive integrations. This information refers to third-party sites, products, or modules that are not maintained by the Expressjs team. Listing here does not constitute an endorsement or recommendation from the Expressjs project team. - [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - REST API with Express in TypeScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM --- ## FAQ URL: https://expressjs.com/en/5x/starter/faq ## How should I structure my application? There is no definitive answer to this question. The answer depends on the scale of your application and the team that is involved. To be as flexible as possible, Express makes no assumptions in terms of structure. Routes and other application-specific logic can live in as many files as you wish, in any directory structure you prefer. View the following examples for inspiration: - [Route listings](https://github.com/expressjs/express/blob/v5.2.1/examples/route-separation/index.js#L34-L49) - [Route map](https://github.com/expressjs/express/blob/v5.2.1/examples/route-map/index.js#L55-L69) - [MVC style controllers](https://github.com/expressjs/express/tree/master/examples/mvc) Also, there are third-party extensions for Express, which simplify some of these patterns: - [Resourceful routing](https://github.com/expressjs/express-resource) ## How do I define models? Express has no notion of a database. This concept is left up to third-party Node modules, allowing you to interface with nearly any database. See [LoopBack](https://loopback.io/) for an Express-based framework that is centered around models. ## How can I authenticate users? Authentication is another opinionated area that Express does not venture into. You may use any authentication scheme you wish. For a simple username / password scheme, see [this example](https://github.com/expressjs/express/tree/master/examples/auth). ## Which template engines does Express support? Express supports any template engine that conforms with the `(path, locals, callback)` signature. To normalize template engine interfaces and caching, see the [consolidate.js](https://github.com/visionmedia/consolidate.js) project for support. Unlisted template engines might still support the Express signature. For more information, see the [Using template engines with Express](/guide/using-template-engines) guide. ## How do I handle 404 responses? In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response: ```js app.use((req, res, next) => { res.status(404).send("Sorry can't find that!"); }); ``` ```ts app.use((req: Request, res: Response, next: NextFunction) => { res.status(404).send("Sorry can't find that!"); }); ``` Add routes dynamically at runtime on an instance of `express.Router()` so the routes are not superseded by a middleware function. ## How do I setup an error handler? You define error-handling middleware in the same way as other middleware, except with four arguments instead of three; specifically with the signature `(err, req, res, next)`: ```js app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); ``` ```ts app.use((err: Error, req: Request, res: Response, next: NextFunction) => { console.error(err.stack); res.status(500).send('Something broke!'); }); ``` For more information, see the [Error handling](/guide/error-handling) guide. ## How do I render plain HTML? You don't! There's no need to "render" HTML with the `res.render()` function. If you have a specific file, use the `res.sendFile()` function. If you are serving many assets from a directory, use the `express.static()` middleware function. ## What version of Node.js does Express require? - [Express 4.x](/4x/api) requires Node.js 0.10 or higher. - [Express 5.x](/api) requires Node.js 18 or higher. --- ## Express application generator URL: https://expressjs.com/en/5x/starter/generator Use the application generator tool, `express-generator`, to quickly create an application skeleton. You can run the application generator with the `npx` command (available in Node.js 8.2.0). ```bash $ npx express-generator ``` For earlier Node versions, install the application generator as a global npm package and then launch it: ```bash $ npm install -g express-generator $ express ``` Display the command options with the `-h` option: ```bash $ express -h Usage: express [options] [dir] Options: -h, --help output usage information --version output the version number -e, --ejs add ejs engine support --hbs add handlebars engine support --pug add pug engine support -H, --hogan add hogan.js engine support --no-view generate without view engine -v, --view add view support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) -c, --css add stylesheet support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory ``` For example, the following creates an Express app named _myapp_. The app will be created in a folder named _myapp_ in the current working directory and the view engine will be set to Pug: ```bash $ express --view=pug myapp create : myapp create : myapp/package.json create : myapp/app.js create : myapp/public create : myapp/public/javascripts create : myapp/public/images create : myapp/routes create : myapp/routes/index.js create : myapp/routes/users.js create : myapp/public/stylesheets create : myapp/public/stylesheets/style.css create : myapp/views create : myapp/views/index.pug create : myapp/views/layout.pug create : myapp/views/error.pug create : myapp/bin create : myapp/bin/www ``` Then install dependencies: ```bash $ cd myapp $ npm install ``` On MacOS or Linux, run the app with this command: ```bash $ DEBUG=myapp:* npm start ``` On Windows Command Prompt, use this command: ```bash > set DEBUG=myapp:* & npm start ``` On Windows PowerShell, use this command: ```bash PS> $env:DEBUG='myapp:*'; npm start ``` Then, load `http://localhost:3000/` in your browser to access the app. The generated app has the following directory structure: ```bash . ├── app.js ├── bin │ └── www ├── package.json ├── public │ ├── images │ ├── javascripts │ └── stylesheets │ └── style.css ├── routes │ ├── index.js │ └── users.js └── views ├── error.pug ├── index.pug └── layout.pug 7 directories, 9 files ``` The app structure created by the generator is just one of many ways to structure Express apps. Feel free to use this structure or modify it to best suit your needs. --- ## Hello world example URL: https://expressjs.com/en/5x/starter/hello-world Embedded below is essentially the simplest Express app you can create. It is a single file app — _not_ what you'd get if you use the [Express generator](/starter/generator), which creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and sub-directories for various purposes. ```cjs title="index.cjs" const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Example app listening on port ${port}`); }); ``` ```mjs title="index.mjs" const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Example app listening on port ${port}`); }); ``` ```ts title="index.ts" const app: Express = express(); const port = 3000; app.get('/', (req: Request, res: Response) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Example app listening on port ${port}`); }); ``` This app starts a server and listens on port 3000 for connections. The app responds with "Hello World!" for requests to the root URL (`/`) or _route_. For every other path, it will respond with a **404 Not Found**. ## Running Locally First create a directory named `myapp`, change to it and run `npm init`. Then, install `express` as a dependency, as per the [installation guide](/starter/installing). In the `myapp` directory, create a file named `app.js` and copy the code from the example above. The `req` (request) and `res` (response) are the exact same objects that Node provides, so you can invoke `req.pipe()`, `req.on('data', callback)`, and anything else you would do without Express involved. Run the app with the following command: ```bash $ node app.js ``` Then, load `http://localhost:3000/` in a browser to see the output. --- ## Installing URL: https://expressjs.com/en/5x/starter/installing Before you begin, make sure you have [Node.js](https://nodejs.org/) 18 or higher installed. Then, create a directory for your application and navigate into it. ```bash mkdir myapp cd myapp ``` Use the `npm init` command to create a `package.json` file for your application. For more information on how `package.json` works, see [Specifics of npm's package.json handling](https://docs.npmjs.com/files/package.json). This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception: ``` entry point: (index.js) ``` Enter `app.js`, or whatever you want the name of the main file to be. If you want it to be `index.js`, hit RETURN to accept the suggested default file name. Now, install Express in the `myapp` directory and save it in the dependencies list. For example: To install Express temporarily and not add it to the dependencies list: ## TypeScript Express is written in JavaScript and does not bundle its own type definitions. To use it with TypeScript, install TypeScript together with the community-maintained types for Express and Node.js (from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped)) as development dependencies: Some middleware does not bundle its own type definitions. If you add an official middleware package that TypeScript reports as untyped, also install its types from DefinitelyTyped as a dev dependency, for example `@types/cors` alongside `cors`. Add a `tsconfig.json`. These options mirror how Node.js runs TypeScript and make the compiler reject non-erasable syntax (such as `enum`s, namespaces, and parameter properties) that Node cannot strip: ```json title="tsconfig.json" { "compilerOptions": { "target": "esnext", "module": "nodenext", "rewriteRelativeImportExtensions": true, "erasableSyntaxOnly": true, "verbatimModuleSyntax": true, "noEmit": true, "strict": true, "skipLibCheck": true } } ``` Write your application in TypeScript, annotating the [request](/api/request) and [response](/api/response) objects: ```ts title="src/app.ts" const app: Express = express(); app.get('/', (req: Request, res: Response) => { res.send('Hello World!'); }); app.listen(3000); ``` You do not need to annotate everything. When you pass a handler directly to a route method or to `app.use()`, Express infers the types of `req`, `res`, and `next`, and it infers route parameters from the path, so `req.params.id` is a `string` in `app.get('/users/:id', ...)`. Add explicit types only where TypeScript has no context to infer from: error-handling middleware, whose `(err, req, res, next)` signature is not inferred, and handlers you define separately from the route. In those cases, annotate the parameters or type the whole function as `RequestHandler` or `ErrorRequestHandler`. Run the file directly with Node.js, which strips the TypeScript types and runs the result without a build step: ```bash node src/app.ts ``` Running `.ts` files directly requires Node.js >= 22.18.0 (or >= 23.6.0 on the v23 line) and TypeScript >= 5.8. Node strips the types but does not type-check them, so run `npx tsc` to type-check your project. For more details, see the Node.js guide on [running TypeScript natively](https://nodejs.org/learn/typescript/run-natively). --- ## Serving static files in Express URL: https://expressjs.com/en/5x/starter/static-files To serve static files such as images, CSS files, and JavaScript files, use the `express.static` built-in middleware function in Express. The function signature is: ```js express.static(root, [options]); ``` The `root` argument specifies the root directory from which to serve static assets. For more information on the `options` argument, see [express.static](/api/express/#expressstatic). For example, use the following code to serve images, CSS files, and JavaScript files in a directory named `public`: ```js app.use(express.static('public')); ``` Now, you can load the files that are in the `public` directory: ```text http://localhost:3000/images/kitten.jpg http://localhost:3000/css/style.css http://localhost:3000/js/app.js http://localhost:3000/images/bg.png http://localhost:3000/hello.html ``` Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL. To use multiple static assets directories, call the `express.static` middleware function multiple times: ```js app.use(express.static('public')); app.use(express.static('files')); ``` Express looks up the files in the order in which you set the static directories with the `express.static` middleware function. For best results, [use a reverse proxy](/advanced/best-practice-performance/#use-a-reverse-proxy) cache to improve performance of serving static assets. To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the `express.static` function, [specify a mount path](/api/application/#appuse) for the static directory, as shown below: ```js app.use('/static', express.static('public')); ``` Now, you can load the files that are in the `public` directory from the `/static` path prefix. ```text http://localhost:3000/static/images/kitten.jpg http://localhost:3000/static/css/style.css http://localhost:3000/static/js/app.js http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html ``` However, the path that you provide to the `express.static` function is relative to the directory from where you launch your `node` process. If you run the express app from another directory, it's safer to use the absolute path of the directory that you want to serve: ```cjs title="index.cjs" const path = require('path'); app.use('/static', express.static(path.join(__dirname, 'public'))); ``` ```mjs title="index.mjs" app.use('/static', express.static(path.join(__dirname, 'public'))); ``` For more details about the `serve-static` function and its options, see [serve-static](/resources/middleware/serve-static). --- ## 5.x API Reference URL: https://expressjs.com/en/5x/api This section provides an overview of the modules and APIs available in Express 5.x for building web applications and HTTP services. ```cjs title="index.cjs" const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('hello world'); }); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); app.get('/', (req, res) => { res.send('hello world'); }); app.listen(3000); ``` ```ts title="index.ts" const app: Express = express(); app.get('/', (req: Request, res: Response) => { res.send('hello world'); }); app.listen(3000); ``` Express 5.x requires **Node.js 18 or higher**. With express v5.x, you can define routes, configure middleware, and start handling HTTP requests using the application instance created by the `express()` function. The API is organized into the following sections: --- ## Application Object URL: https://expressjs.com/en/5x/api/application The `app` object conventionally denotes the Express application. Create it by calling the top-level `express()` function exported by the Express module: ```cjs title="index.cjs" var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('hello world'); }); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); app.get('/', function (req, res) { res.send('hello world'); }); app.listen(3000); ``` ```ts title="index.ts" const app: Express = express(); app.get('/', function (req: Request, res: Response) { res.send('hello world'); }); app.listen(3000); ``` The `app` object has methods for - Routing HTTP requests; see for example, [app.METHOD](#appmethod) and [app.param](#appparam). - Configuring middleware; see [app.route](#approute). - Rendering HTML views; see [app.render](#apprender). - Registering a template engine; see [app.engine](#appengine). It also has settings (properties) that affect how the application behaves; for more information, see [Application settings](#application-settings). The Express application object can be referred from the [request object](/api/request/) and the [response object](/api/response/) as `req.app`, and `res.app`, respectively. ## Properties ### app.locals Type: Object. The `app.locals` object has properties that are local variables within the application, and will be available in templates rendered with [res.render](/api/response/#resrender). The `locals` object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations. ```js console.dir(app.locals.title); // => 'My App' console.dir(app.locals.email); // => 'me@myapp.com' ``` Once set, the value of `app.locals` properties persist throughout the life of the application, in contrast with [res.locals](/api/response/#reslocals) properties that are valid only for the lifetime of the request. You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via `req.app.locals` (see [req.app](/api/request/#reqapp)) ```js app.locals.title = 'My App'; app.locals.strftime = require('strftime'); app.locals.email = 'me@myapp.com'; ``` ### app.mountpath Type: String | String[]. The `app.mountpath` property contains one or more path patterns on which a sub-app was mounted. A sub-app is an instance of `express` that may be used for handling the request to a route. ```cjs title="index.cjs" const express = require('express'); const app = express(); // the main app const admin = express(); // the sub app admin.get('/', (req, res) => { console.log(admin.mountpath); // /admin res.send('Admin Homepage'); }); app.use('/admin', admin); // mount the sub app ``` ```mjs title="index.mjs" const app = express(); // the main app const admin = express(); // the sub app admin.get('/', (req, res) => { console.log(admin.mountpath); // /admin res.send('Admin Homepage'); }); app.use('/admin', admin); // mount the sub app ``` ```ts title="index.ts" const app: Express = express(); // the main app const admin: Express = express(); // the sub app admin.get('/', (req: Request, res: Response) => { console.log(admin.mountpath); // /admin res.send('Admin Homepage'); }); app.use('/admin', admin); // mount the sub app ``` It is similar to the [baseUrl](/api/request/#reqbaseurl) property of the `req` object, except `req.baseUrl` returns the matched URL path, instead of the matched patterns. If a sub-app is mounted on multiple path patterns, `app.mountpath` returns the list of patterns it is mounted on, as shown in the following example. ```js const admin = express(); admin.get('/', (req, res) => { console.log(admin.mountpath); // [ '/adm{*splat}n', '/manager' ] res.send('Admin Homepage'); }); const secret = express(); secret.get('/', (req, res) => { console.log(secret.mountpath); // /secr{*splat}t res.send('Admin Secret'); }); admin.use('/secr{*splat}t', secret); // load the 'secret' router on '/secr{*splat}t', on the 'admin' sub app app.use(['/adm{*splat}n', '/manager'], admin); // load the 'admin' router on '/adm{*splat}n' and '/manager', on the parent app ``` ```ts const admin: Express = express(); admin.get('/', (req: Request, res: Response) => { console.log(admin.mountpath); // [ '/adm{*splat}n', '/manager' ] res.send('Admin Homepage'); }); const secret: Express = express(); secret.get('/', (req: Request, res: Response) => { console.log(secret.mountpath); // /secr{*splat}t res.send('Admin Secret'); }); admin.use('/secr{*splat}t', secret); // load the 'secret' router on '/secr{*splat}t', on the 'admin' sub app app.use(['/adm{*splat}n', '/manager'], admin); // load the 'admin' router on '/adm{*splat}n' and '/manager', on the parent app ``` ### app.router Type: Router. The application's in-built instance of router. This is created lazily, on first access. ```cjs title="index.cjs" const express = require('express'); const app = express(); const router = app.router; router.get('/', (req, res) => { res.send('hello world'); }); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); const router = app.router; router.get('/', (req, res) => { res.send('hello world'); }); app.listen(3000); ``` ```ts title="index.ts" const app: Express = express(); const router = app.router; router.get('/', (req: Request, res: Response) => { res.send('hello world'); }); app.listen(3000); ``` You can add middleware and HTTP method routes to the `router` just like an application. For more information, see [Router](/api/router/). ## Events ### app.on('mount') Arguments: - callback (Function): The listener called when the `mount` event fires. It receives the parent app as its only argument: `callback(parent)`. The `mount` event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function. Sub-apps will: - Not inherit the value of settings that have a default value. You must set the value in the sub-app. - Inherit the value of settings with no default value. - Inherit `case sensitive routing` and `strict routing` unless those settings are explicitly set on the sub-app. These values configure the sub-app's router when it is created; mounting does not reconfigure an existing router. If a parent uses path-specific middleware to protect a sub-app, apply that middleware to the full mount path of the sub-app rather than to a narrower path inside it. For details, see [Application settings](#application-settings). ```js const admin = express(); admin.on('mount', (parent) => { console.log('Admin Mounted'); console.log(parent); // refers to the parent app }); admin.get('/', (req, res) => { res.send('Admin Homepage'); }); app.use('/admin', admin); ``` ```ts const admin: Express = express(); admin.on('mount', (parent: Application) => { console.log('Admin Mounted'); console.log(parent); // refers to the parent app }); admin.get('/', (req: Request, res: Response) => { res.send('Admin Homepage'); }); app.use('/admin', admin); ``` ## Methods ### app.all() Arguments: - path (String | RegExp | Array): The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See [Path examples](#path-examples) for syntax. - callback (Function | Function[]): Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since [router](/api/router/) and [app](/api/application/) implement the middleware interface, you can use them as you would any other middleware function. For examples, see [Middleware callback function examples](#middleware-callback-function-examples). This method is like the standard [app.METHOD()](#appmethod) methods, except it matches all HTTP verbs. #### Examples The following callback is executed for requests to `/secret` whether using GET, POST, PUT, DELETE, or any other HTTP request method: ```js app.all('/secret', (req, res, next) => { console.log('Accessing the secret section ...'); next(); // pass control to the next handler }); ``` ```ts app.all('/secret', (req: Request, res: Response, next: NextFunction) => { console.log('Accessing the secret section ...'); next(); // pass control to the next handler }); ``` The `app.all()` method is useful for mapping "global" logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, it requires that all routes from that point on require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end-points: `loadUser` can perform a task, then call `next()` to continue matching subsequent routes. ```js app.all('{*splat}', requireAuthentication, loadUser); ``` Or the equivalent: ```js app.all('{*splat}', requireAuthentication); app.all('{*splat}', loadUser); ``` Another example is white-listed "global" functionality. The example is similar to the ones above, but it only restricts paths that start with "/api": ```js app.all('/api/{*splat}', requireAuthentication); ``` ### app.delete() Arguments: - path (String | RegExp | Array): The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See [Path examples](#path-examples) for syntax. - callback (Function | Function[]): Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since [router](/api/router/) and [app](/api/application/) implement the middleware interface, you can use them as you would any other middleware function. For examples, see [Middleware callback function examples](#middleware-callback-function-examples). Routes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the [routing guide](/guide/routing/). #### Example ```js app.delete('/', (req, res) => { res.send('DELETE request to homepage'); }); ``` ```ts app.delete('/', (req: Request, res: Response) => { res.send('DELETE request to homepage'); }); ``` ### app.disable() Returns: Application. Arguments: - name (String): The name of the Boolean setting to disable; one of the properties from the [app settings table](#application-settings). Sets the Boolean setting `name` to `false`, where `name` is one of the properties from the [app settings table](#application-settings). Calling `app.set('foo', false)` for a Boolean property is the same as calling `app.disable('foo')`. For example: ```js app.disable('trust proxy'); app.get('trust proxy'); // => false ``` ### app.disabled() Returns: Boolean. Arguments: - name (String): The name of the Boolean setting to test; one of the properties from the [app settings table](#application-settings). Returns `true` if the Boolean setting `name` is disabled (`false`), where `name` is one of the properties from the [app settings table](#application-settings). ```js app.disabled('trust proxy'); // => true app.enable('trust proxy'); app.disabled('trust proxy'); // => false ``` ### app.enable() Returns: Application. Arguments: - name (String): The name of the Boolean setting to enable; one of the properties from the [app settings table](#application-settings). Sets the Boolean setting `name` to `true`, where `name` is one of the properties from the [app settings table](#application-settings). Calling `app.set('foo', true)` for a Boolean property is the same as calling `app.enable('foo')`. ```js app.enable('trust proxy'); app.get('trust proxy'); // => true ``` ### app.enabled() Returns: Boolean. Arguments: - name (String): The name of the setting to test; one of the properties from the [app settings table](#application-settings). Returns `true` if the setting `name` is enabled (`true`), where `name` is one of the properties from the [app settings table](#application-settings). ```js app.enabled('trust proxy'); // => false app.enable('trust proxy'); app.enabled('trust proxy'); // => true ``` ### app.engine() Returns: Application. Arguments: - ext (String): The file extension the template engine is registered for (for example, `pug` or `html`). - callback (Function): The template engine function used to render files with the given extension. Registers the given template engine `callback` as `ext`. By default, Express will `require()` the engine based on the file extension. For example, if you try to render a "foo.pug" file, Express invokes the following internally, and caches the `require()` on subsequent calls to increase performance. ```js app.engine('pug', require('pug').__express); ``` Use this method for engines that do not provide `.__express` out of the box, or if you wish to "map" a different extension to the template engine. For example, to map the EJS template engine to ".html" files: ```js app.engine('html', require('ejs').renderFile); ``` In this case, EJS provides a `.renderFile()` method with the same signature that Express expects: `(path, options, callback)`, though note that it aliases this method as `ejs.__express` internally so if you're using ".ejs" extensions you don't need to do anything. Some template engines do not follow this convention. The [consolidate.js](https://github.com/tj/consolidate.js) library maps Node template engines to follow this convention, so they work seamlessly with Express. ```cjs title="index.cjs" const engines = require('consolidate'); app.engine('haml', engines.haml); app.engine('html', engines.hogan); ``` ```mjs title="index.mjs" app.engine('haml', engines.haml); app.engine('html', engines.hogan); ``` ### app.get(name) Returns: any. Arguments: - name (String): The name of the setting to read; one of the strings in the [app settings table](#application-settings). Returns the value of `name` app setting, where `name` is one of the strings in the [app settings table](#application-settings). For example: ```js app.get('title'); // => undefined app.set('title', 'My Site'); app.get('title'); // => 'My Site' ``` ### app.get() Arguments: - path (String | RegExp | Array): The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See [Path examples](#path-examples) for syntax. - callback (Function | Function[]): Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since [router](/api/router/) and [app](/api/application/) implement the middleware interface, you can use them as you would any other middleware function. For examples, see [Middleware callback function examples](#middleware-callback-function-examples). Routes HTTP GET requests to the specified path with the specified callback functions. For more information, see the [routing guide](/guide/routing/). #### Example ```js app.get('/', (req, res) => { res.send('GET request to homepage'); }); ``` ```ts app.get('/', (req: Request, res: Response) => { res.send('GET request to homepage'); }); ``` ### app.listen() Returns: http.Server. Arguments: - port (Number, optional): The TCP port to listen on. If omitted or `0`, the OS assigns an arbitrary unused port. - host (String, optional): The host on which to accept connections. - backlog (Number, optional): The maximum length of the queue of pending connections. - path (String, optional): The path of a UNIX socket to listen on, as an alternative to host and port. - callback (Function, optional): A function called once the server is listening. If the server emits an `error` event (for example `EADDRINUSE`), the error is passed to this callback as its argument. Binds and listens for connections on the specified host and port, or starts a UNIX socket and listens for connections on the given path. This method is identical to Node's [http.Server.listen()](https://nodejs.org/api/http.html#serverlisten). If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.). ```cjs title="index.cjs" const express = require('express'); const app = express(); app.listen(3000); // bind and listen on a TCP port app.listen('/tmp/sock'); // or listen on a UNIX socket ``` ```mjs title="index.mjs" const app = express(); app.listen(3000); // bind and listen on a TCP port app.listen('/tmp/sock'); // or listen on a UNIX socket ``` ```ts title="index.ts" const app: Express = express(); app.listen(3000); // bind and listen on a TCP port app.listen('/tmp/sock'); // or listen on a UNIX socket ``` When the server emits an `error` event (such as `EADDRINUSE`), the error is passed to the provided `callback`. Handle it inside the callback: ```js const server = app.listen(8080, '0.0.0.0', (error) => { if (error) { throw error; // e.g. EADDRINUSE } console.log(`Listening on ${JSON.stringify(server.address())}`); }); ``` The `app` returned by `express()` is in fact a JavaScript `Function`, designed to be passed to Node's HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback): ```cjs title="index.cjs" const express = require('express'); const https = require('https'); const http = require('http'); const app = express(); http.createServer(app).listen(80); https.createServer(options, app).listen(443); ``` ```mjs title="index.mjs" const app = express(); http.createServer(app).listen(80); https.createServer(options, app).listen(443); ``` ```ts title="index.ts" const app: Express = express(); http.createServer(app).listen(80); https.createServer(options, app).listen(443); ``` The `app.listen()` method returns an [http.Server](https://nodejs.org/api/http.html#class-httpserver) object and (for HTTP) is a convenience method for the following: ```js app.listen = function () { const server = http.createServer(this); return server.listen.apply(server, arguments); }; ``` All the forms of Node's [http.Server.listen()](https://nodejs.org/api/http.html#serverlisten) method are in fact actually supported. ### app.METHOD() Arguments: - path (String | RegExp | Array): The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See [Path examples](#path-examples) for syntax. - callback (Function | Function[]): Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since [router](/api/router/) and [app](/api/application/) implement the middleware interface, you can use them as you would any other middleware function. For examples, see [Middleware callback function examples](#middleware-callback-function-examples). Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are `app.get()`, `app.post()`, `app.put()`, and so on. See [Routing methods](#routing-methods) below for the complete list. String route patterns match the whole request path. For example, `app.get('/apple', ...)` matches `/apple`, but not `/apple/images`. With the same path, [app.use()](#appuse) matches both. Regular expressions can match part of the path. `app.get(/apple/, ...)` matches `/apple/images`. Use `^` and `$` for a full match: `app.get(/^\/apple$/, ...)` matches only `/apple`. #### Routing methods Express supports the following routing methods corresponding to the HTTP methods of the same names:
- `checkout` - `copy` - [`delete`](#appdelete) - [`get`](#appget) - `head` - `lock` - `merge` - `mkactivity` - `mkcol` - `move` - `m-search` - `notify` - `options` - `patch` - [`post`](#apppost) - `purge` - [`put`](#appput) - [`query`](#appquery) - `report` - `search` - `subscribe` - `trace` - `unlock` - `unsubscribe`
The API documentation has explicit entries only for the most popular HTTP methods `app.get()`, `app.post()`, `app.put()`, `app.delete()`, and `app.query()`. However, the other methods listed above work in exactly the same way. To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, `app['m-search']('/', function ...`. ```js ins={10} app.get('/', (req, res) => { res.send('GET request to homepage'); }); app.post('/', (req, res) => { res.send('POST request to homepage'); }); // methods that are invalid JavaScript variable names use bracket notation app['m-search']('/', (req, res) => { res.send('M-SEARCH request to homepage'); }); ``` ```ts app.get('/', (req: Request, res: Response) => { res.send('GET request to homepage'); }); app.post('/', (req: Request, res: Response) => { res.send('POST request to homepage'); }); // methods that are invalid JavaScript variable names use bracket notation app['m-search']('/', (req: Request, res: Response) => { res.send('M-SEARCH request to homepage'); }); ``` The `app.get()` function is automatically called for the HTTP `HEAD` method in addition to the `GET` method if `app.head()` was not called for the path before `app.get()`. The method, `app.all()`, is not derived from any HTTP method and loads middleware at the specified path for _all_ HTTP request methods. For more information, see [app.all](#appall). For more information on routing, see the [routing guide](/guide/routing/). ### app.param() Arguments: - name (String | String[]): The name of the route parameter, or an array of names. - callback (Function): The trigger called as `callback(req, res, next, value, name)`: the request object, the response object, the next middleware, the value of the parameter, and the name of the parameter, in that order. Add callback triggers to [route parameters](/guide/routing/#route-parameters), where `name` is the name of the parameter or an array of them, and `callback` is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order. If `name` is an array, the `callback` trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to `next` inside the callback will call the callback for the next declared parameter. For the last parameter, a call to `next` will call the next middleware in place for the route currently being processed, just like it would if `name` were just a string. 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 app.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')); } }); }); ``` 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 `app` will be triggered only by route parameters defined on `app` routes. All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples. ```js app.param('id', (req, res, next, id) => { console.log('CALLED ONLY ONCE'); next(); }); app.get('/user/:id', (req, res, next) => { console.log('although this matches'); next(); }); app.get('/user/:id', (req, res) => { console.log('and this matches too'); res.end(); }); ``` ```ts app.param('id', (req: Request, res: Response, next: NextFunction, id: string) => { console.log('CALLED ONLY ONCE'); next(); }); app.get('/user/:id', (req: Request, res: Response, next: NextFunction) => { console.log('although this matches'); next(); }); app.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 ``` ```js app.param(['id', 'page'], (req, res, next, value) => { console.log('CALLED ONLY ONCE with', value); next(); }); app.get('/user/:id/:page', (req, res, next) => { console.log('although this matches'); next(); }); app.get('/user/:id/:page', (req, res) => { console.log('and this matches too'); res.end(); }); ``` ```ts app.param(['id', 'page'], (req: Request, res: Response, next: NextFunction, value: string) => { console.log('CALLED ONLY ONCE with', value); next(); }); app.get('/user/:id/:page', (req: Request, res: Response, next: NextFunction) => { console.log('although this matches'); next(); }); app.get('/user/:id/:page', (req: Request, res: Response) => { console.log('and this matches too'); res.end(); }); ``` On `GET /user/42/3`, the following is printed: ``` CALLED ONLY ONCE with 42 CALLED ONLY ONCE with 3 although this matches and this matches too ``` ### app.path() Returns: String. Returns the canonical path of the app, a string. ```js title="index.js" const app = express(); const blog = express(); const blogAdmin = express(); app.use('/blog', blog); blog.use('/admin', blogAdmin); console.log(app.path()); // '' console.log(blog.path()); // '/blog' console.log(blogAdmin.path()); // '/blog/admin' ``` ```ts title="index.ts" const app: Express = express(); const blog: Express = express(); const blogAdmin: Express = express(); app.use('/blog', blog); blog.use('/admin', blogAdmin); console.log(app.path()); // '' console.log(blog.path()); // '/blog' console.log(blogAdmin.path()); // '/blog/admin' ``` The behavior of this method can become very complicated in complex cases of mounted apps: it is usually better to use [req.baseUrl](/api/request/#reqbaseurl) to get the canonical path of the app. ### app.post() Arguments: - path (String | RegExp | Array): The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See [Path examples](#path-examples) for syntax. - callback (Function | Function[]): Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since [router](/api/router/) and [app](/api/application/) implement the middleware interface, you can use them as you would any other middleware function. For examples, see [Middleware callback function examples](#middleware-callback-function-examples). Routes HTTP POST requests to the specified path with the specified callback functions. For more information, see the [routing guide](/guide/routing/). #### Example ```js app.post('/', (req, res) => { res.send('POST request to homepage'); }); ``` ```ts app.post('/', (req: Request, res: Response) => { res.send('POST request to homepage'); }); ``` ### app.put() Arguments: - path (String | RegExp | Array): The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See [Path examples](#path-examples) for syntax. - callback (Function | Function[]): Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since [router](/api/router/) and [app](/api/application/) implement the middleware interface, you can use them as you would any other middleware function. For examples, see [Middleware callback function examples](#middleware-callback-function-examples). Routes HTTP PUT requests to the specified path with the specified callback functions. #### Example ```js app.put('/', (req, res) => { res.send('PUT request to homepage'); }); ``` ```ts app.put('/', (req: Request, res: Response) => { res.send('PUT request to homepage'); }); ``` ### app.query() Requires runtime: Node.js >=20.19.3 <21 || >=22.2.0. Arguments: - path (String | RegExp | Array): The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See [Path examples](#path-examples) for syntax. - callback (Function | Function[]): Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since [router](/api/router/) and [app](/api/application/) implement the middleware interface, you can use them as you would any other middleware function. For examples, see [Middleware callback function examples](#middleware-callback-function-examples). Routes HTTP QUERY requests to the specified path with the specified callback functions. For more information, see the [routing guide](/guide/routing/). The HTTP QUERY method was standardized on June 15, 2026 as [RFC 10008](https://www.rfc-editor.org/rfc/rfc10008.html). Client and intermediary support is still limited. Verify that your target environments support the QUERY verb before relying on it in production. The HTTP QUERY method ([RFC 10008](https://www.rfc-editor.org/rfc/rfc10008.html)) is designed for queries whose input is too large or too sensitive to encode in the URL. Unlike `GET`, a QUERY request carries a body containing the query input. Unlike `POST`, it is explicitly **safe and idempotent**, intermediaries and caches can retry it automatically, and the response is cacheable (with the request body included in the cache key). Use `app.query()` when query parameters would exceed URL length limits, contain sensitive data that should not appear in server logs or browser history, or are too complex to express cleanly as a URL query string, such as deeply nested filters or structured criteria. Because the query input travels in the request body, `req.body` is `undefined` until you mount a body-parsing middleware such as [`express.json()`](/api/express/#expressjson) or [`express.urlencoded()`](/api/express/#expressurlencoded) that matches the request's `Content-Type`. #### Example ```js title="index.js" app.use(express.json()); // populate req.body for application/json payloads app.query('/search', (req, res) => { // complex filter criteria arrive in req.body, not the URL const results = db.search(req.body); res.json(results); }); ``` ```ts title="index.ts" app.use(express.json()); // populate req.body for application/json payloads app.query('/search', (req: Request, res: Response) => { // complex filter criteria arrive in req.body, not the URL const results = db.search(req.body); res.json(results); }); ``` ### app.render() Arguments: - view (String): The name of the view to render. - locals (Object, optional): An object whose properties define local variables for the view. - callback (Function): The callback invoked as `callback(err, html)` with the rendered HTML. Returns the rendered HTML of a view via the `callback` function. It accepts an optional parameter that is an object containing local variables for the view. It is like [res.render()](/api/response/#resrender), except it cannot send the rendered view to the client on its own. Think of `app.render()` as a utility function for generating rendered view strings. Internally `res.render()` uses `app.render()` to render views. The `view` argument performs file system operations like reading a file from disk and evaluating Node.js modules, and as so for security reasons should not contain input from the end-user. The `locals` object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations. The local variable `cache` is reserved for enabling view cache. Set it to `true`, if you want to cache view during development; view caching is enabled in production by default. ```js app.render('email', (err, html) => { // ... }); app.render('email', { name: 'Tobi' }, (err, html) => { // ... }); ``` ### app.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 `app.route()` to avoid duplicate route names (and thus typo errors). ```js const app = express(); app .route('/events') .all((req, res, next) => { // runs for all HTTP verbs first // think of it as route specific middleware! }) .get((req, res, next) => { res.json({}); }) .post((req, res, next) => { // maybe add a new event... }); ``` ```ts const app: Express = express(); app .route('/events') .all((req: Request, res: Response, next: NextFunction) => { // runs for all HTTP verbs first // think of it as route specific middleware! }) .get((req: Request, res: Response, next: NextFunction) => { res.json({}); }) .post((req: Request, res: Response, next: NextFunction) => { // maybe add a new event... }); ``` ### app.set() Returns: Application. Arguments: - name (String): The name of the setting to assign. Certain names configure the server's behavior; see the [app settings table](#application-settings). - value (any): The value to assign to the setting. Assigns setting `name` to `value`. You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the [app settings table](#application-settings). Calling `app.set('foo', true)` for a Boolean property is the same as calling `app.enable('foo')`. Similarly, calling `app.set('foo', false)` for a Boolean property is the same as calling `app.disable('foo')`. Retrieve the value of a setting with [`app.get()`](#appgetname). ```js app.set('title', 'My Site'); app.get('title'); // "My Site" ``` #### Application Settings The following table lists application settings. Sub-apps will: - Not inherit the value of settings that have a default value. You must set the value in the sub-app. - Inherit the value of settings with no default value; these are explicitly noted in the table below. - Inherit `case sensitive routing` and `strict routing` unless those settings are explicitly set on the sub-app. These values configure the sub-app's router when it is created; mounting does not reconfigure an existing router. If a parent uses path-specific middleware to protect a sub-app, apply that middleware to the full mount path of the sub-app rather than to a narrower path inside it. Exceptions: Sub-apps will inherit the value of `trust proxy` even though it has a default value (for backward-compatibility); Sub-apps will not inherit the value of `view cache` in production (when `NODE_ENV` is "production"). Settings: - case sensitive routing (Boolean, default: N/A (undefined)): Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same. This setting is read when the app first creates its router. Adding a route or middleware, calling `app.param()`, accessing `app.router`, or handling a request can create the router. Set it before any of these operations. Changing it afterwards has no effect on routing, including routes added later. Sub-apps inherit this setting unless they explicitly set their own value. If the sub-app's router already exists when the setting is inherited, `subApp.get('case sensitive routing')` reports the inherited value, but the router keeps its original configuration. To avoid relying on mount order, set `case sensitive routing` on the sub-app before its router is created. - env (String, default: process.env.NODE_ENV (NODE_ENV environment variable) or "development" if NODE_ENV is not set.): Environment mode. Be sure to set to "production" in a production environment; see [Production best practices: performance and reliability](/advanced/best-practice-performance#things-to-do-in-your-environment--setup). - etag (Boolean | String | Function, default: weak): Set the ETag response header. For possible values, see the `etag` options table below. [More about the HTTP ETag header](https://en.wikipedia.org/wiki/HTTP_ETag). - jsonp callback name (String, default: "callback"): Specifies the default JSONP callback name. - json escape (Boolean, default: N/A (undefined)): Enable escaping JSON responses from the `res.json`, `res.jsonp`, and `res.send` APIs. This will escape the characters `<`, `>`, and `&` as Unicode escape sequences in JSON. The purpose of this is to assist with [mitigating certain types of persistent XSS attacks](https://blog.mozilla.org/security/2017/07/18/web-service-audits-firefox-accounts/) when clients sniff responses for HTML. Sub-apps will inherit the value of this setting. - json replacer (Function | Array, default: N/A (undefined)): The ['replacer' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter). Sub-apps will inherit the value of this setting. - json spaces (Number | String, default: N/A (undefined)): The ['space' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_space_parameter). This is typically set to the number of spaces to use to indent prettified JSON. Sub-apps will inherit the value of this setting. - query parser (Boolean | String | Function, default: "simple"): Disable query parsing by setting the value to `false`, or set the query parser to use either "simple" or "extended" or a custom query string parsing function. The simple query parser is based on Node's native query parser, [querystring](https://nodejs.org/api/querystring.html). The extended query parser is based on [qs](https://www.npmjs.com/package/qs). A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values. - strict routing (Boolean, default: N/A (undefined)): Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same. This setting is read when the app first creates its router. Adding a route or middleware, calling `app.param()`, accessing `app.router`, or handling a request can create the router. Set it before any of these operations. Changing it afterwards has no effect on routing, including routes added later. Sub-apps inherit this setting unless they explicitly set their own value. If the sub-app's router already exists when the setting is inherited, `subApp.get('strict routing')` reports the inherited value, but the router keeps its original configuration. To avoid relying on mount order, set `strict routing` on the sub-app before its router is created. - subdomain offset (Number, default: 2): The number of dot-separated parts of the host to remove to access subdomain. - trust proxy (Boolean | String | Number | Function | Array, default: false (disabled)): Indicates the app is behind a front-facing proxy, and to use the `X-Forwarded-*` headers to determine the connection and the IP address of the client. `X-Forwarded-*` headers are easily spoofed and the detected IP addresses are unreliable. When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table below. The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation. Sub-apps _will_ inherit the value of this setting, even though it has a default value. - views (String | Array, default: process.cwd() + '/views'): A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array. - view cache (Boolean, default: true in production, otherwise undefined.): Enables view template compilation caching. Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production"). - view engine (String, default: N/A (undefined)): The default engine extension to use when omitted. Sub-apps will inherit the value of this setting. - x-powered-by (Boolean, default: true): Enables the "X-Powered-By: Express" HTTP header. #### Options for `trust proxy` setting Read [Express behind proxies](/guide/behind-proxies) for more information. **Boolean**: If `true`, the client's IP address is understood as the left-most entry in the `X-Forwarded-*` header. If `false`, the app is understood as directly facing the Internet and the client's IP address is derived from `req.connection.remoteAddress`. This is the default setting. **String / String containing comma-separated values / Array of strings**: An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are: - 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` Set IP addresses in any of the following ways: Specify a single subnet: ```js app.set('trust proxy', 'loopback'); ``` Specify a subnet and an address: ```js app.set('trust proxy', 'loopback, 123.123.123.123'); ``` Specify multiple subnets as CSV: ```js app.set('trust proxy', 'loopback, linklocal, uniquelocal'); ``` Specify multiple subnets as an array: ```js app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']); ``` 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. **Number**: Trust the *n*th hop from the front-facing proxy server as the client. **Function**: Custom trust implementation. Use this only if you know what you are doing. ```js app.set('trust proxy', (ip) => { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true; // trusted IPs else return false; }); ``` #### Options for `etag` setting These settings apply only to dynamic files, not static files. The `express.static` middleware ignores these settings. The ETag functionality is implemented using the [etag](https://www.npmjs.com/package/etag) package. For more information, see its documentation. Values: - Boolean: `true` enables weak ETag. This is the default setting. `false` disables ETag altogether. - String: If "strong", enables strong ETag. If "weak", enables weak ETag. - Function: Custom ETag function implementation. Use this only if you know what you are doing. ```js app.set('etag', (body, encoding) => { return generateHash(body, encoding); // consider the function is defined }); ``` ### app.use() Arguments: - path (String | RegExp | Array, optional): The path for which the middleware function is invoked; can be any of: a string representing a path, a path pattern, a regular expression pattern to match paths, or an array of combinations of any of the above. For examples, see [Path examples](#path-examples). - callback (Function | Function[]): Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since [router](/api/router/) and [app](/api/application/) implement the middleware interface, you can use them as you would any other middleware function. For examples, see [Middleware callback function examples](#middleware-callback-function-examples). Mounts the specified [middleware](/guide/using-middleware) function or functions at the specified path: the middleware function is executed when the base of the requested path matches `path`. #### Description With a string path, `app.use()` matches that path and its subpaths. For example, `app.use('/apple', ...)` matches `/apple`, `/apple/images`, and `/apple/images/news`, but not `/apples`. Since `path` defaults to "/", middleware mounted without a path will be executed for every request to the app. For example, this middleware function will be executed for _every_ request to the app: ```js app.use((req, res, next) => { console.log('Time: %d', Date.now()); next(); }); ``` ```ts app.use((req: Request, res: Response, next: NextFunction) => { console.log('Time: %d', Date.now()); next(); }); ``` Sub-apps will: - Not inherit the value of settings that have a default value. You must set the value in the sub-app. - Inherit the value of settings with no default value. For details, see [Application settings](#application-settings). Middleware functions are executed sequentially, therefore the order of middleware inclusion is important. ```js // this middleware will not allow the request to go beyond it app.use((req, res, next) => { res.send('Hello World'); }); // requests will never reach this route app.get('/', (req, res) => { res.send('Welcome'); }); ``` ```ts // this middleware will not allow the request to go beyond it app.use((req: Request, res: Response, next: NextFunction) => { res.send('Hello World'); }); // requests will never reach this route app.get('/', (req: Request, res: Response) => { res.send('Welcome'); }); ``` **Error-handling middleware** Error-handling middleware always takes _four_ arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don't need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: [Error handling](/guide/error-handling). Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`): ```js app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); ``` ```ts app.use((err: Error, req: Request, res: Response, next: NextFunction) => { console.error(err.stack); res.status(500).send('Something broke!'); }); ``` #### Path examples The following table provides some simple examples of valid `path` values for mounting middleware. **Path**: Matches the exact path `/abcd` and any sub-paths starting with `/abcd/` (for example, `/abcd/foo`): ```js app.use('/abcd', (req, res, next) => { next(); }); ``` ```ts app.use('/abcd', (req: Request, res: Response, next: NextFunction) => { next(); }); ``` **Path Pattern**: This will match paths starting with `/abcd` and `/abd`: ```js app.use('/ab{c}d', (req, res, next) => { next(); }); ``` ```ts app.use('/ab{c}d', (req: Request, res: Response, next: NextFunction) => { next(); }); ``` **Regular Expression**: This will match paths starting with `/abc` and `/xyz`: ```js app.use(/\/abc|\/xyz/, (req, res, next) => { next(); }); ``` ```ts app.use(/\/abc|\/xyz/, (req: Request, res: Response, next: NextFunction) => { next(); }); ``` **Array**: This will match paths starting with `/abcd`, `/xyza`, `/lmn`, and `/pqr`: ```js app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], (req, res, next) => { next(); }); ``` ```ts app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], (req: Request, res: Response, next: NextFunction) => { next(); }); ``` #### Middleware callback function examples The following table provides some simple examples of middleware functions that can be used as the `callback` argument to `app.use()`, `app.METHOD()`, and `app.all()`. **Single Middleware**: You can define and mount a middleware function locally. ```js app.use((req, res, next) => { next(); }); ``` ```ts app.use((req: Request, res: Response, next: NextFunction) => { next(); }); ``` A router is valid middleware. ```js const router = express.Router(); router.get('/', (req, res, next) => { next(); }); app.use(router); ``` ```ts const router = express.Router(); router.get('/', (req: Request, res: Response, next: NextFunction) => { next(); }); app.use(router); ``` An Express app is valid middleware. ```js const subApp = express(); subApp.get('/', (req, res, next) => { next(); }); app.use(subApp); ``` ```ts const subApp: Express = express(); subApp.get('/', (req: Request, res: Response, next: NextFunction) => { next(); }); app.use(subApp); ``` **Series of Middleware**: You can specify more than one middleware function at the same mount path. ```js const r1 = express.Router(); r1.get('/', (req, res, next) => { next(); }); const r2 = express.Router(); r2.get('/', (req, res, next) => { next(); }); app.use(r1, r2); ``` ```ts const r1 = express.Router(); r1.get('/', (req: Request, res: Response, next: NextFunction) => { next(); }); const r2 = express.Router(); r2.get('/', (req: Request, res: Response, next: NextFunction) => { next(); }); app.use(r1, r2); ``` **Array**: Use an array to group middleware logically. ```js const r1 = express.Router(); r1.get('/', (req, res, next) => { next(); }); const r2 = express.Router(); r2.get('/', (req, res, next) => { next(); }); app.use([r1, r2]); ``` ```ts const r1 = express.Router(); r1.get('/', (req: Request, res: Response, next: NextFunction) => { next(); }); const r2 = express.Router(); r2.get('/', (req: Request, res: Response, next: NextFunction) => { next(); }); app.use([r1, r2]); ``` **Combination**: You can combine all the above ways of mounting middleware. ```js function mw1(req, res, next) { next(); } function mw2(req, res, next) { next(); } const r1 = express.Router(); r1.get('/', (req, res, next) => { next(); }); const r2 = express.Router(); r2.get('/', (req, res, next) => { next(); }); const subApp = express(); subApp.get('/', (req, res, next) => { next(); }); app.use(mw1, [mw2, r1, r2], subApp); ``` ```ts function mw1(req: Request, res: Response, next: NextFunction) { next(); } function mw2(req: Request, res: Response, next: NextFunction) { next(); } const r1 = express.Router(); r1.get('/', (req: Request, res: Response, next: NextFunction) => { next(); }); const r2 = express.Router(); r2.get('/', (req: Request, res: Response, next: NextFunction) => { next(); }); const subApp: Express = express(); subApp.get('/', (req: Request, res: Response, next: NextFunction) => { next(); }); app.use(mw1, [mw2, r1, r2], subApp); ``` Following are some examples of using the [express.static](/guide/using-middleware/#built-in-middleware) middleware in an Express app. Serve static content for the app from the "public" directory in the application directory: ```js // GET /style.css etc app.use(express.static(path.join(__dirname, 'public'))); ``` Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static": ```js // GET /static/style.css etc. app.use('/static', express.static(path.join(__dirname, 'public'))); ``` Disable logging for static content requests by loading the logger middleware after the static middleware: ```js app.use(express.static(path.join(__dirname, 'public'))); app.use(logger()); ``` Serve static files from multiple directories, but give 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'))); ``` --- ## Express Object URL: https://expressjs.com/en/5x/api/express Creates an Express application. The `express()` function is a top-level function exported by the `express` module. ```cjs title="index.cjs" const express = require('express'); const app = express(); ``` ```mjs title="index.mjs" const app = express(); ``` ```ts title="index.ts" const app: Express = express(); ``` ## Methods The Express object has the following methods that can be used to create middleware functions, routers and have some built-in middleware: ### express.json() Returns: Function. Arguments: - options (Object, optional): Configures how the JSON body is parsed; it accepts the properties below. Properties: - defaultCharset (String, default: "utf-8"): Specify the default character set for the JSON content if the charset is not specified in the `Content-Type` header of the request. - inflate (Boolean, default: true): Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. - limit (Number | String, default: "100kb"): Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. - reviver (Function, default: null): The `reviver` option is passed directly to `JSON.parse` as the second argument. You can find more information on this argument [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter). ```js app.use(express.json({ reviver: (key, value) => key === 'createdAt' ? new Date(value) : value, })); // Body: {"createdAt":"2026-01-01T00:00:00Z"} // req.body.createdAt is a Date. ``` - strict (Boolean, default: true): Enables or disables only accepting arrays and objects; when disabled will accept anything `JSON.parse` accepts. ```js app.use(express.json({ strict: false })); // Body: 42 -> req.body is the number 42. // With strict: true (the default), this body is rejected with status 400. ``` - type (String | String[] | Function, default: "application/json"): This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this can be an extension name (like `json`), a mime type (like `application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. - verify (Function, default: undefined): This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ```js app.use(express.json({ verify: (req, res, buf) => { req.rawBody = buf; }, })); // req.rawBody contains the original Buffer, before JSON parsing. ``` This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on [body-parser](/resources/middleware/body-parser). Returns middleware that only parses JSON and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts any Unicode encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or `undefined` if there was no body to parse, the `Content-Type` was not matched, or an error occurred. As `req.body`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input. ```cjs title="index.cjs" ins={5} const express = require('express'); const app = express(); // parse requests with a Content-Type of application/json app.use(express.json()); app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body); }); ``` ```mjs title="index.mjs" ins={6} const app = express(); // parse requests with a Content-Type of application/json app.use(express.json()); app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body); }); ``` ```ts title="index.ts" const app: Express = express(); // parse requests with a Content-Type of application/json app.use(express.json()); app.post('/profile', (req: Request, res: Response) => { console.dir(req.body); res.json(req.body); }); ``` ### express.raw() Returns: Function. Arguments: - options (Object, optional): Configures how the request body is parsed; it accepts the properties below. Properties: - inflate (Boolean, default: true): Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. - limit (Number | String, default: "100kb"): Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. - type (String | String[] | Function, default: "application/octet-stream"): This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this can be an extension name (like `bin`), a mime type (like `application/octet-stream`), or a mime type with a wildcard (like `*/*` or `application/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. - verify (Function, default: undefined): This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. This is a built-in middleware function in Express. It parses incoming request payloads into a `Buffer` and is based on [body-parser](/resources/middleware/body-parser). Returns middleware that parses all bodies as a `Buffer` and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts any Unicode encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings. A new `body` `Buffer` containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or `undefined` if there was no body to parse, the `Content-Type` was not matched, or an error occurred. As `req.body`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.toString()` may fail in multiple ways, for example stacking multiple parsers `req.body` may be from a different parser. Testing that `req.body` is a `Buffer` before calling buffer methods is recommended. ```cjs title="index.cjs" ins={5} const express = require('express'); const app = express(); // parse requests with a Content-Type of application/octet-stream into a Buffer app.use(express.raw()); app.post('/upload', (req, res) => { console.dir(Buffer.isBuffer(req.body)); // => true res.send(`received ${req.body.length} bytes`); }); ``` ```mjs title="index.mjs" ins={6} const app = express(); // parse requests with a Content-Type of application/octet-stream into a Buffer app.use(express.raw()); app.post('/upload', (req, res) => { console.dir(Buffer.isBuffer(req.body)); // => true res.send(`received ${req.body.length} bytes`); }); ``` ```ts title="index.ts" const app: Express = express(); // parse requests with a Content-Type of application/octet-stream into a Buffer app.use(express.raw()); app.post('/upload', (req: Request, res: Response) => { console.dir(Buffer.isBuffer(req.body)); // => true res.send(`received ${req.body.length} bytes`); }); ``` ### express.Router() Returns: Router. Arguments: - caseSensitive (Boolean, default: false): Enable case sensitivity. Disabled by default, treating `/Foo` and `/foo` as the same. ```js // caseSensitive: treat "/Foo" and "/foo" as different routes const router = express.Router({ caseSensitive: true }); router.get('/Foo', (req, res) => res.send('Matched /Foo exactly')); ``` - 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 take precedence. ```js // mergeParams: access parent route params in child router const parent = express.Router(); const child = express.Router({ mergeParams: true }); parent.use('/user/:userId', child); child.get('/comments', (req, res) => { // req.params.userId is available because mergeParams: true res.send(`Comments for user ${req.params.userId}`); }); ``` - strict (Boolean, default: false): Enable strict routing. Disabled by default, `/foo` and `/foo/` are treated the same by the router. ```js // strict: treat "/foo" and "/foo/" as different routes const strictRouter = express.Router({ strict: true }); strictRouter.get('/foo/', (req, res) => res.send('Matched /foo/ with trailing slash')); ``` Creates a new [router](/api/router/) object. ```js const router = express.Router([options]); ``` You can add middleware and HTTP method routes (such as `get`, `put`, `post`, and so on) to `router` just like an application. For more information, see [Router](/api/router/). ### express.static() Returns: Function. Arguments: - root (String): The root directory from which to serve static assets. - options (Object, optional): Configures how files are served; it accepts the properties below. See also the [example below](#example-of-expressstatic). Properties: - dotfiles (String, default: "ignore"): Determines how dotfiles (files or directories that begin with a dot ".") are treated. See [dotfiles](#dotfiles) below. - etag (Boolean, default: true): Enable or disable etag generation. `express.static` always sends weak ETags. - extensions (String[] | Boolean, default: false): Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: `['html', 'htm']`. - fallthrough (Boolean, default: true): Let client errors fall-through as unhandled requests, otherwise forward a client error. See [fallthrough](#fallthrough) below. ```js app.use('/assets', express.static('public', { fallthrough: true })); app.use('/assets', (req, res) => { res.status(404).send('Asset not found'); }); // Missing files reach the fallback above. // With fallthrough: false, they reach error-handling middleware instead. ``` - 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. 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. ```js // Use filenames that change whenever the file contents change. app.use('/assets', express.static('public', { maxAge: '1y', immutable: true, })); // Cache-Control: public, max-age=31536000, immutable ``` - index (String | Boolean, default: "index.html"): Sends the specified directory index file. Set to `false` to disable directory indexing. - lastModified (Boolean, default: true): Set the `Last-Modified` header to the last modified date of the file on the OS. - maxAge (Number, default: 0): Set the max-age property of the Cache-Control header in milliseconds or a string in [ms format](https://www.npmjs.com/package/ms). - redirect (Boolean, default: true): Redirect to trailing "/" when the pathname is a directory. - setHeaders (Function): Function for setting HTTP headers to serve with the file. See [setHeaders](#setheaders) below. - acceptRanges (Boolean, default: true): Enable or disable accepting ranged requests. Disabling this will not send the `Accept-Ranges` header and will ignore the contents of the Range request header. - cacheControl (Boolean, default: true): Enable or disable setting the `Cache-Control` response header. Disabling this will ignore the immutable and maxAge options. This is a built-in middleware function in Express. It serves static files and is based on [serve-static](/resources/middleware/serve-static). For best results, [use a reverse proxy](/advanced/best-practice-performance#use-a-reverse-proxy) cache to improve performance of serving static assets. The `root` argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining `req.url` with the provided `root` directory. When a file is not found, instead of sending a 404 response, it instead calls `next()` to move on to the next middleware, allowing for stacking and fall-backs. For more information, see [Serving static files in Express](/starter/static-files). and [Using middleware - Built-in middleware](/guide/using-middleware/#built-in-middleware). #### dotfiles Possible values for this option are: - "allow" - No special treatment for dotfiles. - "deny" - Deny a request for a dotfile, respond with `403`, then call `next()`. - "ignore" - Act as if the dotfile does not exist, respond with `404`, then call `next()`. #### fallthrough When this option is `true`, client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call `next()` to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke `next(err)`. Set this option to `true` so you can map multiple physical directories to the same web address or for routes to fill in non-existent files. Use `false` if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods. #### setHeaders For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously. The signature of the function is: ```js fn(res, path, stat); ``` Arguments: - `res`, the [response object](/api/response/). - `path`, the file path that is being sent. - `stat`, the `stat` object of the file that is being sent. #### Example of express.static Here is an example of using the `express.static` middleware function with an elaborate options object: ```cjs title="index.cjs" ins={16} const express = require('express'); const app = express(); const options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders(res, path, stat) { res.set('x-timestamp', Date.now()); }, }; app.use(express.static('public', options)); ``` ```mjs title="index.mjs" ins={17} const app = express(); const options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders(res, path, stat) { res.set('x-timestamp', Date.now()); }, }; app.use(express.static('public', options)); ``` ```ts title="index.ts" const app: Express = express(); const options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders(res, path, stat) { res.set('x-timestamp', Date.now()); }, }; app.use(express.static('public', options)); ``` ### express.text() Returns: Function. Arguments: - options (Object, optional): Configures how the text body is parsed; it accepts the properties below. Properties: - defaultCharset (String, default: "utf-8"): Specify the default character set for the text content if the charset is not specified in the `Content-Type` header of the request. - inflate (Boolean, default: true): Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. - limit (Number | String, default: "100kb"): Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. - type (String | String[] | Function, default: "text/plain"): This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this can be an extension name (like `txt`), a mime type (like `text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. - verify (Function, default: undefined): This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. This is a built-in middleware function in Express. It parses incoming request payloads into a string and is based on [body-parser](/resources/middleware/body-parser). Returns middleware that parses all bodies as a string and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts any Unicode encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings. A new `body` string containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or `undefined` if there was no body to parse, the `Content-Type` was not matched, or an error occurred. As `req.body`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.trim()` may fail in multiple ways, for example stacking multiple parsers `req.body` may be from a different parser. Testing that `req.body` is a string before calling string methods is recommended. ```cjs title="index.cjs" ins={5} const express = require('express'); const app = express(); // parse requests with a Content-Type of text/plain into a string app.use(express.text()); app.post('/', (req, res) => { console.dir(typeof req.body); // => 'string' res.send(req.body); }); ``` ```mjs title="index.mjs" ins={6} const app = express(); // parse requests with a Content-Type of text/plain into a string app.use(express.text()); app.post('/', (req, res) => { console.dir(typeof req.body); // => 'string' res.send(req.body); }); ``` ```ts title="index.ts" const app: Express = express(); // parse requests with a Content-Type of text/plain into a string app.use(express.text()); app.post('/', (req: Request, res: Response) => { console.dir(typeof req.body); // => 'string' res.send(req.body); }); ``` ### express.urlencoded() Returns: Function. Arguments: - options (Object, optional): Configures how the URL-encoded body is parsed; it accepts the properties below. Properties: - extended (Boolean, default: false): This option allows you to choose between parsing the URL-encoded data with the `querystring` library (when `false`) or the `qs` library (when `true`). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please [see the qs library](https://www.npmjs.com/package/qs#readme). ```js // Form body: user[name]=Tobi app.post('/simple', express.urlencoded({ extended: false }), (req, res) => { res.json(req.body); // => { 'user[name]': 'Tobi' } }); app.post('/extended', express.urlencoded({ extended: true }), (req, res) => { res.json(req.body); // => { user: { name: 'Tobi' } } }); ``` - inflate (Boolean, default: true): Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. - limit (Number | String, default: "100kb"): Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. - parameterLimit (Number, default: 1000): This option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, an error will be raised. - type (String | String[] | Function, default: "application/x-www-form-urlencoded"): This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this can be an extension name (like `urlencoded`), a mime type (like `application/x-www-form-urlencoded`), or a mime type with a wildcard (like `*/x-www-form-urlencoded`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. - verify (Function, default: undefined): This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. - defaultCharset (String, default: "utf-8"): The default charset to parse as, if not specified in content-type. Must be either `utf-8` or `iso-8859-1`. - charsetSentinel (Boolean, default: false): Whether to let the value of the `utf8` parameter take precedence as the charset selector. It requires the form to contain a parameter named `utf8` with a value of `✓`. - interpretNumericEntities (Boolean, default: false): Whether to decode numeric entities such as `☺` when parsing an iso-8859-1 form. - depth (Number, default: 32): Configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. It is recommended to keep this value as low as possible. This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on [body-parser](/resources/middleware/body-parser). Returns middleware that only parses urlencoded bodies and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`), or `undefined` if there was no body to parse, the `Content-Type` was not matched, or an error occurred. This object will contain key-value pairs, where the value can be a string or array (when `extended` is `false`), or any type (when `extended` is `true`). As `req.body`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input. ```cjs title="index.cjs" ins={5} const express = require('express'); const app = express(); // parse requests with a Content-Type of application/x-www-form-urlencoded app.use(express.urlencoded({ extended: true })); app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body); }); ``` ```mjs title="index.mjs" ins={6} const app = express(); // parse requests with a Content-Type of application/x-www-form-urlencoded app.use(express.urlencoded({ extended: true })); app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body); }); ``` ```ts title="index.ts" const app: Express = express(); // parse requests with a Content-Type of application/x-www-form-urlencoded app.use(express.urlencoded({ extended: true })); app.post('/profile', (req: Request, res: Response) => { console.dir(req.body); res.json(req.body); }); ``` --- ## Request Object URL: https://expressjs.com/en/5x/api/request The `req` object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as `req` (and the HTTP response is `res`) but its actual name is determined by the parameters to the callback function in which you're working. For example: ```js app.get('/user/:id', (req, res) => { res.send(`user ${req.params.id}`); }); ``` ```ts app.get('/user/:id', (req: Request, res: Response) => { res.send(`user ${req.params.id}`); }); ``` But you could just as well have: ```js app.get('/user/:id', (request, response) => { response.send(`user ${request.params.id}`); }); ``` ```ts app.get('/user/:id', (request: Request, response: Response) => { response.send(`user ${request.params.id}`); }); ``` The `req` object is an enhanced version of Node's own request object and supports all [built-in fields and methods](https://nodejs.org/api/http.html#class-httpincomingmessage). ## Properties The `req` object contains a number of properties that provide information about the HTTP request, such as headers, query parameters, and more. ### req.app Type: Application. This property holds a reference to the instance of the Express application that is using the middleware. If you follow the pattern in which you create a module that just exports a middleware function and `require()` it in your main file, then the middleware can access the Express instance via `req.app` For example: ```cjs title="index.cjs" app.get('/viewdirectory', require('./mymiddleware.cjs')); ``` ```mjs title="index.mjs" app.get('/viewdirectory', mymiddleware); ``` And the middleware module itself: ```cjs title="mymiddleware.cjs" module.exports = (req, res) => { res.send(`The views directory is ${req.app.get('views')}`); }; ``` ```mjs title="mymiddleware.mjs" export default (req, res) => { res.send(`The views directory is ${req.app.get('views')}`); }; ``` ```ts title="mymiddleware.ts" export default (req: Request, res: Response) => { res.send(`The views directory is ${req.app.get('views')}`); }; ``` ### req.baseUrl Type: String. The URL path on which a router instance was mounted. The `req.baseUrl` property is similar to the [mountpath](/api/application/#appmountpath) property of the `app` object, except `app.mountpath` returns the matched path pattern(s). For example: ```js const greet = express.Router(); greet.get('/jp', (req, res) => { console.log(req.baseUrl); // /greet res.send('Konnichiwa!'); }); app.use('/greet', greet); // load the router on '/greet' ``` ```ts const greet = express.Router(); greet.get('/jp', (req: Request, res: Response) => { console.log(req.baseUrl); // /greet res.send('Konnichiwa!'); }); app.use('/greet', greet); // load the router on '/greet' ``` Even if you use a path pattern or a set of path patterns to load the router, the `baseUrl` property returns the matched string, not the pattern(s). In the following example, the `greet` router is loaded on two path patterns. ```js app.use(['/gre:"param"t', '/hel{l}o'], greet); // load the router on '/gre:"param"t' and '/hel{l}o' ``` When a request is made to `/greet/jp`, `req.baseUrl` is "/greet". When a request is made to `/hello/jp`, `req.baseUrl` is "/hello". ### req.body Type: Object. Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use body-parsing middleware such as [`express.json()`](/api/express/#expressjson) or [`express.urlencoded()`](/api/express/#expressurlencoded). As `req.body`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input. The following example shows how to use body-parsing middleware to populate `req.body`. ```cjs title="index.cjs" const express = require('express'); const app = express(); app.use(express.json()); // for parsing application/json app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.post('/profile', (req, res, next) => { console.log(req.body); res.json(req.body); }); ``` ```mjs title="index.mjs" const app = express(); app.use(express.json()); // for parsing application/json app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.post('/profile', (req, res, next) => { console.log(req.body); res.json(req.body); }); ``` ```ts title="index.ts" const app: Express = express(); app.use(express.json()); // for parsing application/json app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.post('/profile', (req: Request, res: Response, next: NextFunction) => { console.log(req.body); res.json(req.body); }); ``` ### req.cookies Type: Object. When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to `{}`. ```js // Cookie: name=tj console.dir(req.cookies.name); // => 'tj' ``` If the cookie has been signed, you have to use [req.signedCookies](#reqsignedcookies). For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser). ### req.fresh Type: Boolean. When the response is still "fresh" in the client's cache `true` is returned, otherwise `false` is returned to indicate that the client cache is now stale and the full response should be sent. When a client sends the `Cache-Control: no-cache` request header to indicate an end-to-end reload request, this module will return `false` to make handling these requests transparent. Further details for how cache validation works can be found in the [HTTP/1.1 Caching Specification](https://tools.ietf.org/html/rfc7234). ```js console.dir(req.fresh); // => true ``` ### req.hostname Type: String. Contains the hostname derived from the `Host` HTTP header. When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting) does not evaluate to `false`, this property will instead get the value from the `X-Forwarded-Host` header field. This header can be set by the client or by the proxy. If there is more than one `X-Forwarded-Host` header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used. ```js // Host: "example.com:3000" console.dir(req.hostname); // => 'example.com' ``` ### req.host Type: String. Contains the host derived from the `Host` HTTP header. When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting) does not evaluate to `false`, this property will instead get the value from the `X-Forwarded-Host` header field. This header can be set by the client or by the proxy. If there is more than one `X-Forwarded-Host` header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used. ```js // Host: "example.com:3000" console.dir(req.host); // => 'example.com:3000' // Host: "[::1]:3000" console.dir(req.host); // => '[::1]:3000' ``` ### req.ip Type: String. Contains the remote IP address of the request. When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting) does not evaluate to `false`, the value of this property is derived from the left-most entry in the `X-Forwarded-For` header. This header can be set by the client or by the proxy. ```js console.dir(req.ip); // => '127.0.0.1' ``` ### req.ips Type: String[]. When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting) does not evaluate to `false`, this property contains an array of IP addresses specified in the `X-Forwarded-For` request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy. For example, if `X-Forwarded-For` is `client, proxy1, proxy2`, `req.ips` would be `["client", "proxy1", "proxy2"]`, where `proxy2` is the furthest downstream. ```js // normal request, or `trust proxy` disabled (the default) console.dir(req.ips); // => [] // app.set('trust proxy', true) and // request header `X-Forwarded-For: client, proxy1, proxy2` console.dir(req.ips); // => ['client', 'proxy1', 'proxy2'] ``` ### req.method Type: String. Contains a string corresponding to the HTTP method of the request: `GET`, `POST`, `PUT`, and so on. ```js app.use((req, res, next) => { console.dir(req.method); // => 'GET' next(); }); ``` ```ts app.use((req: Request, res: Response, next: NextFunction) => { console.dir(req.method); // => 'GET' next(); }); ``` ### req.originalUrl Type: String. `req.url` is not a native Express property, it is inherited from Node's [http module](https://nodejs.org/api/http.html#messageurl). This property is much like `req.url`; however, it retains the original request URL, allowing you to rewrite `req.url` freely for internal routing purposes. For example, the "mounting" feature of [app.use()](/api/application/#appuse) will rewrite `req.url` to strip the mount point. ```js // GET /search?q=something console.dir(req.originalUrl); // => '/search?q=something' ``` `req.originalUrl` is available both in middleware and router objects, and is a combination of `req.baseUrl` and `req.url`. Consider following example: ```js // GET 'http://www.example.com/admin/new?sort=desc' app.use('/admin', (req, res, next) => { console.dir(req.originalUrl); // '/admin/new?sort=desc' console.dir(req.baseUrl); // '/admin' console.dir(req.path); // '/new' next(); }); ``` ```ts // GET 'http://www.example.com/admin/new?sort=desc' app.use('/admin', (req: Request, res: Response, next: NextFunction) => { console.dir(req.originalUrl); // '/admin/new?sort=desc' console.dir(req.baseUrl); // '/admin' console.dir(req.path); // '/new' next(); }); ``` ### req.params Type: Object. This property is an object containing properties mapped to the [named route "parameters"](/guide/routing/#route-parameters). For example, if you have the route `/user/:name`, then the "name" property is available as `req.params.name`. This object defaults to `Object.create(null)` when using string paths, but remains a standard object with a normal prototype when the path is defined with a regular expression. ```js // GET /user/tj console.dir(req.params.name); // => 'tj' ``` Properties corresponding to wildcard parameters are arrays containing separate path segments split on `/`: ```js app.get('/files/*file', (req, res) => { console.dir(req.params.file); // GET /files/note.txt // => [ 'note.txt' ] // GET /files/images/image.png // => [ 'images', 'image.png' ] }); ``` ```ts app.get('/files/*file', (req: Request, res: Response) => { console.dir(req.params.file); // GET /files/note.txt // => [ 'note.txt' ] // GET /files/images/image.png // => [ 'images', 'image.png' ] }); ``` Parameters defined in [optional segments](/guide/routing/#optional-segments) that are not present in the request URL are omitted from `req.params` entirely. When you use a regular expression for the route definition, capture groups are provided as integer keys using `req.params[n]`, where `n` is the nth capture group. ```js app.use(/^\/file\/(.*)$/, (req, res) => { // GET /file/javascripts/jquery.js console.dir(req.params[0]); // => 'javascripts/jquery.js' }); ``` ```ts app.use(/^\/file\/(.*)$/, (req: Request, res: Response) => { // GET /file/javascripts/jquery.js console.dir(req.params[0]); // => 'javascripts/jquery.js' }); ``` Named capturing groups in regular expressions behave like named route parameters. For example the group from `/^\/file\/(?.*)$/` expression is available as `req.params.path`. If you need to make changes to a key in `req.params`, use the [app.param](/api/application/#appparam) handler. Changes are applicable only to [parameters](/guide/routing/#route-parameters) already defined in the route path. Any changes made to the `req.params` object in a middleware or route handler will be reset. Express automatically decodes the values in `req.params` (using `decodeURIComponent`). ### req.path Type: String. Contains the path part of the request URL. ```js // example.com/users?sort=desc console.dir(req.path); // => '/users' ``` When called from a middleware, the mount point is not included in `req.path`. See [app.use()](/api/application/#appuse) for more details. ### req.protocol Type: String. Contains the request protocol string: either `http` or (for TLS requests) `https`. When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting) does not evaluate to `false`, this property will use the value of the `X-Forwarded-Proto` header field if present. This header can be set by the client or by the proxy. ```js console.dir(req.protocol); // => 'http' ``` ### req.query Type: Object. This property is an object containing a property for each query string parameter in the route. When [query parser](/api/application/#application-settings) is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser. As `req.query`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.query.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input. The value of this property can be configured with the [query parser application setting](/api/application/#application-settings) to work how your application needs it. A very popular query string parser is the [`qs` module](https://www.npmjs.com/package/qs), and this is used by default. The `qs` module is very configurable with many settings, and it may be desirable to use different settings than the default to populate `req.query`: ```cjs title="index.cjs" const qs = require('qs'); app.set('query parser', (str) => qs.parse(str, { /* custom options */ }) ); ``` ```mjs title="index.mjs" app.set('query parser', (str) => qs.parse(str, { /* custom options */ }) ); ``` ```ts title="index.ts" app.set('query parser', (str: string) => qs.parse(str, { /* custom options */ }) ); ``` Check out the [query parser application setting](/api/application/#application-settings) documentation for other customization options. ### req.res Type: Response. This property holds a reference to the [response object](/api/response) that relates to this request object. ```js app.get('/', (req, res) => { console.dir(req.res === res); // => true res.send('OK'); }); ``` ```ts app.get('/', (req: Request, res: Response) => { console.dir(req.res === res); // => true res.send('OK'); }); ``` ### req.route Type: Route. Contains the currently-matched route (a `Route` object). For example: ```js app.get('/user/{:id}', (req, res) => { console.dir(req.route, { depth: null }); res.send('GET'); }); ``` ```ts app.get('/user/{:id}', (req: Request, res: Response) => { console.dir(req.route, { depth: null }); res.send('GET'); }); ``` Example output from the previous snippet: ``` Route { path: '/user/{:id}', stack: [ Layer { handle: [Function (anonymous)], keys: [], name: '', params: undefined, path: undefined, slash: false, matchers: [ [Function: match] ], method: 'get' } ], methods: [Object: null prototype] { get: true } } ``` ### req.secure Type: Boolean. A Boolean property that is true if a TLS connection is established. Equivalent to the following: {/* */} ```js req.protocol === 'https'; ``` ### req.signedCookies Type: Object. When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside in a different object to show developer intent; otherwise, a malicious attack could be placed on `req.cookie` values (which are easy to spoof). Note that signing a cookie does not make it "hidden" or encrypted; but simply prevents tampering (because the secret used to sign is private). If no signed cookies are sent, the property defaults to `{}`. ```js // Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3 console.dir(req.signedCookies.user); // => 'tobi' ``` For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser). ### req.stale Type: Boolean. Indicates whether the request is "stale," and is the opposite of `req.fresh`. For more information, see [req.fresh](#reqfresh). ```js console.dir(req.stale); // => true ``` ### req.subdomains Type: String[]. An array of subdomains in the domain name of the request. ```js // Host: "tobi.ferrets.example.com" console.dir(req.subdomains); // => ['ferrets', 'tobi'] ``` The application property `subdomain offset`, which defaults to 2, is used for determining the beginning of the subdomain segments. To change this behavior, change its value using [app.set](/api/application/#appset). ### req.xhr Type: Boolean. A Boolean property that is `true` if the request's `X-Requested-With` header field is "XMLHttpRequest", indicating that the request was issued by a client library such as jQuery. ```js console.dir(req.xhr); // => true ``` ## Methods The `req` object also contains a number of methods that can be used to perform various tasks related to the HTTP request, such as checking the content type, retrieving header values, and more. ### req.accepts() Returns: String | false. Arguments: - types (String | String[]): The content type(s) to check: a MIME type (such as `application/json`), an extension name (such as `json`), a comma-delimited list, or an array. Checks if the specified content types are acceptable, based on the request's `Accept` HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns `false` (in which case, the application should respond with `406 "Not Acceptable"`). The `type` value may be a single MIME type string (such as "application/json"), an extension name such as "json", a comma-delimited list, or an array. For a list or array, the method returns the _best_ match (if any). ```js // Accept: text/html req.accepts('html'); // => 'html' // Accept: text/*, application/json req.accepts('html'); // => 'html' req.accepts('text/html'); // => 'text/html' req.accepts(['json', 'text']); // => 'json' req.accepts('application/json'); // => 'application/json' // Accept: text/*, application/json req.accepts('image/png'); req.accepts('png'); // => false // Accept: text/*;q=.5, application/json req.accepts(['html', 'json']); // => 'json' ``` For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). ### req.acceptsCharsets() Returns: String | false. Arguments: - charset (String | String[]): One or more character sets to test against the request's `Accept-Charset` header. Returns the first accepted charset of the specified character sets, based on the request's `Accept-Charset` HTTP header field. If none of the specified charsets is accepted, returns `false`. ```js // Accept-Charset: utf-8, iso-8859-1;q=0.5 req.acceptsCharsets('utf-8', 'iso-8859-1'); // => 'utf-8' req.acceptsCharsets('us-ascii'); // => false ``` For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). ### req.acceptsEncodings() Returns: String | false. Arguments: - encoding (String | String[]): One or more encodings to test against the request's `Accept-Encoding` header. Returns the first accepted encoding of the specified encodings, based on the request's `Accept-Encoding` HTTP header field. If none of the specified encodings is accepted, returns `false`. ```js // Accept-Encoding: gzip, deflate req.acceptsEncodings('gzip', 'deflate'); // => 'gzip' req.acceptsEncodings('br'); // => false ``` For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). ### req.acceptsLanguages() Returns: String | String[] | false. Arguments: - lang (String | String[], optional): One or more languages to test against the request's `Accept-Language` header. If omitted, all accepted languages are returned as an array. Returns the first accepted language of the specified languages, based on the request's `Accept-Language` HTTP header field. If none of the specified languages is accepted, returns `false`. If no `lang` argument is given, then `req.acceptsLanguages()` returns all languages from the HTTP `Accept-Language` header as an `Array`. ```js // Accept-Language: en;q=0.8, es req.acceptsLanguages('en', 'es'); // => 'es' req.acceptsLanguages(); // => ['es', 'en'] ``` For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). Express (5.x) source: [request.js line 172](https://github.com/expressjs/express/blob/v5.1.0/lib/request.js#L172) Accepts (2.0) source: [index.js line 195](https://github.com/jshttp/accepts/blob/2.0.0/index.js#L195) ### req.get() Returns: String | undefined. Arguments: - field (String): The name of the HTTP request header to read (case-insensitive). `Referrer` and `Referer` are interchangeable. Returns the specified HTTP request header field (case-insensitive match). The `Referrer` and `Referer` fields are interchangeable. ```js req.get('Content-Type'); // => 'text/plain' req.get('content-type'); // => 'text/plain' req.get('Something'); // => undefined ``` Aliased as `req.header(field)`. ### req.is() Returns: String | false | null. Arguments: - type (String | String[]): The MIME type(s) or extension name(s) to match against the request's `Content-Type` header. Returns the matching content type if the incoming request's "Content-Type" HTTP header field matches the MIME type specified by the `type` parameter. If the request has no body, returns `null`. Returns `false` otherwise. ```js // With Content-Type: text/html; charset=utf-8 req.is('html'); // => 'html' req.is('text/html'); // => 'text/html' req.is('text/*'); // => 'text/*' // When Content-Type is application/json req.is('json'); // => 'json' req.is('application/json'); // => 'application/json' req.is('application/*'); // => 'application/*' // Using arrays // When Content-Type is application/json req.is(['json', 'html']); // => 'json' // Using multiple arguments // When Content-Type is application/json req.is('json', 'html'); // => 'json' req.is('html'); // => false req.is(['xml', 'yaml']); // => false req.is('xml', 'yaml'); // => false ``` For more information, or if you have issues or concerns, see [type-is](https://github.com/expressjs/type-is). ### req.range() Returns: Array | Number. Arguments: - size (Number): The maximum size of the resource. - options (Object, optional): Options for parsing the `Range` header. Properties: - combine (Boolean, default: false): Specify if overlapping and adjacent ranges should be combined. When `true`, ranges are combined and returned as if they were specified that way in the header. ```js // Range: bytes=0-99,50-149 const separate = req.range(1000, { combine: false }); console.log(separate[0]); // => { start: 0, end: 99 } console.log(separate[1]); // => { start: 50, end: 149 } const combined = req.range(1000, { combine: true }); console.log(combined[0]); // => { start: 0, end: 149 } ``` `Range` header parser. An array of ranges will be returned or negative numbers indicating an error parsing. - `-2` signals a malformed header string - `-1` signals an unsatisfiable range ```js // parse header from request const range = req.range(1000); // the type of the range if (range.type === 'bytes') { // the ranges range.forEach((r) => { // do something with r.start and r.end }); } ``` --- ## Response URL: https://expressjs.com/en/5x/api/response The `res` object represents the HTTP response that an Express app sends when it gets an HTTP request. In this documentation and by convention, the object is always referred to as `res` (and the HTTP request is `req`) but its actual name is determined by the parameters to the callback function in which you're working. For example: ```js app.get('/user/:id', (req, res) => { res.send(`user ${req.params.id}`); }); ``` ```ts app.get('/user/:id', (req: Request, res: Response) => { res.send(`user ${req.params.id}`); }); ``` But you could just as well have: ```js app.get('/user/:id', (request, response) => { response.send(`user ${request.params.id}`); }); ``` ```ts app.get('/user/:id', (request: Request, response: Response) => { response.send(`user ${request.params.id}`); }); ``` The `res` object is an enhanced version of Node's own response object and supports all [built-in fields and methods](https://nodejs.org/api/http.html#class-httpserverresponse). ## Properties ### res.app Type: Application. This property holds a reference to the instance of the Express application that is using the middleware. `res.app` is identical to the [req.app](/api/request/#reqapp) property in the request object. ```js app.get('/', (req, res) => { console.dir(res.app.get('view engine')); console.dir(res.app === req.app); // => true res.send('OK'); }); ``` ```ts app.get('/', (req: Request, res: Response) => { console.dir(res.app.get('view engine')); console.dir(res.app === req.app); // => true res.send('OK'); }); ``` ### res.headersSent Type: Boolean. Boolean property that indicates if the app sent HTTP headers for the response. ```js app.get('/', (req, res) => { console.log(res.headersSent); // false res.send('OK'); console.log(res.headersSent); // true }); ``` ```ts app.get('/', (req: Request, res: Response) => { console.log(res.headersSent); // false res.send('OK'); console.log(res.headersSent); // true }); ``` ### res.locals Type: Object. Use this property to set variables accessible in templates rendered with [res.render](#resrender). The variables set on `res.locals` are available within a single request-response cycle, and will not be shared between requests. The `locals` object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations. In order to keep local variables for use in template rendering between requests, use [app.locals](/api/application/#applocals) instead. This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application. ```js app.use((req, res, next) => { // Make `user` and `authenticated` available in templates res.locals.user = req.user; res.locals.authenticated = !req.user.anonymous; next(); }); ``` ```ts app.use((req: Request, res: Response, next: NextFunction) => { // Make `user` and `authenticated` available in templates res.locals.user = req.user; res.locals.authenticated = !req.user.anonymous; next(); }); ``` ### res.req Type: Request. This property holds a reference to the [request object](/api/request/) that relates to this response object. ```js app.get('/', (req, res) => { console.dir(res.req === req); // => true res.send('OK'); }); ``` ```ts app.get('/', (req: Request, res: Response) => { console.dir(res.req === req); // => true res.send('OK'); }); ``` ## Methods ### res.append() Returns: Response. Arguments: - field (String): The name of the HTTP response header to append to. - value (String | String[], optional): The value(s) to append to the header. Appends the specified `value` to the HTTP response header `field`. If the header is not already set, it creates the header with the specified value. The `value` parameter can be a string or an array. calling `res.set()` after `res.append()` will reset the previously-set header value. ```js res.append('Link', ['', '']); res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); res.append('Warning', '199 Miscellaneous warning'); ``` ### res.attachment() Returns: Response. Arguments: - filename (String, optional): The file name used to set the `Content-Disposition` "filename=" parameter and the `Content-Type` (from its extension). Sets the HTTP response `Content-Disposition` header field to "attachment". If a `filename` is given, then it sets the `Content-Type` based on the extension name via `res.type()`, and sets the `Content-Disposition` "filename=" parameter. ```js res.attachment(); // Content-Disposition: attachment res.attachment('path/to/logo.png'); // Content-Disposition: attachment; filename="logo.png" // Content-Type: image/png ``` ### res.clearCookie() Returns: Response. Arguments: - name (String): The name of the cookie to clear. - options (Object, optional): Cookie options, which should match those given to [res.cookie()](#rescookie) (excluding `expires` and `maxAge`). Clears the cookie with the specified `name` by sending a `Set-Cookie` header that sets its expiration date in the past. This instructs the client that the cookie has expired and is no longer valid. For more information about available `options`, see [res.cookie()](#rescookie). The `expires` and `maxAge` options are being ignored completely. Web browsers and other compliant clients will only clear the cookie if the given `options` is identical to those given to [res.cookie()](#rescookie) ```js res.cookie('name', 'tobi', { path: '/admin' }); res.clearCookie('name', { path: '/admin' }); ``` ### res.cookie() Returns: Response. Arguments: - name (String): The name of the cookie. - value (String | Object): The cookie value; an object is serialized as JSON. - options (Object, optional): Options for the `Set-Cookie` header. Properties: - domain (String): Domain name for the cookie. Defaults to the domain name of the app. - encode (Function): A synchronous function used for cookie value encoding. Defaults to `encodeURIComponent`. - expires (Date): Expiry date of the cookie in GMT. If not specified or set to `0`, creates a session cookie. - httpOnly (Boolean): Flags the cookie to be accessible only by the web server. - maxAge (Number): Convenient option for setting the expiry time relative to the current time in milliseconds. - path (String, default: "/"): Path for the cookie. Defaults to "/". - partitioned (Boolean): Indicates that the cookie should be stored using partitioned storage. See [CHIPS](https://developer.mozilla.org/en-US/docs/Web/Privacy/Guides/Third-party_cookies/Partitioned_cookies) for more details. - priority (String): Value of the "Priority" **Set-Cookie** attribute. - secure (Boolean): Marks the cookie to be used with HTTPS only. - signed (Boolean): Indicates if the cookie should be signed. - sameSite (Boolean | String): Value of the "SameSite" **Set-Cookie** attribute. Sets cookie `name` to `value`. The `value` parameter may be a string or object converted to JSON. All `res.cookie()` does is set the HTTP `Set-Cookie` header with the options provided. Any option not specified defaults to the value stated in [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265). For example: ```js res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); res.cookie('remember_me', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); ``` You can set multiple cookies in a single response by calling `res.cookie` multiple times, for example: ```js res .status(201) .cookie('access_token', `Bearer ${token}`, { expires: new Date(Date.now() + 8 * 3600000), // cookie will be removed after 8 hours }) .cookie('test', 'test') .redirect(301, '/admin'); ``` The `encode` option allows you to choose the function used for cookie value encoding. Does not support asynchronous functions. Example use case: You need to set a domain-wide cookie for another site in your organization. This other site (not under your administrative control) does not use URI-encoded cookie values. ```js // Default encoding res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' }); // Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/' // Custom encoding res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com', encode: String, }); // Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;' ``` The `maxAge` option is a convenience option for setting "expires" relative to the current time in milliseconds. The following is equivalent to the second example above. ```js res.cookie('remember_me', '1', { maxAge: 900000, httpOnly: true }); ``` You can pass an object as the `value` parameter; it is then serialized as JSON and parsed by `bodyParser()` middleware. ```js res.cookie('cart', { items: [1, 2, 3] }); res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 }); ``` When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this method also supports signed cookies. Simply include the `signed` option set to `true`. Then, `res.cookie()` will use the secret passed to `cookieParser(secret)` to sign the value. ```js res.cookie('name', 'tobi', { signed: true }); ``` Later, you may access this value through the [req.signedCookies](/api/request/#reqsignedcookies) object. ### res.download() Arguments: - path (String): The path to the file to transfer. If relative, it is resolved against the current working directory or the `root` option. - filename (String, optional): The file name for the `Content-Disposition` "filename=" parameter; overrides the name derived from `path`. - options (Object, optional): Options forwarded to [res.sendFile()](#ressendfile). 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 `path` as an "attachment". Typically, browsers will prompt the user for download. By default, the `Content-Disposition` header "filename=" parameter is derived from the `path` argument, but can be overridden with the `filename` parameter. If `path` is relative, then it will be based on the current working directory of the process or the `root` option, if provided. This API provides access to data on the running file system. Ensure that either (a) the way in which the `path` argument was constructed 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, 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. ```js res.download('/report-12345.pdf'); res.download('/report-12345.pdf', 'report.pdf'); res.download('/report-12345.pdf', 'report.pdf', (err) => { if (err) { // Handle error, but keep in mind the response may be partially-sent // so check res.headersSent } else { // decrement a download credit, etc. } }); ``` ### res.end() Returns: Response. Arguments: - data (String | Buffer, optional): Data to write before ending the response. - encoding (String, optional): The encoding for `data` when it is a string. - callback (Function, optional): Called once the response has finished. Ends the response process. This method actually comes from Node core, specifically the [response.end() method of http.ServerResponse](https://nodejs.org/api/http.html#responseenddata-encoding-callback). Use to quickly end the response without any data. If you need to respond with data, instead use methods such as [res.send()](#ressend) and [res.json()](#resjson). ```js res.end(); res.status(404).end(); ``` ### res.format() Returns: Response. Arguments: - object (Object): An object whose keys are MIME types (or extension names) mapped to handler functions, optionally with a `default` handler. Performs content-negotiation on the `Accept` HTTP header on the request object, when present. It uses [req.accepts()](/api/request/#reqaccepts) to select a handler for the request, based on the acceptable types ordered by their quality values. If the header is not specified, the first callback is invoked. When no match is found, the server responds with 406 "Not Acceptable", or invokes the `default` callback. The `Content-Type` response header is set when a callback is selected. However, you may alter this within the callback using methods such as `res.set()` or `res.type()`. The following example would respond with `{ "message": "hey" }` when the `Accept` header field is set to "application/json" or "\*/json" (however, if it is "\*/\*", then the response will be "hey"). ```js res.format({ 'text/plain'() { res.send('hey'); }, 'text/html'() { res.send('

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: ; rel="next", ; rel="last" ``` ### res.location() Returns: Response. Arguments: - path (String): The URL to set in the `Location` header. Sets the response `Location` HTTP header to the specified `path` parameter. ```js res.location('/foo/bar'); res.location('http://example.com'); ``` After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the `Location` header, without any validation. Browsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the `Location` header; and redirect the user accordingly. ### res.redirect() Arguments: - status (Number, optional): The HTTP status code to use. Defaults to `302` (Found). - path (String): The URL to redirect to. Redirects to the URL derived from the specified `path`, with specified `status`, a positive integer that corresponds to an [HTTP status code](https://www.rfc-editor.org/rfc/rfc9110#name-status-codes). If not specified, `status` defaults to `302 "Found"`. ```js res.redirect('/foo/bar'); res.redirect('http://example.com'); res.redirect(301, 'http://example.com'); res.redirect('../login'); ``` Redirects can be a fully-qualified URL for redirecting to a different site: ```js res.redirect('https://google.com'); ``` Redirects can be relative to the root of the host name. For example, if the application is on `http://example.com/admin/post/new`, the following would redirect to the URL `http://example.com/admin`: ```js res.redirect('/admin'); ``` Redirects can be relative to the current URL. For example, from `http://example.com/blog/admin/` (notice the trailing slash), the following would redirect to the URL `http://example.com/blog/admin/post/new`. ```js res.redirect('post/new'); ``` Redirecting to `post/new` from `http://example.com/blog/admin` (no trailing slash), will redirect to `http://example.com/blog/post/new`. If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense. Path-relative redirects are also possible. If you were on `http://example.com/admin/post/new`, the following would redirect to `http://example.com/admin/post`: ```js res.redirect('..'); ``` See also [Security best practices: Prevent open redirect vulnerabilities](/advanced/best-practice-security/#prevent-open-redirects). ### res.render() Arguments: - view (String): The file path of the view to render (absolute or relative to the `views` setting). - locals (Object, optional): An object whose properties define local variables for the view. - callback (Function, optional): Called as `callback(err, html)`. When provided, the rendered HTML is not sent automatically. Renders a `view` and sends the rendered HTML string to the client. Optional parameters: - `locals`, an object whose properties define local variables for the view. - `callback`, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes `next(err)` internally. The `view` argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the `views` setting. If the path does not contain a file extension, then the `view engine` setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via `require()`) and render it using the loaded module's `__express` function. For more information, see [Using template engines with Express](/guide/using-template-engines). The `view` argument performs file system operations like reading a file from disk and evaluating Node.js modules, and as so for security reasons should not contain input from the end-user. The `locals` object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations. The local variable `cache` enables view caching. Set it to `true`, to cache the view during development; view caching is enabled in production by default. ```js // send the rendered view to the client res.render('index'); // if a callback is specified, the rendered HTML string has to be sent explicitly res.render('index', (err, html) => { res.send(html); }); // pass a local variable to the view res.render('user', { name: 'Tobi' }, (err, html) => { // ... }); ``` ### res.send() Returns: Response. Arguments: - body (String | Buffer | Object | Array | Boolean, optional): The response body. Strings are sent as HTML; objects and arrays as JSON; Buffers as binary. Sends the HTTP response. The `body` parameter can be a `Buffer` object, a `String`, an object, `Boolean`, or an `Array`. For example: ```js res.send(Buffer.from('whoop')); res.send({ some: 'json' }); res.send('

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 `` for your system and app: ```sh [Unit] Description= [Service] Type=simple ExecStart=/usr/local/bin/node WorkingDirectory= User=nobody Group=nogroup Environment=NODE_ENV=production LimitNOFILE=infinity LimitCORE=infinity StandardInput=null StandardOutput=syslog StandardError=syslog Restart=always [Install] WantedBy=multi-user.target ``` For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html). ### Run your app in a cluster In a multi-core system, you can increase the performance of a Node app by many times by launching a cluster of processes. A cluster runs multiple instances of the app, ideally one instance on each CPU core, thereby distributing the load and tasks among the instances. ![Balancing between application instances using the cluster API](/images/clustering.png) IMPORTANT: Since the app instances run as separate processes, they do not share the same memory space. That is, objects are local to each instance of the app. Therefore, you cannot maintain state in the application code. However, you can use an in-memory datastore like [Redis](https://redis.io/) to store session-related data and state. This caveat applies to essentially all forms of horizontal scaling, whether clustering with multiple processes or multiple physical servers. In clustered apps, worker processes can crash individually without affecting the rest of the processes. Apart from performance advantages, failure isolation is another reason to run a cluster of app processes. Whenever a worker process crashes, always make sure to log the event and spawn a new process using cluster.fork(). #### Using Node's cluster module Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers. #### Using PM2 If you deploy your application with PM2, then you can take advantage of clustering _without_ modifying your application code. You should ensure your [application is stateless](https://pm2.keymetrics.io/docs/usage/specifics/#stateless-apps) first, meaning no local data is stored in the process (such as sessions, websocket connections and the like). When running an application with PM2, you can enable **cluster mode** to run it in a cluster with a number of instances of your choosing, such as the matching the number of available CPUs on the machine. You can manually change the number of processes in the cluster using the `pm2` command line tool without stopping the app. To enable cluster mode, start your application like so: ```bash $ pm2 start npm --name my-app -i 4 -- start $ pm2 start npm --name my-app -i max -- start ``` This can also be configured within a PM2 process file (`ecosystem.config.js` or similar) by setting `exec_mode` to `cluster` and `instances` to the number of workers to start. Once running, the application can be scaled like so: ```bash $ pm2 scale my-app +3 $ pm2 scale my-app 2 ``` For more information on clustering with PM2, see [Cluster Mode](https://pm2.keymetrics.io/docs/usage/cluster-mode/) in the PM2 documentation. ### Cache request results Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly. Use a caching server like [Varnish](https://www.varnish.org/) or [Nginx](https://blog.nginx.org/blog/nginx-caching-guide) (see also [Nginx Caching](https://serversforhackers.com/c/nginx-caching)) to greatly improve the speed and performance of your app. ### Use a load balancer No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance. A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/). ### Use a reverse proxy A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things. Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like [Nginx](https://nginx.org/) or [HAProxy](https://www.haproxy.org/) in production. --- ## Production Best Practices: Security URL: https://expressjs.com/en/advanced/best-practice-security The term _"production"_ refers to the stage in the software lifecycle when an application or API is generally available to its end-users or consumers. In contrast, in the _"development"_ stage, you're still actively writing and testing code, and the application is not open to external access. The corresponding system environments are known as _production_ and _development_ environments, respectively. Development and production environments are usually set up differently and have vastly different requirements. What's fine in development may not be acceptable in production. For example, in a development environment you may want verbose logging of errors for debugging, while the same behavior can become a security concern in a production environment. And in development, you don't need to worry about scalability, reliability, and performance, while those concerns become critical in production. If you believe you have discovered a security vulnerability in Express, please see [Security Policies and Procedures](/resources/contributing#security-policies-and-procedures). ## Don't use deprecated or vulnerable versions of Express Express 2.x and 3.x are no longer maintained. Security and performance issues in these versions won't be fixed. Do not use them! If you haven't moved to version 4, follow the [migration guide](/guide/migrating-4) or consider [Commercial Support Options](/support#commercial-support-options). Also ensure you are not using any of the vulnerable Express versions listed on the [Security updates page](/advanced/security-updates). If you are, update to one of the stable releases, preferably the latest. ## Use TLS If your app deals with or transmits sensitive data, use [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (TLS) to secure the connection and the data. This technology encrypts data before it is sent from the client to the server, thus preventing some common (and easy) hacks. Although Ajax and POST requests might not be visibly obvious and seem "hidden" in browsers, their network traffic is vulnerable to [packet sniffing](https://en.wikipedia.org/wiki/Packet_analyzer) and [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). You may be familiar with Secure Socket Layer (SSL) encryption. [TLS is simply the next progression of SSL](https://learn.microsoft.com/en-us/windows/win32/secauthn/tls-versus-ssl). In other words, if you were using SSL before, consider upgrading to TLS. In general, we recommend Nginx to handle TLS. For a good reference to configure TLS on Nginx (and other servers), see [Recommended Server Configurations (TLSRef)](https://docs.tlsref.org/server-side-tls.html#recommended-configurations). Also, a handy tool to get a free TLS certificate is [Let's Encrypt](https://letsencrypt.org/about/), a free, automated, and open certificate authority (CA) provided by the [Internet Security Research Group (ISRG)](https://www.abetterinternet.org/). ## Do not trust user input For web applications, one of the most critical security requirements is proper user input validation and handling. This comes in many forms and we will not cover all of them here. Ultimately, the responsibility for validating and correctly handling the types of user input your application accepts is yours. ### Prevent open redirects An example of potentially dangerous user input is an _open redirect_, where an application accepts a URL as user input (often in the URL query, for example `?url=https://example.com`) and uses `res.redirect` to set the `location` header and return a 3xx status. An application must validate that it supports redirecting to the incoming URL to avoid sending users to malicious links such as phishing websites, among other risks. Here is an example of checking URLs before using `res.redirect` or `res.location`: ```js app.use((req, res) => { try { if (new URL(req.query.url).host !== 'example.com') { return res.status(400).end(`Unsupported redirect to host: ${req.query.url}`); } } catch (e) { return res.status(400).end(`Invalid url: ${req.query.url}`); } res.redirect(req.query.url); }); ``` ## Use Helmet [Helmet][helmet] can help protect your app from some well-known web vulnerabilities by setting HTTP headers appropriately. Helmet is a middleware function that sets security-related HTTP response headers. Helmet sets the following headers by default: - `Content-Security-Policy`: A powerful allow-list of what can happen on your page which mitigates many attacks - `Cross-Origin-Opener-Policy`: Helps process-isolate your page - `Cross-Origin-Resource-Policy`: Blocks others from loading your resources cross-origin - `Origin-Agent-Cluster`: Changes process isolation to be origin-based - `Referrer-Policy`: Controls the [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Referer) header - `Strict-Transport-Security`: Tells browsers to prefer HTTPS - `X-Content-Type-Options`: Avoids [MIME sniffing](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types#mime_sniffing) - `X-DNS-Prefetch-Control`: Controls DNS prefetching - `X-Download-Options`: Forces downloads to be saved (Internet Explorer only) - `X-Frame-Options`: Legacy header that mitigates [Clickjacking](https://en.wikipedia.org/wiki/Clickjacking) attacks - `X-Permitted-Cross-Domain-Policies`: Controls cross-domain behavior for Adobe products, like Acrobat - `X-Powered-By`: Info about the web server. Removed because it could be used in simple attacks - `X-XSS-Protection`: Legacy header that tries to mitigate [XSS attacks](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting), but makes things worse, so Helmet disables it Each header can be configured or disabled. To read more about it please go to [its documentation website][helmet]. Install Helmet like any other module: Then to use it in your code: ```cjs title="index.cjs" // ... const helmet = require('helmet'); app.use(helmet()); // ... ``` ```mjs title="index.mjs" // ... app.use(helmet()); // ... ``` ## Reduce fingerprinting It can help to provide an extra layer of security to reduce the ability of attackers to determine the software that a server uses, known as "fingerprinting." Though not a security issue itself, reducing the ability to fingerprint an application improves its overall security posture. Server software can be fingerprinted by quirks in how it responds to specific requests, for example in the HTTP response headers. By default, Express sends the `X-Powered-By` response header that you can disable using the `app.disable()` method: ```js app.disable('x-powered-by'); ``` Disabling the `X-Powered-By header` does not prevent a sophisticated attacker from determining that an app is running Express. It may discourage a casual exploit, but there are other ways to determine an app is running Express. Express also sends its own formatted "404 Not Found" messages and formatter error response messages. These can be changed by [adding your own not found handler](/starter/faq#how-do-i-handle-404-responses) and [writing your own error handler](/guide/error-handling#writing-error-handlers): ```js // last app.use calls right before app.listen(): // custom 404 app.use((req, res, next) => { res.status(404).send("Sorry can't find that!"); }); // custom error handler app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); ``` ## Use cookies securely To ensure cookies don't open your app to exploits, don't use the default session cookie name and set cookie security options appropriately. There are two main middleware cookie session modules: - [express-session](https://www.npmjs.com/package/express-session) that replaces `express.session` middleware built-in to Express 3.x. - [cookie-session](https://www.npmjs.com/package/cookie-session) that replaces `express.cookieSession` middleware built-in to Express 3.x. The main difference between these two modules is how they save cookie session data. The [express-session](https://www.npmjs.com/package/express-session) middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment. In production, you'll need to set up a scalable session-store; see the list of [compatible session stores](https://github.com/expressjs/session#compatible-session-stores). In contrast, [cookie-session](https://www.npmjs.com/package/cookie-session) middleware implements cookie-backed storage: it serializes the entire session to the cookie, rather than just a session key. Only use it when session data is relatively small and easily encoded as primitive values (rather than objects). Although browsers are supposed to support at least 4096 bytes per cookie, to ensure you don't exceed the limit, don't exceed a size of 4093 bytes per domain. Also, be aware that the cookie data will be visible to the client, so if there is any reason to keep it secure or obscure, then `express-session` may be a better choice. ### Don't use the default session cookie name Using the default session cookie name can open your app to attacks. The security issue posed is similar to `X-Powered-By`: a potential attacker can use it to fingerprint the server and target attacks accordingly. To avoid this problem, use generic cookie names; for example using [express-session](https://www.npmjs.com/package/express-session) middleware: ```cjs title="index.cjs" const session = require('express-session'); app.set('trust proxy', 1); // trust first proxy app.use( session({ secret: 's3Cur3', name: 'sessionId', }) ); ``` ```mjs title="index.mjs" app.set('trust proxy', 1); // trust first proxy app.use( session({ secret: 's3Cur3', name: 'sessionId', }) ); ``` ### Set cookie security options Set the following cookie options to enhance security: - `secure` - Ensures the browser only sends the cookie over HTTPS. - `httpOnly` - Ensures the cookie is sent only over HTTP(S), not client JavaScript, helping to protect against cross-site scripting attacks. - `domain` - indicates the domain of the cookie; use it to compare against the domain of the server in which the URL is being requested. If they match, then check the path attribute next. - `path` - indicates the path of the cookie; use it to compare against the request path. If this and domain match, then send the cookie in the request. - `expires` - use to set expiration date for persistent cookies. Here is an example using [cookie-session](https://www.npmjs.com/package/cookie-session) middleware: ```cjs title="index.cjs" const session = require('cookie-session'); const express = require('express'); const app = express(); const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour app.use( session({ name: 'session', keys: ['key1', 'key2'], cookie: { secure: true, httpOnly: true, domain: 'example.com', path: 'foo/bar', expires: expiryDate, }, }) ); ``` ```mjs title="index.mjs" const app = express(); const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour app.use( session({ name: 'session', keys: ['key1', 'key2'], cookie: { secure: true, httpOnly: true, domain: 'example.com', path: 'foo/bar', expires: expiryDate, }, }) ); ``` ## Prevent brute-force attacks against authorization Make sure login endpoints are protected to make private data more secure. A simple and powerful technique is to block authorization attempts using two metrics: 1. The number of consecutive failed attempts by the same user name and IP address. 1. The number of failed attempts from an IP address over some long period of time. For example, block an IP address if it makes 100 failed attempts in one day. [rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) package provides tools to make this technique easy and fast. You can find [an example of brute-force protection in the documentation](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection) ## Ensure your dependencies are secure Using npm to manage your application's dependencies is powerful and convenient. But the packages that you use may contain critical security vulnerabilities that could also affect your application. The security of your app is only as strong as the "weakest link" in your dependencies. Since npm@6, npm automatically reviews every install request. Also, you can use `npm audit` to analyze your dependency tree. ```bash $ npm audit ``` If you want to stay more secure, consider [Snyk](https://snyk.io/). Snyk offers both a [command-line tool](https://www.npmjs.com/package/snyk) and a [GitHub integration](https://docs.snyk.io/discover-snyk/getting-started) that checks your application against [Snyk's open source vulnerability database](https://security.snyk.io/) for any known vulnerabilities in your dependencies. Install the CLI as follows: ```bash $ npm install -g snyk $ cd your-app ``` Use this command to test your application for vulnerabilities: ```bash $ snyk test ``` ### Avoid other known vulnerabilities Keep an eye out for [GitHub Advisory Database](https://github.com/advisories?query=ecosystem%3Anpm) or [Snyk](https://security.snyk.io/vuln/npm) advisories that may affect Express or other modules that your app uses. In general, these databases are excellent resources for knowledge and tools about Node security. Finally, Express apps—like any other web apps—can be vulnerable to a variety of web-based attacks. Familiarize yourself with known [web vulnerabilities](https://owasp.org/www-project-top-ten/) and take precautions to avoid them. ## Additional considerations Here are some further recommendations from the excellent [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/). Refer to that blog post for all the details on these recommendations: - Always filter and sanitize user input to protect against cross-site scripting (XSS) and command injection attacks. - Defend against SQL injection attacks by using parameterized queries or prepared statements. - Use the open-source [sqlmap](https://sqlmap.org/) tool to detect SQL injection vulnerabilities in your app. - Use the [nmap](https://nmap.org/) and [sslyze](https://github.com/nabla-c0d3/sslyze) tools to test the configuration of your SSL ciphers, keys, and renegotiation as well as the validity of your certificate. - Use [safe-regex](https://www.npmjs.com/package/safe-regex) to ensure your regular expressions are not susceptible to [regular expression denial of service](https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS) attacks. [helmet]: https://helmet.js.org/ --- ## Health Checks and Graceful Shutdown URL: https://expressjs.com/en/advanced/healthcheck-graceful-shutdown ## Graceful shutdown When you deploy a new version of your application, you must replace the previous version. The process manager you're using will first send a SIGTERM signal to the application to notify it that it will be killed. Once the application gets this signal, it should stop accepting new requests, finish all the ongoing requests, clean up the resources it used, including database connections and file locks then exit. ### Example ```js const server = app.listen(port); process.on('SIGTERM', () => { debug('SIGTERM signal received: closing HTTP server'); server.close(() => { debug('HTTP server closed'); }); }); ``` ## Health checks A load balancer uses health checks to determine if an application instance is healthy and can accept requests. For example, [Kubernetes has two health checks](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes//): - `liveness`, that determines when to restart a container. - `readiness`, that determines when a container is ready to start accepting traffic. When a pod is not ready, it is removed from the service load balancers. --- ## Security updates URL: https://expressjs.com/en/advanced/security-updates Node.js vulnerabilities directly affect Express. Therefore, [keep a watch on Node.js vulnerabilities](https://nodejs.org/en/blog/vulnerability/) and make sure you are using the latest stable version of Node.js. The list below enumerates the Express vulnerabilities that were fixed in the specified version update. If you believe you have discovered a security vulnerability in Express, please see [Security Policies and Procedures](/resources/contributing#security-policies-and-procedures). ## 4.x - 4.21.2 - The dependency `path-to-regexp` has been updated to address a [vulnerability](https://github.com/pillarjs/path-to-regexp/security/advisories/GHSA-rhx6-c78j-4q9w). - 4.21.1 - The dependency `cookie` has been updated to address a [vulnerability](https://github.com/jshttp/cookie/security/advisories/GHSA-pxg6-pf52-xh8x), This may affect your application if you use `res.cookie`. - 4.20.0 - Fixed XSS vulnerability in `res.redirect` ([advisory](https://github.com/expressjs/express/security/advisories/GHSA-qw6h-vgh9-j6wx), [CVE-2024-43796](https://www.cve.org/CVERecord?id=CVE-2024-43796)). - The dependency `serve-static` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-cm22-4g7w-348p). - The dependency `send` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-m6fv-jmcg-4jfg). - The dependency `path-to-regexp` has been updated to address a [vulnerability](https://github.com/pillarjs/path-to-regexp/security/advisories/GHSA-9wv6-86v2-598j). - The dependency `body-parser` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-qwcr-r2fm-qrc7), This may affect your application if you had url encoding activated. - 4.19.0, 4.19.1 - Fixed open redirect vulnerability in `res.location` and `res.redirect` ([advisory](https://github.com/expressjs/express/security/advisories/GHSA-rv95-896h-c2vc), [CVE-2024-29041](https://www.cve.org/CVERecord?id=CVE-2024-29041)). - 4.17.3 - The dependency `qs` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-hrpp-h998-j3pp). This may affect your application if the following APIs are used: `req.query`, `req.body`, `req.param`. - 4.16.0 - The dependency `forwarded` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-mpcf-4gmh-23w8). This may affect your application if the following APIs are used: `req.host`, `req.hostname`, `req.ip`, `req.ips`, `req.protocol`. - The dependency `mime` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-wrvr-8mpx-r7pp), but this issue does not impact Express. - The dependency `send` has been updated to provide a protection against a [Node.js 8.5.0 vulnerability](https://nodejs.org/en/blog/vulnerability/september-2017-path-validation/). This only impacts running Express on the specific Node.js version 8.5.0. - 4.15.5 - The dependency `debug` has been updated to address a [vulnerability](https://security.snyk.io/vuln/npm:debug:20170905), but this issue does not impact Express. - The dependency `fresh` has been updated to address a [vulnerability](https://github.com/advisories/GHSA-9qj9-36jm-prpv). This will affect your application if the following APIs are used: `express.static`, `req.fresh`, `res.json`, `res.jsonp`, `res.send`, `res.sendfile` `res.sendFile`, `res.sendStatus`. - 4.15.3 - The dependency `ms` has been updated to address a [vulnerability](https://security.snyk.io/vuln/npm:ms:20170412). This may affect your application if untrusted string input is passed to the `maxAge` option in the following APIs: `express.static`, `res.sendfile`, and `res.sendFile`. - 4.15.2 - The dependency `qs` has been updated to address a [vulnerability](https://security.snyk.io/vuln/npm:qs:20170213), but this issue does not impact Express. Updating to 4.15.2 is a good practice, but not required to address the vulnerability. - 4.11.1 - Fixed root path disclosure vulnerability in `express.static`, `res.sendfile`, and `res.sendFile` - 4.10.7 - Fixed open redirect vulnerability in `express.static` ([advisory](https://github.com/advisories/GHSA-c3x7-gjmx-r2ff), [CVE-2015-1164](https://www.cve.org/CVERecord?id=CVE-2015-1164)). - 4.8.8 - Fixed directory traversal vulnerabilities in `express.static` ([advisory](https://github.com/advisories/GHSA-xwg4-93c6-3h42) , [CVE-2014-6394](https://www.cve.org/CVERecord?id=CVE-2014-6394)). - 4.8.4 - Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness. - 4.8.0 - Sparse arrays that have extremely high indexes in the query string could cause the process to run out of memory and crash the server. - Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily. ## 3.x **Express 3.x IS END-OF-LIFE AND NO LONGER MAINTAINED** Known and unknown security and performance issues in 3.x have not been addressed since the last update (1 August, 2015). It is highly recommended to use the latest version of Express. If you are unable to upgrade past 3.x, please consider [Commercial Support Options](/support#commercial-support-options). - 3.19.1 - Fixed root path disclosure vulnerability in `express.static`, `res.sendfile`, and `res.sendFile` - 3.19.0 - Fixed open redirect vulnerability in `express.static` ([advisory](https://github.com/advisories/GHSA-c3x7-gjmx-r2ff), [CVE-2015-1164](https://www.cve.org/CVERecord?id=CVE-2015-1164)). - 3.16.10 - Fixed directory traversal vulnerabilities in `express.static`. - 3.16.6 - Node.js 0.10 can leak `fd`s in certain situations that affect `express.static` and `res.sendfile`. Malicious requests could cause `fd`s to leak and eventually lead to `EMFILE` errors and server unresponsiveness. - 3.16.0 - Sparse arrays that have extremely high indexes in query string could cause the process to run out of memory and crash the server. - Extremely nested query string objects could cause the process to block and make the server unresponsive temporarily. - 3.3.0 - The 404 response of an unsupported method override attempt was susceptible to cross-site scripting attacks. --- ## Database integration URL: https://expressjs.com/en/guide/database-integration To connect a database to an Express app simply load the desired Node.js driver or ORM in your app. The general pattern is shown below using SQLite as an example. There are also a few [best practices](#best-practices) to follow, regardless of the database you're using. ## SQLite Node.js includes a built-in SQLite client, [node:sqlite](https://nodejs.org/api/sqlite.html), available without a flag since Node.js 22.13.0. No installation is required. For older Node.js versions, [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) offers a similar synchronous API. ### Example This example creates a sample user that you can retrieve at `http://localhost:3000/users/1`. It uses a synchronous SQLite API for simplicity: long-running queries block the thread handling requests. For workloads with long-running queries, consider moving database work to a worker thread or using an asynchronous database driver. ```cjs title="index.cjs" const express = require('express'); const { DatabaseSync } = require('node:sqlite'); const app = express(); const db = new DatabaseSync('app.db'); db.exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'); db.prepare('INSERT INTO users (id, name) VALUES (?, ?) ON CONFLICT(id) DO NOTHING').run(1, 'Alice'); const findUser = db.prepare('SELECT id, name FROM users WHERE id = ?'); app.get('/users/:id', (req, res) => { const user = findUser.get(req.params.id); if (!user) { return res.status(404).json({ error: 'User not found' }); } res.json(user); }); app.listen(3000); ``` ```mjs title="index.mjs" const app = express(); const db = new DatabaseSync('app.db'); db.exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'); db.prepare('INSERT INTO users (id, name) VALUES (?, ?) ON CONFLICT(id) DO NOTHING').run(1, 'Alice'); const findUser = db.prepare('SELECT id, name FROM users WHERE id = ?'); app.get('/users/:id', (req, res) => { const user = findUser.get(req.params.id); if (!user) { return res.status(404).json({ error: 'User not found' }); } res.json(user); }); app.listen(3000); ``` ```ts title="index.ts" interface User { id: number; name: string; } const app = express(); const db = new DatabaseSync('app.db'); db.exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'); db.prepare('INSERT INTO users (id, name) VALUES (?, ?) ON CONFLICT(id) DO NOTHING').run(1, 'Alice'); const findUser = db.prepare('SELECT id, name FROM users WHERE id = ?'); app.get('/users/:id', (req, res) => { const user = findUser.get(req.params.id) as User | undefined; if (!user) { return res.status(404).json({ error: 'User not found' }); } res.json(user); }); app.listen(3000); ``` ## Other databases Every other database follows the same pattern: install the Node.js driver from npm, create a client or connection pool once when the app starts, and use it in your route handlers. Refer to the official documentation of each driver for connection options and API details: - PostgreSQL: [pg](https://node-postgres.com/) or [postgres](https://github.com/porsager/postgres) - MySQL and MariaDB: [mysql2](https://sidorares.github.io/node-mysql2/docs) or [mariadb](https://mariadb.com/docs/connectors/mariadb-connector-nodejs) - MongoDB: [mongodb](https://www.mongodb.com/docs/drivers/node/current/) - Redis: [redis](https://redis.io/docs/latest/develop/clients/nodejs/) or [ioredis](https://github.com/redis/ioredis) - SQL Server: [mssql](https://github.com/tediousjs/node-mssql) - Oracle: [oracledb](https://www.npmjs.com/package/oracledb) - Cassandra: [cassandra-driver](https://docs.datastax.com/en/developer/nodejs-driver/latest/) - Elasticsearch: [@elastic/elasticsearch](https://www.elastic.co/docs/reference/elasticsearch/clients/javascript) For any database not listed here, search for its driver on the [npm](https://www.npmjs.com/) site. ## ORMs and query builders The example above uses a database driver directly, which is a good fit for small apps and for learning how things work. As an application grows, an ORM (object-relational mapper) or a query builder can take over concerns such as schema definitions, migrations, relations between tables, and input mapping, while reducing boilerplate. Many of them also provide type safety when used with TypeScript. Popular options in the Node.js ecosystem include: - [Prisma](https://www.prisma.io/): a type-safe ORM with a schema-first workflow and built-in migrations. Supports PostgreSQL, MySQL, SQLite, SQL Server, MongoDB, and CockroachDB. - [Drizzle ORM](https://orm.drizzle.team/): a lightweight, TypeScript-first ORM with a SQL-like query API and a migrations toolkit. - [Sequelize](https://sequelize.org/): a mature, promise-based ORM for PostgreSQL, MySQL, MariaDB, SQLite, and SQL Server. - [TypeORM](https://typeorm.io/): an ORM built around decorators and entities, supporting many SQL databases and MongoDB. - [Mongoose](https://mongoosejs.com/): an ODM (object document mapper) for MongoDB. - [Knex.js](https://knexjs.org/): a flexible SQL query builder with migrations support, useful when you want control over your queries without writing raw strings. - [Kysely](https://kysely.dev/): a type-safe SQL query builder for TypeScript. Each ORM has its own API, supported databases, and approach to schemas, migrations, and queries. Features and setup requirements vary, so consult each project's documentation before choosing one. Query builders keep you close to SQL, while full ORMs abstract more of it away. Pick the level of abstraction that matches your team and project, and prefer tools that are actively maintained. ## Best practices Adapt these practices to the database and library you choose. The snippets below illustrate separate parts of an application. The PostgreSQL snippets assume you have installed the [pg](https://node-postgres.com/) driver and created a shared pool: ```js const pool = new Pool({ connectionString: process.env.DATABASE_URL }); ``` ### Create connections once and reuse them Opening a database connection is expensive. Many drivers provide a connection pool that creates connections as needed and reuses them across requests. Create the pool (or client) once when the app starts. Acquire connections from that shared pool as needed in your route handlers, for example for a transaction, and always release them in a `finally` block. For individual queries, `pool.query()` in `pg` handles acquiring and releasing a connection for you. ### Use parameterized queries Never build SQL queries by concatenating or interpolating user input into the query string. Doing so exposes your app to SQL injection. Use your driver's parameterized queries or prepared statements to pass user input separately from the query itself. ```js // Vulnerable: user input becomes part of the query const user = await pool.query(`SELECT * FROM users WHERE id = ${req.params.id}`); ``` ```js // Safe: user input is passed as a parameter const user = await pool.query('SELECT * FROM users WHERE id = $1', [req.params.id]); ``` Also validate user input before it reaches your queries, both for security and for data integrity. For NoSQL databases, construct queries using the driver's API and validate the types, fields, and operators you accept. Do not pass user-supplied query objects directly to the database. ### Keep credentials out of your code Never hardcode connection strings, usernames, or passwords in your source code, and never commit them to version control. Read them from environment variables or a secrets manager instead: ```js const pool = new Pool({ connectionString: process.env.DATABASE_URL }); ``` During development, you can keep these values in a `.env` file and load it with Node.js's built-in support for environment files, with no extra dependencies: ```bash node --env-file=.env index.js ``` Make sure `.env` is listed in your `.gitignore` file so it never gets committed. ### Handle database errors Database calls fail: connections drop, queries time out, constraints are violated. In Express 5, errors thrown in async route handlers are passed to your [error-handling middleware](/en/guide/error-handling) automatically, so define one and decide there what to expose to clients. Avoid leaking internal error details, such as query text or stack traces, in API responses. ### Cancel work when the client disconnects Since Node.js 24.20.0, every request exposes [req.signal](https://nodejs.org/api/http.html#messagesignal), an `AbortSignal` that is aborted when the client disconnects. Pass it to any cancellation-aware API, such as a database driver that supports abort signals, so your app stops doing work nobody is waiting for: ```js app.get('/reports', async (req, res) => { const report = await generateReport({ signal: req.signal }); res.json(report); }); ``` ### Close connections on shutdown When your app receives a termination signal, stop accepting new requests and close your database connections so in-flight queries can finish cleanly: ```js const server = app.listen(3000); process.on('SIGTERM', () => { server.close(async () => { await pool.end(); process.exit(0); }); }); ``` If you already use an [AbortSignal](https://nodejs.org/api/globals.html#class-abortsignal) to coordinate cancellation across your app, you can pass it to `app.listen` and abort it instead of calling `server.close()` directly. --- ## Moving to Express 4 URL: https://expressjs.com/en/guide/migrating-4 Express 4 is a breaking change from Express 3. That means an existing Express 3 app will _not_ work if you update the Express version in its dependencies. This article covers: - [Changes in Express 4](#changes-in-express-4). - [An example](#example-app-migration) of migrating an Express 3 app to Express 4. - [Upgrading to the Express 4 app generator](#upgrading-to-the-express-4-app-generator). ## Changes in Express 4 There are several significant changes in Express 4: - [Changes to Express core and middleware system.](#changes-to-express-core-and-middleware-system) The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself. - [Changes to the routing system.](#the-routing-system) - [Various other changes.](#other-changes) See also: - [New features in 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x) - [Migrating from 3.x to 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) ### Changes to Express core and middleware system Express 4 no longer depends on Connect, and removes all built-in middleware from its core, except for the `express.static` function. This means that Express is now an independent routing and middleware web framework, and Express versioning and releases are not affected by middleware updates. Without built-in middleware, you must explicitly add all the middleware that is required to run your app. Simply follow these steps: 1. Install the module: `npm install --save ` 2. In your app, require the module: `require('module-name')` 3. Use the module according to its documentation: `app.use( ... )` The following table lists Express 3 middleware and their counterparts in Express 4. | Express 3 | Express 4 | | ------------------------ | ------------------------------------------------------------------------------------------------------- | | `express.bodyParser` | [body-parser](https://github.com/expressjs/body-parser) + [multer](https://github.com/expressjs/multer) | | `express.compress` | [compression](https://github.com/expressjs/compression) | | `express.cookieSession` | [cookie-session](https://github.com/expressjs/cookie-session) | | `express.cookieParser` | [cookie-parser](https://github.com/expressjs/cookie-parser) | | `express.logger` | [morgan](https://github.com/expressjs/morgan) | | `express.session` | [express-session](https://github.com/expressjs/session) | | `express.favicon` | [serve-favicon](https://github.com/expressjs/serve-favicon) | | `express.responseTime` | [response-time](https://github.com/expressjs/response-time) | | `express.errorHandler` | [errorhandler](https://github.com/expressjs/errorhandler) | | `express.methodOverride` | [method-override](https://github.com/expressjs/method-override) | | `express.timeout` | [connect-timeout](https://github.com/expressjs/timeout) | | `express.vhost` | [vhost](https://github.com/expressjs/vhost) | | `express.csrf` | [csurf](https://github.com/expressjs/csurf) | | `express.directory` | [serve-index](https://github.com/expressjs/serve-index) | | `express.static` | [serve-static](https://github.com/expressjs/serve-static) | Here is the [complete list](https://github.com/senchalabs/connect#middleware) of Express 4 middleware. In most cases, you can simply replace the old version 3 middleware with its Express 4 counterpart. For details, see the module documentation in GitHub. #### `app.use` accepts parameters In version 4 you can use a variable parameter to define the path where middleware functions are loaded, then read the value of the parameter from the route handler. For example: ```js app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id); next(); }); ``` ### The routing system Apps now implicitly load routing middleware, so you no longer have to worry about the order in which middleware is loaded with respect to the `router` middleware. The way you define routes is unchanged, but the routing system has two new features to help organize your routes: - A new method, `app.route()`, to create chainable route handlers for a route path. - A new class, `express.Router`, to create modular mountable route handlers. #### `app.route()` method The new `app.route()` method enables you to create chainable route handlers for a route path. Because the path is specified in a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see [`Router()` documentation](/4x/api/router/). Here is an example of chained route handlers that are defined by using the `app.route()` function. ```js app .route('/book') .get((req, res) => { res.send('Get a random book'); }) .post((req, res) => { res.send('Add a book'); }) .put((req, res) => { res.send('Update the book'); }); ``` #### `express.Router` class The other feature that helps to organize routes is a new class, `express.Router`, that you can use to create modular mountable route handlers. A `Router` instance is a complete middleware and routing system; for this reason it is often referred to as a "mini-app". The following example creates a router as a module, loads middleware in it, defines some routes, and mounts it on a path on the main app. For example, create a router file named `birds.js` in the app directory, with the following content: ```cjs title="birds.cjs" var express = require('express'); var router = express.Router(); // middleware specific to this router router.use((req, res, next) => { console.log('Time: ', Date.now()); next(); }); // define the home page route router.get('/', (req, res) => { res.send('Birds home page'); }); // define the about route router.get('/about', (req, res) => { res.send('About birds'); }); module.exports = router; ``` ```mjs title="birds.mjs" const router = express.Router(); // middleware specific to this router router.use((req, res, next) => { console.log('Time: ', Date.now()); next(); }); // define the home page route router.get('/', (req, res) => { res.send('Birds home page'); }); // define the about route router.get('/about', (req, res) => { res.send('About birds'); }); export default router; ``` Then, load the router module in the app: ```cjs title="index.cjs" var birds = require('./birds'); // ... app.use('/birds', birds); ``` ```mjs title="index.mjs" // ... app.use('/birds', birds); ``` The app will now be able to handle requests to the `/birds` and `/birds/about` paths, and will call the `timeLog` middleware that is specific to the route. ### Other changes The following table lists other small but important changes in Express 4: | Object | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Node.js | Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. | | `http.createServer()` | The `http` module is no longer needed, unless you need to directly work with it (socket.io/SPDY/HTTPS). The app can be started by using the `app.listen()` function. | | `app.configure()` | The `app.configure()` function has been removed. Use the `process.env.NODE_ENV` or `app.get('env')` function to detect the environment and configure the app accordingly. | | `json spaces` | The `json spaces` application property is disabled by default in Express 4. | | `req.accepted()` | Use `req.accepts()`, `req.acceptsEncodings()`, `req.acceptsCharsets()`, and `req.acceptsLanguages()`. | | `res.location()` | No longer resolves relative URLs. | | `req.params` | Was an array; now an object. | | `res.locals` | Was a function; now an object. | | `res.headerSent` | Changed to `res.headersSent`. | | `app.route` | Now available as `app.mountpath`. | | `res.on('header')` | Removed. | | `res.charset` | Removed. | | `res.setHeader('Set-Cookie', val)` | Functionality is now limited to setting the basic cookie value. Use `res.cookie()` for added functionality. | ## Example app migration Here is an example of migrating an Express 3 application to Express 4. The files of interest are `app.js` and `package.json`. ### Version 3 app #### `app.js` Consider an Express v.3 application with the following `app.js` file: ```cjs title="index.cjs" var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.methodOverride()); app.use(express.session({ secret: 'your secret here' })); app.use(express.bodyParser()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if (app.get('env') === 'development') { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')); }); ``` ```mjs title="index.mjs" const app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.methodOverride()); app.use(express.session({ secret: 'your secret here' })); app.use(express.bodyParser()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if (app.get('env') === 'development') { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')); }); ``` #### `package.json` The accompanying version 3 `package.json` file might look something like this: ```json { "name": "application-name", "version": "0.0.1", "private": true, "scripts": { "start": "node app.js" }, "dependencies": { "express": "3.12.0", "pug": "*" } } ``` ### Process Begin the migration process by installing the required middleware for the Express 4 app and updating Express and Pug to their respective latest version with the following command: Make the following changes to `app.js`: 1. The built-in Express middleware functions `express.favicon`, `express.logger`, `express.methodOverride`, `express.session`, `express.bodyParser` and `express.errorHandler` are no longer available on the `express` object. You must install their alternatives manually and load them in the app. 2. You no longer need to load the `app.router` function. It is not a valid Express 4 app object, so remove the `app.use(app.router);` code. 3. Make sure that the middleware functions are loaded in the correct order - load `errorHandler` after loading the app routes. ### Version 4 app #### `package.json` Running the above `npm` command will update `package.json` as follows: ```json { "name": "application-name", "version": "0.0.1", "private": true, "scripts": { "start": "node app.js" }, "dependencies": { "body-parser": "^1.5.2", "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", "serve-favicon": "^2.0.1" } } ``` #### `app.js` Then, remove invalid code, load the required middleware, and make other changes as necessary. The `app.js` file will look like this: ```cjs title="index.cjs" var http = require('http'); var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var methodOverride = require('method-override'); var session = require('express-session'); var bodyParser = require('body-parser'); var multer = require('multer'); var errorHandler = require('errorhandler'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(favicon(path.join(__dirname, '/public/favicon.ico'))); app.use(logger('dev')); app.use(methodOverride()); app.use( session({ resave: true, saveUninitialized: true, secret: 'uwotm8', }) ); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(multer()); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', routes.index); app.get('/users', user.list); // error handling middleware should be loaded after the loading the routes if (app.get('env') === 'development') { app.use(errorHandler()); } var server = http.createServer(app); server.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')); }); ``` ```mjs title="index.mjs" const app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(favicon(path.join(__dirname, '/public/favicon.ico'))); app.use(logger('dev')); app.use(methodOverride()); app.use( session({ resave: true, saveUninitialized: true, secret: 'uwotm8', }) ); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(multer()); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', routes.index); app.get('/users', user.list); // error handling middleware should be loaded after the loading the routes if (app.get('env') === 'development') { app.use(errorHandler()); } const server = http.createServer(app); server.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')); }); ``` Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way: ```js app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')); }); ``` ### Run the app The migration process is complete, and the app is now an Express 4 app. To confirm, start the app by using the following command: ```bash $ node . ``` Load [http://localhost:3000](http://localhost:3000) and see the home page being rendered by Express 4. ## Upgrading to the Express 4 app generator The command-line tool to generate an Express app is still `express`, but to upgrade to the new version, you must uninstall the Express 3 app generator and then install the new `express-generator`. ### Installing If you already have the Express 3 app generator installed on your system, you must uninstall it: Depending on how your file and directory privileges are configured, you might need to run this command with `sudo`. Now install the new generator: Depending on how your file and directory privileges are configured, you might need to run this command with `sudo`. Now the `express` command on your system is updated to the Express 4 generator. ### Changes to the app generator Command options and use largely remain the same, with the following exceptions: - Removed the `--sessions` option. - Removed the `--jshtml` option. - Added the `--hogan` option to support [Hogan.js](https://twitter.github.io/hogan.js/). ### Example Execute the following command to create an Express 4 app: ```bash $ express app4 ``` If you look at the contents of the `app4/app.js` file, you will notice that all the middleware functions (except `express.static`) that are required for the app are loaded as independent modules, and the `router` middleware is no longer explicitly loaded in the app. You will also notice that the `app.js` file is now a Node.js module, in contrast to the standalone app that was generated by the old generator. After installing the dependencies, start the app by using the following command: ```bash $ npm start ``` If you look at the `npm start` script in the `package.json` file, you will notice that the actual command that starts the app is `node ./bin/www`, which used to be `node app.js` in Express 3. Because the `app.js` file that was generated by the Express 4 generator is now a Node.js module, it can no longer be started independently as an app (unless you modify the code). The module must be loaded in a Node.js file and started via the Node.js file. The Node.js file is `./bin/www` in this case. Neither the `bin` directory nor the extensionless `www` file is mandatory for creating an Express app or starting the app. They are just suggestions made by the generator, so feel free to modify them to suit your needs. To get rid of the `www` directory and keep things the "Express 3 way", delete the line that says `module.exports = app;` at the end of the `app.js` file, then paste the following code in its place: ```js app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port); }); ``` Ensure that you load the `debug` module at the top of the `app.js` file by using the following code: ```js var debug = require('debug')('app4'); ``` Next, change `"start": "node ./bin/www"` in the `package.json` file to `"start": "node app.js"`. You have now moved the functionality of `./bin/www` back to `app.js`. This change is not recommended, but the exercise helps you to understand how the `./bin/www` file works, and why the `app.js` file no longer starts on its own. --- ## Upgrade to Express v5 URL: https://expressjs.com/en/guide/migrating-5 Express 5 is not very different from Express 4; although it maintains the same basic API, there are still changes that break compatibility with the previous version. Therefore, an application built with Express 4 might not work if you update it to use Express 5. ## Installation To install this version, you need to have a **Node.js version 18 or higher**. Then, execute the following command in your application directory: You can then run your automated tests to see what fails, and fix problems according to the updates listed below. After addressing test failures, run your app to see what errors occur. You'll find out right away if the app uses any methods or properties that are not supported. ## Express 5 Codemods To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. Run the following command for run all the codemods available: If you want to run a specific codemod, you can run the following command: You can find the list of available codemods [here](https://codemod.link/express). ## Removed methods and properties If you use any of these methods or properties in your app, it will crash. So, you'll need to change your app after you update to version 5. ### app.del() Express 5 no longer supports the `app.del()` function. If you use this function, an error is thrown. For registering HTTP DELETE routes, use the `app.delete()` function instead. Initially, `del` was used instead of `delete`, because `delete` is a reserved keyword in JavaScript. However, as of ECMAScript 6, `delete` and other reserved keywords can legally be used as property names. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff -app.del('/user/:id', (req, res) => { +app.delete('/user/:id', (req, res) => { res.send(`DELETE /user/${req.params.id}`); }); ``` ### app.param(fn) The `app.param(fn)` signature was used for modifying the behavior of the `app.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all. ### Pluralized method names The following method names have been pluralized. In Express 4, using the old methods resulted in a deprecation warning. Express 5 no longer supports them at all: `req.acceptsCharset()` is replaced by `req.acceptsCharsets()`. `req.acceptsEncoding()` is replaced by `req.acceptsEncodings()`. `req.acceptsLanguage()` is replaced by `req.acceptsLanguages()`. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.all('/', (req, res) => { - req.acceptsCharset('utf-8'); - req.acceptsEncoding('br'); - req.acceptsLanguage('en'); + req.acceptsCharsets('utf-8'); + req.acceptsEncodings('br'); + req.acceptsLanguages('en'); // ... }); ``` ### Leading colon (:) in the name for app.param(name, fn) A leading colon character (:) in the name for the `app.param(name, fn)` function is a remnant of Express 3, and for the sake of backwards compatibility, Express 4 supported it with a deprecation notice. Express 5 will silently ignore it and use the name parameter without prefixing it with a colon. This should not affect your code if you follow the Express 4 documentation of [app.param](/4x/api/application/#appparam), as it makes no mention of the leading colon. ### req.param(name) This potentially confusing and dangerous method of retrieving form data has been removed. You will now need to specifically look for the submitted parameter name in the `req.params`, `req.body`, or `req.query` object. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.post('/user', (req, res) => { - const id = req.param('id'); - const body = req.param('body'); - const query = req.param('query'); + const id = req.params.id; + const body = req.body; + const query = req.query; // ... }); ``` ### res.json(obj, status) Express 5 no longer supports the signature `res.json(obj, status)`. Instead, set the status and then chain it to the `res.json()` method like this: `res.status(status).json(obj)`. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.post('/user', (req, res) => { - res.json({ name: 'Ruben' }, 201); + res.status(201).json({ name: 'Ruben' }); }); ``` ### res.jsonp(obj, status) Express 5 no longer supports the signature `res.jsonp(obj, status)`. Instead, set the status and then chain it to the `res.jsonp()` method like this: `res.status(status).jsonp(obj)`. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.post('/user', (req, res) => { - res.jsonp({ name: 'Ruben' }, 201); + res.status(201).jsonp({ name: 'Ruben' }); }); ``` ### res.redirect(url, status) Express 5 no longer supports the signature `res.redirect(url, status)`. Instead, use the following signature: `res.redirect(status, url)`. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.get('/user', (req, res) => { - res.redirect('/users', 302); + res.redirect(302, '/users'); }); // A redirect that relies on the default 302 status is unaffected app.get('/admin', (req, res) => { res.redirect('/dashboard'); }); ``` ### res.redirect('back') and res.location('back') Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the `res.redirect('back')` and `res.location('back')` methods were deprecated. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.get('/user', (req, res) => { - res.redirect('back'); + res.redirect(req.get('Referrer') || '/'); }); ``` ### res.send(body, status) Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.get('/user', (req, res) => { - res.send({ name: 'Ruben' }, 200); + res.status(200).send({ name: 'Ruben' }); }); ``` ### res.send(status) Express 5 no longer supports the signature `res.send(status)`, where `status` is a number. Instead, use the `res.sendStatus(statusCode)` function, which sets the HTTP response header status code and sends the text version of the code: "Not Found", "Internal Server Error", and so on. If you need to send a number by using the `res.send()` function, quote the number to convert it to a string, so that Express does not interpret it as an attempt to use the unsupported old signature. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.get('/user', (req, res) => { - res.send(200); + res.sendStatus(200); }); ``` ### res.sendfile() The `res.sendfile()` function has been replaced by a camel-cased version `res.sendFile()` in Express 5. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.get('/user', (req, res) => { - res.sendfile('/path/to/file'); + res.sendFile('/path/to/file'); }); ``` ### res.sendFile() options The `hidden` and `from` options for `res.sendFile()` are no longer supported. Use `dotfiles` and `root` instead. The `dotfiles` option applies to hidden directories in the path as well as hidden files. For example, a file served from an absolute path like `/var/www/app/.cache/index.html` now requires `dotfiles: 'allow'`, even though `index.html` is not a dotfile. In Express 4 a hidden directory in the path was served by default; Express 5 returns `404` unless you opt in. This check only applies to the part of the path that `send` evaluates. When you pass a `root`, only the portion relative to `root` is checked, so a hidden directory inside `root` is unaffected. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff app.get('/files/:name', (req, res) => { - res.sendFile(req.params.name, { hidden: true, from: '/uploads' }); + res.sendFile(req.params.name, { dotfiles: 'allow', root: '/uploads' }); }); ``` If you serve an absolute path that contains a hidden directory, opt in with `dotfiles: 'allow'` or use `root` so the hidden segment is not part of the evaluated path: ```diff app.get('/build', (req, res) => { - res.sendFile('/var/www/app/.cache/index.html'); + res.sendFile('/var/www/app/.cache/index.html', { dotfiles: 'allow' }); + // or: res.sendFile('index.html', { root: '/var/www/app/.cache' }); }); ``` ### express.static() options The `hidden` and `from` options for `express.static()` are no longer supported. Use `dotfiles` and `root` instead. Note that `from` was never documented in the API but was accepted as an alias for `root`. The default value of `dotfiles` is now `"ignore"`. The `dotfiles` check now also applies to hidden **directories** in the request path, not just hidden files. A request like `GET /.well-known/acme-challenge/...` that was served by default in Express 4 now returns `404` unless you set `dotfiles: 'allow'`. This only affects the part of the path relative to the configured `root`; a hidden directory in `root` itself is unaffected. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff const express = require('express'); const app = express(); -app.use(express.static('public', { hidden: true })); +app.use(express.static('public', { dotfiles: 'allow' })); ``` If you rely on serving a hidden directory such as `.well-known` (for example, ACME/Let's Encrypt challenges), opt in explicitly. This is needed even if you never used the `hidden` option: ```diff -app.use(express.static('public')); +app.use(express.static('public', { dotfiles: 'allow' })); ``` ### router.param(fn) The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all. ### express.static.mime In Express 5, `mime` is no longer an exported property of the `static` field. Use the [`mime-types` package](https://github.com/jshttp/mime-types) to work with MIME type values. #### How to update You can automatically update your code by running the following command: Or you can update your code manually: ```diff -express.static.mime.lookup('json'); +const mime = require('mime-types'); +mime.lookup('json'); ``` ### MIME type changes Several MIME types have changed due to updates in [`mime-db`](https://github.com/jshttp/mime-db). These changes only affect `express.static()` and `res.sendFile()`. For a full list of changes, see the [`mime-db` changelog](https://github.com/jshttp/mime-db/blob/HEAD/HISTORY.md). Express 4 uses `mime-db` version **1.52.0**, while Express 5 uses newer versions that reflect updates to IANA and other MIME type specifications. The most notable change is that JavaScript files (`.js`) are now served as `text/javascript` instead of `application/javascript`. In Express 5, changes to MIME types from `mime-db` updates are not considered breaking changes, so be careful when updating your dependencies as MIME types may change between minor or patch versions. ### express:router debug logs Router handling logic is now performed by a separate dependency ([`router`](https://github.com/pillarjs/router)) maintained by the Express team, so debug logs have moved to a different namespace. Before Express 5.1, these debug logs did not exist. To get them, update to a recent Express 5 version or update the `router` package in your `package-lock.json`: | v4 | v5 | | -------------------------- | ----------------------------------- | | `express:router` | `router` | | `express:router:layer` | `router:layer` | | `express:router:route` | `router:route` | | `express:*` (includes all) | `express:*` + `router` + `router:*` | #### How to update ```diff -DEBUG=express:* node index.js +DEBUG=express:*,router,router:* node index.js ``` ## Changed These APIs still exist but their behavior has changed. Review these changes to make sure your app works as expected. ### Path route matching syntax Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: - The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` ```diff -app.get('/*', async (req, res) => { +app.get('/*splat', async (req, res) => { res.send('ok'); }); ``` `*splat` matches any path without the root path. If you need to match the root path as well `/`, you can use `/{*splat}`, wrapping the wildcard in braces. ```js app.get('/{*splat}', async (req, res) => { res.send('ok'); }); ``` - The optional character `?` is no longer supported, use braces instead. ```diff -app.get('/:file.:ext?', async (req, res) => { +app.get('/:file{.:ext}', async (req, res) => { res.send('ok'); }); ``` - Regexp characters are not supported. For example: ```diff -app.get('/[discussion|page]/:slug', async (req, res) => { +app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { res.status(200).send('ok'); }); ``` - Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. - Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. ### Rejected promises handled from middleware and handlers Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. Details of how Express handles errors is covered in the [error handling documentation](/guide/error-handling). #### How to update You can now use `async/await` directly without manually catching errors. If `getUserById` throws an error or rejects, `next` will be called automatically with the rejected value. ```diff -app.get('/user/:id', (req, res, next) => { - getUserById(req.params.id) - .then((user) => res.send(user)) - .catch(next); -}); +app.get('/user/:id', async (req, res) => { + const user = await getUserById(req.params.id); + res.send(user); +}); ``` ### express.urlencoded The `express.urlencoded` method makes the `extended` option `false` by default. #### How to update If your application relies on the `extended` behavior, explicitly set it to `true`: ```diff -app.use(express.urlencoded()); +app.use(express.urlencoded({ extended: true })); ``` ### express.static dotfiles The `express.static` middleware's `dotfiles` option now defaults to `"ignore"`. In Express 4, dotfiles were served by default. As a result, files inside a directory that starts with a dot (`.`), such as `.well-known`, will no longer be accessible and will return a **404 Not Found** error. This can break functionality that depends on serving dot-directories, such as Android App Links and Apple Universal Links. #### How to update Serve specific dot-directories explicitly using the `dotfiles: "allow"` option. This allows you to safely serve only the intended dot-directories while keeping the default secure behavior for other dotfiles. ```diff +app.use('/.well-known', express.static('public/.well-known', { dotfiles: 'allow' })); app.use(express.static('public')); ``` ### router.param() with an array of names `router.param(name, fn)` no longer accepts an array for `name`. In Express 4 an array was accepted silently; in Express 5, passing anything other than a string throws `TypeError: argument name must be a string`. (Note that `app.param()` still accepts an array of names.) #### How to update Register each parameter name with its own `router.param()` call: ```diff -router.param(['id', 'page'], (req, res, next, value) => { - // ... -}); +const loadParam = (req, res, next, value) => { + // ... +}; +router.param('id', loadParam); +router.param('page', loadParam); ``` ### app.listen In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. For example: ```js ins={2-4} const server = app.listen(8080, '0.0.0.0', (error) => { if (error) { throw error; // e.g. EADDRINUSE } console.log(`Listening on ${JSON.stringify(server.address())}`); }); ``` ### app.router The `app.router` object, which was removed in Express 4, has made a comeback in Express 5. In the new version, this object is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it. ### req.body The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default. ```js del={4} ins={6} app.post('/user', (req, res) => { console.dir(req.body); // Express 4 // => {} // Express 5 // => undefined }); ``` ### req.host In Express 4, the `req.host` function incorrectly stripped off the port number if it was present. In Express 5, the port number is maintained. ### req.params The `req.params` object now has a **null prototype** when using string paths. However, if the path is defined with a regular expression, `req.params` remains a standard object with a normal prototype. Additionally, there are two important behavioral changes: **Wildcard parameters are now arrays:** Wildcards (e.g., `/*splat`) capture path segments as an array instead of a single string. ```js app.get('/*splat', (req, res) => { // GET /foo/bar console.dir(req.params); // => [Object: null prototype] { splat: [ 'foo', 'bar' ] } }); ``` **Unmatched parameters are omitted:** In Express 4, unmatched wildcards were empty strings (`''`) and optional `:` parameters (using `?`) had a key with value `undefined`. In Express 5, unmatched parameters are completely omitted from `req.params`. ```diff -// v4: unmatched wildcard is empty string -app.get('/*', (req, res) => { - // GET / - console.dir(req.params); - // => { '0': '' } -}); - -// v4: unmatched optional param is undefined -app.get('/:file.:ext?', (req, res) => { - // GET /image - console.dir(req.params); - // => { file: 'image', ext: undefined } -}); - +// v5: unmatched optional param is omitted +app.get('/:file{.:ext}', (req, res) => { + // GET /image + console.dir(req.params); + // => [Object: null prototype] { file: 'image' } +}); ``` ### req.query The `req.query` property is no longer a writable property and is instead a getter. The default query parser has been changed from "extended" to "simple". ```js del={3} app.get('/search', (req, res) => { // This is no longer possible in Express 5 req.query.page = 1; }); ``` ### res.clearCookie The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. ```diff app.get('/logout', (req, res) => { - res.clearCookie('session', { maxAge: 0, expires: new Date(0) }); + res.clearCookie('session'); }); ``` ### res.status The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. ```js del={2} app.get('/user', (req, res) => { res.status(99); // Throws an error res.status(200); // OK }); ``` ### res.vary The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console. ```js del={2} app.get('/user', (req, res) => { res.vary(); // Throws an error res.vary('Accept'); // OK }); ``` ## Improvements These changes don't require any migration steps, but are worth knowing about when upgrading. ### res.render() This method now enforces asynchronous behavior for all view engines, avoiding bugs caused by view engines that had a synchronous implementation and that violated the recommended interface. ### Brotli encoding support Middleware like `express.json()`, `express.urlencoded()`, `express.text()`, and `express.raw()` now support Brotli (`Content-Encoding: br`) decompression for incoming request bodies, in addition to `gzip` and `deflate`. --- ## Resources URL: https://expressjs.com/en/resources Find resources to help you learn, contribute, and connect with the Express.js ecosystem. Whether you're looking to get involved in the community, explore middleware, or understand key concepts, you'll find what you need here. --- ## Community URL: https://expressjs.com/en/resources/community ## Technical committee The Express technical committee meets online every two weeks (as needed) to discuss development and maintenance of Express, and other issues relevant to the Express project. Each meeting is typically announced in an [expressjs/discussions issue](https://github.com/expressjs/discussions/issues) with a link to join or view the meeting, which is open to all observers. The meetings are recorded; for a list of the recordings, see the [Express.js YouTube channel](https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g). Members of the Express technical committee are: **Active:** - [@blakeembrey](https://github.com/blakeembrey) - Blake Embrey - [@crandmck](https://github.com/crandmck) - Rand McKinney - [@LinusU](https://github.com/LinusU) - Linus Unnebäck - [@ulisesgascon](https://github.com/ulisesGascon) - Ulises Gascón - [@sheplu](https://github.com/sheplu) - Jean Burellier - [@wesleytodd](https://github.com/wesleytodd) - Wes Todd - [@jonchurch](https://github.com/jonchurch) - Jon Church - [@ctcpip](https://github.com/ctcpip/) - Chris de Almeida **Inactive:** - [@dougwilson](https://github.com/dougwilson) - Douglas Wilson - [@hacksparrow](https://github.com/hacksparrow) - Hage Yaapa - [@jonathanong](https://github.com/jonathanong) - jongleberry - [@niftylettuce](https://github.com/niftylettuce) - niftylettuce - [@troygoode](https://github.com/troygoode) - Troy Goode ## Express is made of many modules Our vibrant community has created a large variety of extensions, [middleware modules](/resources/middleware) and higher-level frameworks. Additionally, the Express community maintains modules in these two GitHub orgs: - [jshttp](https://github.com/jshttp) modules providing useful utility functions; see [Utility modules](/resources/utils/). - [pillarjs](https://github.com/pillarjs): low-level modules that Express uses internally. To keep up with what is going on in the whole community, check out the [ExpressJS StatusBoard](https://expressjs.github.io/statusboard/). ## Issues If you've come across what you think is a bug, or just want to make a feature request open a ticket in the [issue queue](https://github.com/expressjs/express/issues). ## Examples View dozens of Express application [examples](https://github.com/expressjs/express/tree/master/examples) in the repository covering everything from API design and authentication to template engine integration. ## GitHub Discussions The [GitHub Discussions](https://github.com/expressjs/discussions) section is an excellent space to engage in conversations about the development and maintenance of Express, as well as to share ideas and discuss topics related to its usage. ## Express.js Logo Express is a project of the OpenJS Foundation. Please review the [trademark policy](https://trademark-policy.openjsf.org/) for information about permissible use of Express.js logos and marks. ### Wordmark ### Glyph ### Kawaii This logo was created by [SAWARATSUKI](https://github.com/SAWARATSUKI). --- ## Contributing to Express URL: https://expressjs.com/en/resources/contributing Express is an [OpenJS Foundation](https://openjsf.org/) project spread across three GitHub organizations: [expressjs](https://github.com/expressjs), [pillarjs](https://github.com/pillarjs), and [jshttp](https://github.com/jshttp). All contributions are welcome, whether it's reporting bugs, improving documentation, or submitting code. The guidelines below describe how the project operates and how you can get involved. ## Technical committee The Express technical committee consists of active project members, and guides development and maintenance of the Express project. For more information, see [Express Community - Technical committee](/resources/community/#technical-committee). ## Community contributing guide {/* SRC: expressjs/discussions docs/GOVERNANCE.md */} The goal of this document is to create a contribution process that: - Encourages new contributions. - Encourages contributors to remain involved. - Avoids unnecessary processes and bureaucracy whenever possible. - Creates a transparent decision making process that makes it clear how contributors can be involved in decision making. ### Vocabulary - A **Contributor** is any individual creating or commenting on an issue or pull request. - A **Committer** is a subset of contributors who have been given write access to the repository. - A **Project Captain** is the lead maintainer of a repository. - A **TC (Technical Committee)** is a group of committers representing the required technical expertise to resolve rare disputes. - A **Triager** is a subset of contributors who have been given triage access to the repository. ### Logging Issues Log an issue for any question or problem you might have. When in doubt, log an issue, and any additional policies about what to include will be provided in the responses. The only exception is security disclosures which should be sent privately. Committers may direct you to another repository, ask for additional clarifications, and add appropriate metadata before the issue is addressed. Please be courteous and respectful. Every participant is expected to follow the project's Code of Conduct. ### Contributions Any change to resources in this repository must be through pull requests. This applies to all changes to documentation, code, binary files, etc. Even long term committers and TC members must use pull requests. No pull request can be merged without being reviewed. For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that contributors in other timezones have time to review. Consideration should also be given to weekends and other holiday periods to ensure active committers all have reasonable time to become involved in the discussion and review process if they wish. The default for each contribution is that it is accepted once no committer has an objection. During a review, committers may also request that a specific contributor who is most versed in a particular area gives a "LGTM" before the PR can be merged. There is no additional "sign off" process for contributions to land. Once all issues brought by committers are addressed it can be landed by any committer. In the case of an objection being raised in a pull request by another committer, all involved committers should seek to arrive at a consensus by way of addressing concerns being expressed by discussion, compromise on the proposed change, or withdrawal of the proposed change. If a contribution is controversial and committers cannot agree about how to get it to land or if it should land then it should be escalated to the TC. TC members should regularly discuss pending contributions in order to find a resolution. It is expected that only a small minority of issues be brought to the TC for resolution and that discussion and compromise among committers be the default resolution mechanism. ### Becoming a Triager Anyone can become a triager! Read more about the process of being a triager in [the triage process document](https://github.com/expressjs/discussions/blob/HEAD/docs/contributing/triager-guide.md). Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate a new triager. If you are interested in becoming a triager, our best advice is to actively participate in the community by helping triaging issues and pull requests. As well we recommend to engage in other community activities like attending the TC meetings, and participating in the Slack discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution. You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people) if you have questions or need guidance. ### Becoming a Committer All contributors who have landed significant and valuable contributions should be onboarded in a timely manner, and added as a committer, and be given write access to the repository. Committers are expected to follow this policy and continue to send pull requests, go through proper review, and have other committers merge their pull requests. ### TC Process The TC uses a "consensus seeking" process for issues that are escalated to the TC. The group tries to find a resolution that has no open objections among TC members. If a consensus cannot be reached that has no objections then a majority wins vote is called. It is also expected that the majority of decisions made by the TC are via a consensus seeking process and that voting is only used as a last-resort. Resolution may involve returning the issue to project captains with suggestions on how to move forward towards a consensus. It is not expected that a meeting of the TC will resolve all issues on its agenda during that meeting and may prefer to continue the discussion happening among the project captains. Members can be added to the TC at any time. Any TC member can nominate another committer to the TC and the TC uses its standard consensus seeking process to evaluate whether or not to add this new member. The TC will consist of a minimum of 3 active members and a maximum of 10. If the TC should drop below 5 members the active TC members should nominate someone new. If a TC member is stepping down, they are encouraged (but not required) to nominate someone to take their place. TC members will be added as admin's on the Github orgs, npm orgs, and other resources as necessary to be effective in the role. To remain "active" a TC member should have participation within the last 12 months and miss no more than six consecutive TC meetings. Our goal is to increase participation, not punish people for any lack of participation, this guideline should be only be used as such (replace an inactive member with a new active one, for example). Members who do not meet this are expected to step down. If A TC member does not step down, an issue can be opened in the discussions repo to move them to inactive status. TC members who step down or are removed due to inactivity will be moved into inactive status. Inactive status members can become active members by self nomination if the TC is not already larger than the maximum of 10. They will also be given preference if, while at max size, an active member steps down. ### Project Captains The Express TC can designate captains for individual projects/repos in the organizations. These captains are responsible for being the primary day-to-day maintainers of the repo on a technical and community front. Repo captains are empowered with repo ownership and package publication rights. When there are conflicts, especially on topics that effect the Express project at large, captains are responsible to raise it up to the TC and drive those conflicts to resolution. Captains are also responsible for making sure community members follow the community guidelines, maintaining the repo and the published package, as well as in providing user support. Like TC members, Repo captains are a subset of committers. To become a captain for a project the candidate is expected to participate in that project for at least 6 months as a committer prior to the request. They should have helped with code contributions as well as triaging issues. They are also required to have 2FA enabled on both their GitHub and npm accounts. Any TC member or an existing captain on the **same** repo can nominate another committer to the captain role. To do so, they should submit a PR to this document, updating the **Active Project Captains** section (while maintaining the sort order) with the project name, the nominee's GitHub handle, and their npm username (if different). - Repos can have as many captains as make sense for the scope of work. - A TC member or an existing repo captain **on the same project** can nominate a new captain. Repo captains from other projects should not nominate captains for a different project. The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow for comment and/or dissent. When the PR is merged, a TC member will add them to the proper GitHub/npm groups. #### Active Projects and Captains The list can be found at [https://github.com/expressjs/discussions/blob/HEAD/docs/contributing/captains_and_committers.md#active-projects-and-members](https://github.com/expressjs/discussions/blob/HEAD/docs/contributing/captains_and_committers.md#active-projects-and-members) #### Current Initiative Captains The list can be found at [https://github.com/expressjs/discussions/blob/HEAD/docs/contributing/captains_and_committers.md#current-initiative-captains](https://github.com/expressjs/discussions/blob/HEAD/docs/contributing/captains_and_committers.md#current-initiative-captains) ### Inactivity and Emeritus Policy for Any Role To support the health and continuity of the project, all individuals holding a role within the community (such as Triager, Committer, WG member, Project Captain, or TC member) are encouraged to maintain active participation. Inactivity is defined as the absence of meaningful involvement in the project—such as contributions, code reviews, triage, meeting attendance, or discussion participation—for a continuous period of 6 months. #### Exceptions Anyone may request a temporary leave from active participation due to personal or professional reasons. In such cases, the individual should inform the relevant team or the Technical Committee (TC). During this time, the inactivity policy is paused, and the individual will not be flagged as inactive. #### Inactivity Process - If someone is deemed inactive, the individual may be transitioned to an emeritus role that reflects their past contributions. A best effort will be made to inform them that this has occurred. They may request to be reinstated when they are ready to be active again. - The emeritus status helps preserve a clear record of contributors who have meaningfully shaped the project over time. #### Accountability - The Technical Committee (TC) and the respective captains of each package/team are responsible for assessing activity levels and enacting this policy fairly and transparently, in coordination with other relevant teams. - In case of disagreement, the situation can be discussed and resolved by consensus within the TC or appropriate team. ### Developer's Certificate of Origin 1.1 ```text By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` ## Collaborator's guide {/* SRC: expressjs/.github CONTRIBUTING.md */} ### Website Issues Open issues for the expressjs.com website in https://github.com/expressjs/expressjs.com. For issues in other Express managed repos (everything in `expressjs`, `pillarjs` or `jshttp` other than `expressjs/express`), be sure to check their contributing guide and open issues and PRs in the appropriate repository. ### PRs and Code contributions - Tests must pass. - Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`. - If you fix a bug, add a test. ### Branches Use the `master` branch for bug fixes or minor work that is intended for the current release stream. Use the correspondingly named branch, e.g. `6.x`, for anything intended for a future release of Express. ### Steps for contributing 1. Create an issue for the bug you want to fix or the feature that you want to add. 2. Create your own fork on GitHub, then checkout your fork. 3. Write your code in your local copy. It's good practice to create a branch for each new issue you work on, although not compulsory. 4. To run the test suite, first install the dependencies by running `npm install`, then run `npm test`. 5. Ensure your code is linted by running `npm run lint` -- fix any issue you see listed. 6. If the tests pass, you can commit your changes to your fork and then create a pull request from there. Make sure to reference your issue from the pull request comments by including the issue number e.g. `#123`. ### Issues which are questions We will typically close any vague issues or questions that are specific to some app you are writing. Please double check the docs and other references before being trigger happy with posting a question issue. Things that will help get your question issue looked at: - Full and runnable JS code. - Clear description of the problem or unexpected behavior. - Clear description of the expected result. - Steps you have taken to debug it yourself. If you post a question and do not outline the above items or make it easy for us to understand and reproduce your issue, it will be closed. If your question meets all of the above requirements but you do not believe it needs to be looked at by the maintainers (for example, if you are just looking for community input) please open it as a discussion topic instead of an issue. If you are unsure and open an issue, we may move it to discussions if we triage them and decide they do not need high visibility or maintainer input. ## Security Policies and Procedures {/* SRC: expressjs/.github SECURITY.md */} This document outlines security procedures and general policies for the Express project. - [Reporting a Bug or Security Vulnerability](#reporting-a-bug-or-security-vulnerability) - [Disclosure Policy](#disclosure-policy) - [Comments on this Policy](#comments-on-this-policy) - [The Express Threat Model](#the-express-threat-model) ### Reporting a Bug or Security Vulnerability Before reporting a vulnerability, please review the [Express Threat Model](#the-express-threat-model) to check if the issue falls within Express's security scope. The Express team and community take all security vulnerabilities seriously. Thank you for improving the security of Express and related projects. We appreciate your efforts in responsible disclosure and will make every effort to acknowledge your contributions. A [Security triage team member](https://github.com/expressjs/security-wg#security-triage-team-expressjssecurity-triage) or [the repo captain](https://github.com/expressjs/discussions/blob/master/docs/contributing/captains_and_committers.md) will acknowledge your report as soon as possible. These timelines may extend when our triage volunteers are away on holiday, particularly at the end of the year. After the initial reply to your report, the security team will endeavor to keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance. You can find more information about our process in [this guide](https://github.com/expressjs/security-wg/blob/main/docs/incident_response_plan.md) #### Reporting Security Bugs via GitHub Security Advisory (Preferred) The preferred way to report security vulnerabilities is through [GitHub Security Advisories](https://github.com/advisories). This allows us to collaborate on a fix while maintaining the confidentiality of the report. To report a vulnerability ([docs](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability)): 1. Visit the **Security** tab of the affected repository on GitHub. 2. Click **Report a vulnerability** and follow the provided steps. This process applies to any repositories within the Express ecosystem. If you are unsure whether a repository falls under this policy, feel free to reach out via email. #### Reporting via Email If you prefer, you can also report security issues by emailing `express-security@lists.openjsf.org`. To ensure a timely response, please include all relevant details directly in the email body rather than linking to external sources or attaching files. The lead maintainer will acknowledge your email within 48 hours and provide an initial response outlining the next steps. The security team will keep you updated on the progress and may request additional details. #### Third-Party Modules If the security issue pertains to a third-party module that is not directly maintained within the Express ecosystem, please report it to the maintainers of that module. ### Disclosure Policy When the security team receives a security bug report, they will assign it to a primary handler. This person will coordinate the fix and release process, involving the following steps: - Confirm the problem and determine the affected versions. - Audit code to find any potential similar problems. - Prepare fixes for all releases still under maintenance. These fixes will be released as fast as possible to npm. ### Comments on this Policy If you have suggestions on how this process could be improved please submit a pull request. ### The Express Threat Model The Express threat model defines the boundaries of what the framework considers its security responsibility. It establishes which elements are trusted (such as the developer, the runtime environment, and application code) versus untrusted (such as data from network connections). Issues arising from trusted elements are considered out of scope, while Express is responsible for safely handling untrusted data. Many commonly reported concerns fall outside Express's security scope and are the responsibility of the application developer. Such as prototype pollution from unsanitized user input, misconfigured static file serving, or issues in third-party dependencies. For complete details, see the [Express Threat Model](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md). --- ## Glossary URL: https://expressjs.com/en/resources/glossary ## application In general, one or more programs that are designed to carry out operations for a specific purpose. In the context of Express, a program that uses the Express API running on the Node.js platform. Might also refer to an [app object](/api/express). ## API Application programming interface. Spell out the abbreviation when it is first used. ## Express A fast, un-opinionated, minimalist web framework for Node.js applications. In general, "Express" is preferred to "Express.js," though the latter is acceptable. ## libuv A multi-platform support library which focuses on asynchronous I/O, primarily developed for use by Node.js. ## middleware A function that is invoked by the Express routing layer before the final request handler, and thus sits in the middle between a raw request and the final intended route. A few fine points of terminology around middleware: - `var foo = require('middleware')` is called _requiring_ or _using_ a Node.js module. Then the statement `var mw = foo()` typically returns the middleware. - `app.use(mw)` is called _adding the middleware to the global processing stack_. - `app.get('/foo', mw, (req, res) => { /* ... */ })` is called _adding the middleware to the "GET /foo" processing stack_. ## Node.js A software platform that is used to build scalable network applications. Node.js uses JavaScript as its scripting language, and achieves high throughput via non-blocking I/O and a single-threaded event loop. See [nodejs.org](https://nodejs.org/en/). **Usage note**: Initially, "Node.js," thereafter "Node". ## open-source, open source When used as an adjective, hyphenate; for example: "This is open-source software." See [Open-source software on Wikipedia](https://en.wikipedia.org/wiki/Open-source_software). Although it is common not to hyphenate this term, we are using the standard English rules for hyphenating a compound adjective. ## request An HTTP request. A client submits an HTTP request message to a server, which returns a response. The request must use one of several [request methods](https://en.wikipedia.org/wiki/HTTP#Request_methods) such as GET, POST, and so on. ## response An HTTP response. A server returns an HTTP response message to the client. The response contains completion status information about the request and might also contain requested content in its message body. ## route Part of a URL that identifies a resource. For example, in `http://foo.com/products/id`, "/products/id" is the route. ## router See [router](/api/router) in the API reference. --- ## Express middleware URL: https://expressjs.com/en/resources/middleware The Express middleware modules listed here are maintained by the [Expressjs team](https://github.com/orgs/expressjs/people). | Middleware module | Description | | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | [body-parser](/resources/middleware/body-parser) | Parse HTTP request body. | | [compression](/resources/middleware/compression) | Compress HTTP responses. | | [cookie-parser](/resources/middleware/cookie-parser) | Parse cookie header and populate `req.cookies`. See also [cookies](https://github.com/jed/cookies). | | [cookie-session](/resources/middleware/cookie-session) | Establish cookie-based sessions. | | [cors](/resources/middleware/cors) | Enable cross-origin resource sharing (CORS) with various options. | | [errorhandler](/resources/middleware/errorhandler) | Development error-handling/debugging. | | [method-override](/resources/middleware/method-override) | Override HTTP methods using header. | | [morgan](/resources/middleware/morgan) | HTTP request logger. | | [multer](/resources/middleware/multer) | Handle multi-part form data. | | [response-time](/resources/middleware/response-time) | Record HTTP response time. | | [serve-favicon](/resources/middleware/serve-favicon) | Serve a favicon. | | [serve-index](/resources/middleware/serve-index) | Serve directory listing for a given path. | | [serve-static](/resources/middleware/serve-static) | Serve static files. | | [session](/resources/middleware/session) | Establish server-based sessions (development only). | | [timeout](/resources/middleware/timeout) | Set a timeout period for HTTP request processing. | | [vhost](/resources/middleware/vhost) | Create virtual domains. | ## Additional middleware modules These are some additional popular middleware modules. This information refers to third-party sites, products, or modules that are not maintained by the Expressjs team. Listing here does not constitute an endorsement or recommendation from the Expressjs project team. | Middleware module | Description | | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | [helmet](https://github.com/helmetjs/helmet) | Helps secure your apps by setting various HTTP headers. | | [passport](https://github.com/jaredhanson/passport) | Authentication using "strategies" such as OAuth, OpenID and many others. See [passportjs.org](https://passportjs.org/) for more information. | --- ## body-parser middleware URL: https://expressjs.com/en/resources/middleware/body-parser Node.js body parsing middleware. Parse incoming request bodies in a middleware before your handlers, available under the `req.body` property. **Note** As `req.body`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example the `foo` property may not be there or may not be a string, and `toString` may not be a function and instead a string or other user input. [Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/learn/http/anatomy-of-an-http-transaction). _This does not handle multipart bodies_, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: - [busboy](https://www.npmjs.com/package/busboy#readme) and [connect-busboy](https://www.npmjs.com/package/connect-busboy#readme) - [multiparty](https://www.npmjs.com/package/multiparty#readme) and [connect-multiparty](https://www.npmjs.com/package/connect-multiparty#readme) - [formidable](https://www.npmjs.com/package/formidable#readme) - [multer](https://www.npmjs.com/package/multer#readme) This module provides the following parsers: - [JSON body parser](#bodyparserjsonoptions) - [Raw body parser](#bodyparserrawoptions) - [Text body parser](#bodyparsertextoptions) - [URL-encoded form body parser](#bodyparserurlencodedoptions) All parsers support automatic inflation of `gzip`, `br` (brotli), `deflate` and `zstd` encodings. `zstd` is available in Node.js `^22.15.0` and `>=23.8.0`. Other body parsers you might be interested in: - [body](https://www.npmjs.com/package/body#readme) - [co-body](https://www.npmjs.com/package/co-body#readme) ## Installation `body-parser` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js // Import all parsers const bodyParser = require('body-parser'); // Or import individual parsers directly const json = require('body-parser/json'); const urlencoded = require('body-parser/urlencoded'); const raw = require('body-parser/raw'); const text = require('body-parser/text'); ``` The `bodyParser` object exposes various factories to create middlewares. All middlewares will populate the `req.body` property with the parsed body when the `Content-Type` request header matches the `type` option. **Note** As of v2, `req.body` is left `undefined` when no body is parsed (for example when the request has neither `Content-Length` nor `Transfer-Encoding`, or when `Content-Type` does not match). In v1, `req.body` was always initialized to `{}`. Code that assumes `req.body` is always an object should use optional chaining (for example `req.body?.username`) or set a default. The various errors returned by this module are described in the [errors section](#errors). ### bodyParser.json([options]) Returns middleware that only parses `json` and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts any Unicode encoding of the body. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). #### Options The `json` function takes an optional `options` object that may contain any of the following keys: ##### defaultCharset Specify the default character set for the json content if the charset is not specified in the `Content-Type` header of the request. Defaults to `utf-8`. ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### limit Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults to `'100kb'`. > It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. ##### reviver The `reviver` option is passed directly to `JSON.parse` as the second argument. You can find more information on this argument [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter). ##### strict When set to `true`, it will only accept arrays and objects; when `false`, it will accept anything `JSON.parse` accepts. Defaults to `true`. ##### type The `type` option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this can be an extension name (like `json`), a mime type (like `application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `application/json`. ##### verify The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ### bodyParser.raw([options]) Returns middleware that parses all bodies as a `Buffer` and only looks at requests where the `Content-Type` header matches the `type` option. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This will be a `Buffer` object of the body. #### Options The `raw` function takes an optional `options` object that may contain any of the following keys: ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### limit Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults to `'100kb'`. > It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. ##### type The `type` option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this can be an extension name (like `bin`), a mime type (like `application/octet-stream`), or a mime type with a wildcard (like `*/*` or `application/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `application/octet-stream`. ##### verify The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ### bodyParser.text([options]) Returns middleware that parses all bodies as a string and only looks at requests where the `Content-Type` header matches the `type` option. A new `body` string containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This will be a string of the body. #### Options The `text` function takes an optional `options` object that may contain any of the following keys: ##### defaultCharset Specify the default character set for the text content if the charset is not specified in the `Content-Type` header of the request. Defaults to `utf-8`. ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### limit Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults to `'100kb'`. > It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. ##### type The `type` option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this can be an extension name (like `txt`), a mime type (like `text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `text/plain`. ##### verify The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ### bodyParser.urlencoded([options]) Returns middleware that only parses `urlencoded` bodies and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts only UTF-8 and ISO-8859-1 encodings of the body. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This object will contain key-value pairs, where the value can be a string or array (when `extended` is `false`), or any type (when `extended` is `true`). #### Options The `urlencoded` function takes an optional `options` object that may contain any of the following keys: ##### extended The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please [see the qs library](https://www.npmjs.com/package/qs#readme). Defaults to `false`. ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### limit Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults to `'100kb'`. > It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. ##### parameterLimit The `parameterLimit` option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, a 413 will be returned to the client. Defaults to `1000`. ##### type The `type` option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this can be an extension name (like `urlencoded`), a mime type (like `application/x-www-form-urlencoded`), or a mime type with a wildcard (like `*/x-www-form-urlencoded`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `application/x-www-form-urlencoded`. ##### verify The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ##### defaultCharset The default charset to parse as, if not specified in content-type. Must be either `utf-8` or `iso-8859-1`. Defaults to `utf-8`. ##### charsetSentinel Whether to let the value of the `utf8` parameter take precedence as the charset selector. It requires the form to contain a parameter named `utf8` with a value of `✓`. Defaults to `false`. ##### interpretNumericEntities Whether to decode numeric entities such as `☺` when parsing an iso-8859-1 form. Defaults to `false`. ##### depth The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible. ## Errors The middlewares provided by this module create errors using the [`http-errors` module](https://www.npmjs.com/package/http-errors). The errors will typically have a `status`/`statusCode` property that contains the suggested HTTP response code, an `expose` property to determine if the `message` property should be displayed to the client, a `type` property to determine the type of error without matching against the `message`, and a `body` property containing the read body, if available. The following are the common errors created, though any error can come through for various reasons. ### content encoding unsupported This error will occur when the request had a `Content-Encoding` header that contained an encoding but the "inflation" option was set to `false`. The `status` property is set to `415`, the `type` property is set to `'encoding.unsupported'`, and the `charset` property will be set to the encoding that is unsupported. ### entity parse failed This error will occur when the request contained an entity that could not be parsed by the middleware. The `status` property is set to `400`, the `type` property is set to `'entity.parse.failed'`, and the `body` property is set to the entity value that failed parsing. ### entity verify failed This error will occur when the request contained an entity that could not be verified by the defined `verify` option. The `status` property is set to `403`, the `type` property is set to `'entity.verify.failed'`, and the `body` property is set to the entity value that failed verification. ### request aborted This error will occur when the request is aborted by the client before reading the body has finished. The `received` property will be set to the number of bytes received before the request was aborted and the `expected` property is set to the number of expected bytes. The `status` property is set to `400` and `type` property is set to `'request.aborted'`. ### request entity too large This error will occur when the request body's size is larger than the "limit" option. The `limit` property will be set to the byte limit and the `length` property will be set to the request body's length. The `status` property is set to `413` and the `type` property is set to `'entity.too.large'`. ### request size did not match content length This error will occur when the request's length did not match the length from the `Content-Length` header. This typically occurs when the request is malformed, typically when the `Content-Length` header was calculated based on characters instead of bytes. The `status` property is set to `400` and the `type` property is set to `'request.size.invalid'`. ### stream encoding should not be set This error will occur when something called the `req.setEncoding` method prior to this middleware. This module operates directly on bytes only and you cannot call `req.setEncoding` when using this module. The `status` property is set to `500` and the `type` property is set to `'stream.encoding.set'`. ### stream is not readable This error will occur when the request is no longer readable when this middleware attempts to read it. This typically means something other than a middleware from this module read the request body already and the middleware was also configured to read the same request. The `status` property is set to `500` and the `type` property is set to `'stream.not.readable'`. ### too many parameters This error will occur when the content of the request exceeds the configured `parameterLimit` for the `urlencoded` parser. The `status` property is set to `413` and the `type` property is set to `'parameters.too.many'`. ### unsupported charset "BOGUS" This error will occur when the request had a charset parameter in the `Content-Type` header, but the `iconv-lite` module does not support it OR the parser does not support it. The charset is contained in the message as well as in the `charset` property. The `status` property is set to `415`, the `type` property is set to `'charset.unsupported'`, and the `charset` property is set to the charset that is unsupported. ### unsupported content encoding "bogus" This error will occur when the request had a `Content-Encoding` header that contained an unsupported encoding. The encoding is contained in the message as well as in the `encoding` property. The `status` property is set to `415`, the `type` property is set to `'encoding.unsupported'`, and the `encoding` property is set to the encoding that is unsupported. ### The input exceeded the depth This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. With the default `depth` of `32`, an input with 33 or more levels of nesting gets this error. ## Examples ### Express/Connect top-level generic This example demonstrates adding a generic JSON and URL-encoded parser as a top-level middleware, which will parse the bodies of all incoming requests. This is the simplest setup. ```js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded()); // parse application/json app.use(bodyParser.json()); app.use(function (req, res) { res.setHeader('Content-Type', 'text/plain'); res.write('you posted:\n'); res.end(String(JSON.stringify(req.body, null, 2))); }); ``` ### Express route-specific This example demonstrates adding body parsers specifically to the routes that need them. In general, this is the most recommended way to use body-parser with Express. ```js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // create application/json parser const jsonParser = bodyParser.json(); // create application/x-www-form-urlencoded parser const urlencodedParser = bodyParser.urlencoded(); // POST /login gets urlencoded bodies app.post('/login', urlencodedParser, function (req, res) { if (!req.body || !req.body.username) res.sendStatus(400); res.send('welcome, ' + req.body.username); }); // POST /api/users gets JSON bodies app.post('/api/users', jsonParser, function (req, res) { if (!req.body) res.sendStatus(400); // create user in req.body }); ``` ### Change accepted type for parsers All the parsers accept a `type` option which allows you to change the `Content-Type` that the middleware will parse. ```js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // parse various different custom JSON types as JSON app.use(bodyParser.json({ type: 'application/*+json' })); // parse some custom thing into a Buffer app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })); // parse an HTML body into a string app.use(bodyParser.text({ type: 'text/html' })); ``` ## License [MIT](https://github.com/expressjs/body-parser/blob/HEAD/LICENSE) [npm-url]: https://npmjs.com/package/body-parser [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser --- ## compression middleware URL: https://expressjs.com/en/resources/middleware/compression Node.js compression middleware. The following compression codings are supported: - deflate - gzip - br (brotli) **Note** Brotli is available in all currently supported Node.js LTS versions (v18+). ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/downloading-and-installing-packages-locally): `compression` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var compression = require('compression'); ``` ### compression([options]) Returns the compression middleware using the given `options`. The middleware will attempt to compress response bodies for all requests that traverse through the middleware, based on the given `options`. This middleware will never compress responses that include a `Cache-Control` header with the [`no-transform` directive](https://tools.ietf.org/html/rfc7234#section-5.2.2.4), as compressing will transform the body. #### Options `compression()` accepts these properties in the options object. In addition to those listed below, [zlib](https://nodejs.org/api/zlib.html) options may be passed in to the options object or [brotli](https://nodejs.org/api/zlib.html#zlib_class_brotlioptions) options. ##### chunkSize Type: `Number`
Default: `zlib.constants.Z_DEFAULT_CHUNK`, or `16384`. See [Node.js documentation](https://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### filter Type: `Function` A function to decide if the response should be considered for compression. This function is called as `filter(req, res)` and is expected to return `true` to consider the response for compression, or `false` to not compress the response. The default filter function uses the [compressible](https://www.npmjs.com/package/compressible) module to determine if `res.getHeader('Content-Type')` is compressible. ##### level Type: `Number`
Default: `zlib.constants.Z_DEFAULT_COMPRESSION`, or `-1` The level of zlib compression to apply to responses. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster. This is an integer in the range of `0` (no compression) to `9` (maximum compression). The special value `-1` can be used to mean the "default compression level", which is a default compromise between speed and compression (currently equivalent to level 6). - `-1` Default compression level (also `zlib.constants.Z_DEFAULT_COMPRESSION`). - `0` No compression (also `zlib.constants.Z_NO_COMPRESSION`). - `1` Fastest compression (also `zlib.constants.Z_BEST_SPEED`). - `2` - `3` - `4` - `5` - `6` (currently what `zlib.constants.Z_DEFAULT_COMPRESSION` points to). - `7` - `8` - `9` Best compression (also `zlib.constants.Z_BEST_COMPRESSION`). **Note** in the list above, `zlib` is from `zlib = require('zlib')`. ##### memLevel Type: `Number`
Default: `zlib.constants.Z_DEFAULT_MEMLEVEL`, or `8` This specifies how much memory should be allocated for the internal compression state and is an integer in the range of `1` (minimum level) and `9` (maximum level). See [Node.js documentation](https://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### brotli Type: `Object` This specifies the options for configuring Brotli. See [Node.js documentation](https://nodejs.org/api/zlib.html#class-brotlioptions) for a complete list of available options. ##### strategy Type: `Number`
Default: `zlib.constants.Z_DEFAULT_STRATEGY` This is used to tune the compression algorithm. This value only affects the compression ratio, not the correctness of the compressed output, even if it is not set appropriately. - `zlib.constants.Z_DEFAULT_STRATEGY` Use for normal data. - `zlib.constants.Z_FILTERED` Use for data produced by a filter (or predictor). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect is to force more Huffman coding and less string matching; it is somewhat intermediate between `zlib.constants.Z_DEFAULT_STRATEGY` and `zlib.constants.Z_HUFFMAN_ONLY`. - `zlib.constants.Z_FIXED` Use to prevent the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. - `zlib.constants.Z_HUFFMAN_ONLY` Use to force Huffman encoding only (no string match). - `zlib.constants.Z_RLE` Use to limit match distances to one (run-length encoding). This is designed to be almost as fast as `zlib.constants.Z_HUFFMAN_ONLY`, but give better compression for PNG image data. **Note** in the list above, `zlib` is from `zlib = require('zlib')`. ##### threshold Type: `Number` or `String`
Default: `1kb` The byte threshold for the response body size before compression is considered for the response. This is a number of bytes or any string accepted by the [bytes](https://www.npmjs.com/package/bytes) module. **Note** this is only an advisory setting; if the response size cannot be determined at the time the response headers are written, then it is assumed the response is _over_ the threshold. To guarantee the response size can be determined, be sure set a `Content-Length` response header. ##### windowBits Type: `Number`
Default: `zlib.constants.Z_DEFAULT_WINDOWBITS`, or `15` See [Node.js documentation](https://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### enforceEncoding Type: `String`
Default: `identity` This is the default encoding to use when the client does not specify an encoding in the request's [Accept-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding) header. #### .filter The default `filter` function. This is used to construct a custom filter function that is an extension of the default function. ```js var compression = require('compression'); var express = require('express'); var app = express(); app.use(compression({ filter: shouldCompress })); function shouldCompress(req, res) { if (req.headers['x-no-compression']) { // don't compress responses with this request header return false; } // fallback to standard filter function return compression.filter(req, res); } ``` ### res.flush This module adds a `res.flush()` method to force the partially-compressed response to be flushed to the client. ## Examples ### express When using this module with express, simply `app.use` the module as high as you like. Requests that pass through the middleware will be compressed. ```js var compression = require('compression'); var express = require('express'); var app = express(); // compress all responses app.use(compression()); // add all routes ``` ### Node.js HTTP server ```js var compression = require('compression')({ threshold: 0 }); var http = require('http'); function createServer(fn) { return http.createServer(function (req, res) { compression(req, res, function (err) { if (err) { res.statusCode = err.status || 500; res.end(err.message); return; } fn(req, res); }); }); } var server = createServer(function (req, res) { res.setHeader('Content-Type', 'text/plain'); res.end('hello world!'); }); server.listen(3000, () => { console.log('> Listening at http://localhost:3000'); }); ``` ### Server-Sent Events Because of the nature of compression this module does not work out of the box with server-sent events. To compress content, a window of the output needs to be buffered up in order to get good compression. Typically when using server-sent events, there are certain block of data that need to reach the client. You can achieve this by calling `res.flush()` when you need the data written to actually make it to the client. ```js var compression = require('compression'); var express = require('express'); var app = express(); // compress responses app.use(compression()); // server-sent event stream app.get('/events', function (req, res) { res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); // send a ping approx every 2 seconds var timer = setInterval(function () { res.write('data: ping\n\n'); // !!! this is the important part res.flush(); }, 2000); res.on('close', function () { clearInterval(timer); }); }); ``` ## Contributing The Express.js project welcomes all constructive contributions. Contributions take many forms, from code for bug fixes and enhancements, to additions and fixes to documentation, additional tests, triaging incoming pull requests and issues, and more! See the [Contributing Guide](https://github.com/expressjs/.github/blob/HEAD/CONTRIBUTING.md) for more technical details on contributing. ## License [MIT](https://github.com/expressjs/compression/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/compression [downloads-url]: https://npmcharts.com/compare/compression?minimal=true [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/compression/badge [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/compression [funding-url]: https://opencollective.com/express --- ## cookie-parser middleware URL: https://expressjs.com/en/resources/middleware/cookie-parser Parse `Cookie` header and populate `req.cookies` with an object keyed by the cookie names. Optionally you may enable signed cookie support by passing a `secret` string, which assigns `req.secret` so it may be used by other middleware. ## Installation `cookie-parser` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var cookieParser = require('cookie-parser'); ``` ### cookieParser(secret, options) Create a new cookie parser middleware function using the given `secret` and `options`. - `secret` a string or array used for signing cookies. This is optional and if not specified, will not parse signed cookies. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order. - `options` an object that is passed to `cookie.parse` as the second option. See [cookie](https://www.npmjs.org/package/cookie) for more information. - `decode` a function to decode the value of the cookie The middleware will parse the `Cookie` header on the request and expose the cookie data as the property `req.cookies` and, if a `secret` was provided, as the property `req.signedCookies`. These properties are name value pairs of the cookie name to cookie value. When `secret` is provided, this module will unsign and validate any signed cookie values and move those name value pairs from `req.cookies` into `req.signedCookies`. A signed cookie is a cookie that has a value prefixed with `s:`. Signed cookies that fail signature validation will have the value `false` instead of the tampered value. In addition, this module supports special "JSON cookies". These are cookie where the value is prefixed with `j:`. When these values are encountered, the value will be exposed as the result of `JSON.parse`. If parsing fails, the original value will remain. ### cookieParser.JSONCookie(str) Parse a cookie value as a JSON cookie. This will return the parsed JSON value if it was a JSON cookie, otherwise, it will return the passed value. ### cookieParser.JSONCookies(cookies) Given an object, this will iterate over the keys and call `JSONCookie` on each value, replacing the original value with the parsed value. This returns the same object that was passed in. ### cookieParser.signedCookie(str, secret) Parse a cookie value as a signed cookie. This will return the parsed unsigned value if it was a signed cookie and the signature was valid. If the value was not signed, the original value is returned. If the value was signed but the signature could not be validated, `false` is returned. The `secret` argument can be an array or string. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order. ### cookieParser.signedCookies(cookies, secret) Given an object, this will iterate over the keys and check if any value is a signed cookie. If it is a signed cookie and the signature is valid, the key will be deleted from the object and added to the new object that is returned. The `secret` argument can be an array or string. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order. ## Example ```js var express = require('express'); var cookieParser = require('cookie-parser'); var app = express(); app.use(cookieParser()); app.get('/', function (req, res) { // Cookies that have not been signed console.log('Cookies: ', req.cookies); // Cookies that have been signed console.log('Signed Cookies: ', req.signedCookies); }); app.listen(8080); // curl command that sends an HTTP request with two cookies // curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello" ``` ## License [MIT](https://github.com/expressjs/cookie-parser/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/cookie-parser --- ## cookie-session middleware URL: https://expressjs.com/en/resources/middleware/cookie-session Simple cookie-based session middleware. A user session can be stored in two main ways with cookies: on the server or on the client. This module stores the session data on the client within a cookie, while a module like [express-session](https://www.npmjs.com/package/express-session) stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database. The following points can help you choose which to use: - `cookie-session` does not require any database / resources on the server side, though the total session data cannot exceed the browser's max cookie size. - `cookie-session` can simplify certain load-balanced scenarios. - `cookie-session` can be used to store a "light" session and include an identifier to look up a database-backed secondary store to reduce database lookups. **NOTE** This module does not encrypt the session contents in the cookie, only provides signing to prevent tampering. The client will be able to read the session data by examining the cookie's value. Secret data should not be set in `req.session` without encrypting it, or use a server-side session instead. **NOTE** This module does not prevent session replay, as the expiration set is that of the cookie only; if that is a concern of your application, you can store an expiration date in `req.session` object and validate it on the server, and implement any other logic to extend the session as your application needs. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `cookie-session` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var cookieSession = require('cookie-session'); var express = require('express'); var app = express(); app.use( cookieSession({ name: 'session', keys: [ /* secret keys */ ], // Cookie Options maxAge: 24 * 60 * 60 * 1000, // 24 hours }) ); ``` ### cookieSession(options) Create a new cookie session middleware with the provided options. This middleware will attach the property `session` to `req`, which provides an object representing the loaded session. This session is either a new session if no valid session was provided in the request, or a loaded session from the request. The middleware will automatically add a `Set-Cookie` header to the response if the contents of `req.session` were altered. _Note_ that no `Set-Cookie` header will be in the response (and thus no session created for a specific user) unless there are contents in the session, so be sure to add something to `req.session` as soon as you have identifying information to store for the session. #### Options Cookie session accepts these properties in the options object. ##### name The name of the cookie to set, defaults to `session`. ##### keys The list of keys to use to sign & verify cookie values, or a configured [`Keygrip`](https://www.npmjs.com/package/keygrip) instance. Set cookies are always signed with `keys[0]`, while the other keys are valid for verification, allowing for key rotation. If a `Keygrip` instance is provided, it can be used to change signature parameters like the algorithm of the signature. ##### secret A string which will be used as single key if `keys` is not provided. ##### Cookie Options Other options are passed to `cookies.get()` and `cookies.set()` allowing you to control security, domain, path, and signing among other settings. The options can also contain any of the following (for the full list, see [cookies module documentation](https://www.npmjs.org/package/cookies#readme): - `maxAge`: a number representing the milliseconds from `Date.now()` for expiry - `expires`: a `Date` object indicating the cookie's expiration date (expires at the end of session by default). - `path`: a string indicating the path of the cookie (`/` by default). - `domain`: a string indicating the domain of the cookie (no default). - `partitioned`: a boolean indicating whether to partition the cookie in Chrome for the [CHIPS Update](https://developers.google.com/privacy-sandbox/3pcd/chips) (`false` by default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created. - `priority`: a string indicating the cookie priority. This can be set to `'low'`, `'medium'`, or `'high'`. - `sameSite`: a boolean or string indicating whether the cookie is a "same site" cookie (`false` by default). This can be set to `'strict'`, `'lax'`, `'none'`, or `true` (which maps to `'strict'`). - `secure`: a boolean indicating whether the cookie is only to be sent over HTTPS (`false` by default for HTTP, `true` by default for HTTPS). If this is set to `true` and Node.js is not directly over a TLS connection, be sure to read how to [setup Express behind proxies](/guide/behind-proxies/) or the cookie may not ever set correctly. - `httpOnly`: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (`true` by default). - `signed`: a boolean indicating whether the cookie is to be signed (`true` by default). - `overwrite`: a boolean indicating whether to overwrite previously set cookies of the same name (`true` by default). ### req.session Represents the session for the given request. #### .isChanged Is `true` if the session has been changed during the request. #### .isNew Is `true` if the session is new. #### .isPopulated Determine if the session has been populated with data or is empty. ### req.sessionOptions Represents the session options for the current request. These options are a shallow clone of what was provided at middleware construction and can be altered to change cookie setting behavior on a per-request basis. ### Destroying a session To destroy a session simply set it to `null`: ```js req.session = null; ``` ### Saving a session Since the entire contents of the session is kept in a client-side cookie, the session is "saved" by writing a cookie out in a `Set-Cookie` response header. This is done automatically if there has been a change made to the session when the Node.js response headers are being written to the client and the session was not destroyed. ## Examples ### Simple view counter example ```js var cookieSession = require('cookie-session'); var express = require('express'); var app = express(); app.set('trust proxy', 1); // trust first proxy app.use( cookieSession({ name: 'session', keys: ['key1', 'key2'], }) ); app.get('/', function (req, res, next) { // Update views req.session.views = (req.session.views || 0) + 1; // Write response res.end(req.session.views + ' views'); }); app.listen(3000); ``` ### Per-user sticky max age ```js var cookieSession = require('cookie-session'); var express = require('express'); var app = express(); app.set('trust proxy', 1); // trust first proxy app.use( cookieSession({ name: 'session', keys: ['key1', 'key2'], }) ); // This allows you to set req.session.maxAge to let certain sessions // have a different value than the default. app.use(function (req, res, next) { req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge; next(); }); // ... your logic here ... ``` ### Extending the session expiration This module does not send a `Set-Cookie` header if the contents of the session have not changed. This means that to extend the expiration of a session in the user's browser (in response to user activity, for example) some kind of modification to the session needs be made. ```js var cookieSession = require('cookie-session'); var express = require('express'); var app = express(); app.use( cookieSession({ name: 'session', keys: ['key1', 'key2'], }) ); // Update a value in the cookie so that the set-cookie will be sent. // Only changes every minute so that it's not sent with every request. app.use(function (req, res, next) { req.session.nowInMinutes = Math.floor(Date.now() / 60e3); next(); }); // ... your logic here ... ``` ### Using a custom signature algorithm This example shows creating a custom `Keygrip` instance as the `keys` option to provide keys and additional signature configuration. ```js var cookieSession = require('cookie-session'); var express = require('express'); var Keygrip = require('keygrip'); var app = express(); app.use( cookieSession({ name: 'session', keys: new Keygrip(['key1', 'key2'], 'SHA384', 'base64'), }) ); // ... your logic here ... ``` ## Usage Limitations ### Max Cookie Size Because the entire session object is encoded and stored in a cookie, it is possible to exceed the maximum cookie size limits on different browsers. The [RFC6265 specification](https://tools.ietf.org/html/rfc6265#section-6.1) recommends that a browser **SHOULD** allow > At least 4096 bytes per cookie (as measured by the sum of the length of > the cookie's name, value, and attributes) In practice this limit differs slightly across browsers. See a list of [browser limits here](http://browsercookielimits.iain.guru). As a rule of thumb **don't exceed 4093 bytes per domain**. If your session object is large enough to exceed a browser limit when encoded, in most cases the browser will refuse to store the cookie. This will cause the following requests from the browser to either a) not have any session information or b) use old session information that was small enough to not exceed the cookie limit. If you find your session object is hitting these limits, it is best to consider if data in your session should be loaded from a database on the server instead of transmitted to/from the browser with every request. Or move to an [alternative session strategy](https://github.com/expressjs/session#compatible-session-stores) ## License [MIT](https://github.com/expressjs/cookie-session/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/cookie-session --- ## cors middleware URL: https://expressjs.com/en/resources/middleware/cors CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server. **How CORS Works:** This package sets response headers—it doesn't block requests. CORS is enforced by browsers: they check the headers and decide if JavaScript can read the response. Non-browser clients (curl, Postman, other servers) ignore CORS entirely. See the [MDN CORS guide](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) for details. - [Installation](#installation) - [Usage](#usage) - [Simple Usage](#simple-usage-enable-all-cors-requests) - [Enable CORS for a Single Route](#enable-cors-for-a-single-route) - [Configuring CORS](#configuring-cors) - [Configuring CORS w/ Dynamic Origin](#configuring-cors-w-dynamic-origin) - [Enabling CORS Pre-Flight](#enabling-cors-pre-flight) - [Customizing CORS Settings Dynamically per Request](#customizing-cors-settings-dynamically-per-request) - [Configuration Options](#configuration-options) - [Common Misconceptions](#common-misconceptions) - [License](#license) - [Original Author](#original-author) ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/downloading-and-installing-packages-locally): `cors` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## Usage ### Simple Usage (Enable _All_ CORS Requests) ```javascript var express = require('express'); var cors = require('cors'); var app = express(); // Adds headers: Access-Control-Allow-Origin: * app.use(cors()); app.get('/products/:id', function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ### Enable CORS for a Single Route ```javascript var express = require('express'); var cors = require('cors'); var app = express(); // Adds headers: Access-Control-Allow-Origin: * app.get('/products/:id', cors(), function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ### Configuring CORS See the [configuration options](#configuration-options) for details. ```javascript var express = require('express'); var cors = require('cors'); var app = express(); var corsOptions = { origin: 'http://example.com', optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204 }; // Adds headers: Access-Control-Allow-Origin: http://example.com, Vary: Origin app.get('/products/:id', cors(corsOptions), function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ### Configuring CORS w/ Dynamic Origin This module supports validating the origin dynamically using a function provided to the `origin` option. This function will be passed a string that is the origin (or `undefined` if the request has no origin), and a `callback` with the signature `callback(error, origin)`. The `origin` argument to the callback can be any value allowed for the `origin` option of the middleware, except a function. See the [configuration options](#configuration-options) section for more information on all the possible value types. This function is designed to allow the dynamic loading of allowed origin(s) from a backing datasource, like a database. ```javascript var express = require('express'); var cors = require('cors'); var app = express(); var corsOptions = { origin: function (origin, callback) { // db.loadOrigins is an example call to load // a list of origins from a backing database db.loadOrigins(function (error, origins) { callback(error, origins); }); }, }; // Adds headers: Access-Control-Allow-Origin: , Vary: Origin app.get('/products/:id', cors(corsOptions), function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ### Enabling CORS Pre-Flight Certain CORS requests are considered 'complex' and require an initial `OPTIONS` request (called the "pre-flight request"). An example of a 'complex' CORS request is one that uses an HTTP verb other than GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable pre-flighting, you must add a new OPTIONS handler for the route you want to support: ```javascript var express = require('express'); var cors = require('cors'); var app = express(); app.options('/products/:id', cors()); // preflight for DELETE app.delete('/products/:id', cors(), function (req, res, next) { res.json({ msg: 'Hello' }); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` You can also enable pre-flight across-the-board like so: ```javascript app.options('*', cors()); // include before other routes ``` NOTE: When using this middleware as an application level middleware (for example, `app.use(cors())`), pre-flight requests are already handled for all routes. ### Customizing CORS Settings Dynamically per Request For APIs that require different CORS configurations for specific routes or requests, you can dynamically generate CORS options based on the incoming request. The `cors` middleware allows you to achieve this by passing a function instead of static options. This function is called for each incoming request and must use the callback pattern to return the appropriate CORS options. The function accepts: 1. **`req`**: - The incoming request object. 2. **`callback(error, corsOptions)`**: - A function used to return the computed CORS options. - **Arguments**: - **`error`**: Pass `null` if there’s no error, or an error object to indicate a failure. - **`corsOptions`**: An object specifying the CORS policy for the current request. Here’s an example that handles both public routes and restricted, credential-sensitive routes: ```javascript var dynamicCorsOptions = function (req, callback) { var corsOptions; if (req.path.startsWith('/auth/connect/')) { // Access-Control-Allow-Origin: http://mydomain.com, Access-Control-Allow-Credentials: true, Vary: Origin corsOptions = { origin: 'http://mydomain.com', credentials: true, }; } else { // Access-Control-Allow-Origin: * corsOptions = { origin: '*' }; } callback(null, corsOptions); }; app.use(cors(dynamicCorsOptions)); app.get('/auth/connect/twitter', function (req, res) { res.send('Hello'); }); app.get('/public', function (req, res) { res.send('Hello'); }); app.listen(80, function () { console.log('web server listening on port 80'); }); ``` ## Configuration Options - `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Possible values: - `Boolean` - set `origin` to `true` to reflect the [request origin](https://datatracker.ietf.org/doc/html/draft-abarth-origin-09), as defined by `req.header('Origin')`, or set it to `false` to disable CORS. - `String` - set `origin` to a specific origin. For example, if you set it to - `"http://example.com"` only requests from "http://example.com" will be allowed. - `"*"` for all domains to be allowed. - `RegExp` - set `origin` to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern `/example\.com$/` will reflect any request that is coming from an origin ending with "example.com". - `Array` - set `origin` to an array of valid origins. Each origin can be a `String` or a `RegExp`. For example `["http://example1.com", /\.example2\.com$/]` will accept any request from "http://example1.com" or from a subdomain of "example2.com". - `Function` - set `origin` to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (called as `callback(err, origin)`, where `origin` is a non-function value of the `origin` option) as the second. - `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: `['GET', 'PUT', 'POST']`). - `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: `['Content-Type', 'Authorization']`). If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header. - `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: `['Content-Range', 'X-Content-Range']`). If not specified, no custom headers are exposed. - `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted. - `maxAge`: Configures the **Access-Control-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted. - `preflightContinue`: Pass the CORS preflight response to the next handler. - `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`. The default configuration is the equivalent of: ```json { "origin": "*", "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", "preflightContinue": false, "optionsSuccessStatus": 204 } ``` ## Common Misconceptions ### "CORS blocks requests from disallowed origins" **No.** Your server receives and processes every request. CORS headers tell the browser whether JavaScript can read the response—not whether the request is allowed. ### "CORS protects my API from unauthorized access" **No.** CORS is not access control. Any HTTP client (curl, Postman, another server) can call your API regardless of CORS settings. Use authentication and authorization to protect your API. ### "Setting `origin: 'http://example.com'` means only that domain can access my server" **No.** It means browsers will only let JavaScript from that origin read responses. The server still responds to all requests. ## License [MIT License](http://www.opensource.org/licenses/mit-license.php) ## Original Author [Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com)) [downloads-url]: https://npmjs.com/package/cors [github-actions-ci-url]: https://github.com/expressjs/cors?query=workflow%3Aci [npm-url]: https://npmjs.com/package/cors --- ## errorhandler middleware URL: https://expressjs.com/en/resources/middleware/errorhandler Development-only error handler middleware. This middleware is only intended to be used in a development environment, as the _full error stack traces and internal details of any object passed to this module_ will be sent back to the client when an error occurs. When an object is provided to Express as an error, this module will display as much about this object as possible, and will do so by using content negotiation for the response between HTML, JSON, and plain text. - When the object is a standard `Error` object, the string provided by the `stack` property will be returned in HTML/text responses. - When the object is a non-`Error` object, the result of [util.inspect](https://nodejs.org/api/util.html#util_util_inspect_object_options) will be returned in HTML/text responses. - For JSON responses, the result will be an object with all enumerable properties from the object in the response. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `errorhandler` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API {/* eslint-disable no-unused-vars */} ```js var errorhandler = require('errorhandler'); ``` ### errorhandler(options) Create new middleware to handle errors and respond with content negotiation. #### Options Error handler accepts these properties in the options object. ##### log Provide a function to be called with the error and a string representation of the error. Can be used to write the error to any desired location, or set to `false` to only send the error back in the response. Called as `log(err, str, req, res)` where `err` is the `Error` object, `str` is a string representation of the error, `req` is the request object and `res` is the response object (note, this function is invoked _after_ the response has been written). The default value for this option is `true` unless `process.env.NODE_ENV === 'test'`. Possible values: - `true`: Log errors using `console.error(str)`. - `false`: Only send the error back in the response. - A function: pass the error to a function for handling. ## Examples ### Simple example Basic example of adding this middleware as the error handler only in development with `connect` (`express` also can be used in this example). ```js var connect = require('connect'); var errorhandler = require('errorhandler'); var app = connect(); // assumes NODE_ENV is set by the user if (process.env.NODE_ENV === 'development') { // only use in development app.use(errorhandler()); } ``` ### Custom output location Sometimes you may want to output the errors to a different location than STDERR during development, like a system notification, for example. {/* eslint-disable handle-callback-err */} ```js var connect = require('connect'); var errorhandler = require('errorhandler'); var notifier = require('node-notifier'); var app = connect(); // assumes NODE_ENV is set by the user if (process.env.NODE_ENV === 'development') { // only use in development app.use(errorhandler({ log: errorNotification })); } function errorNotification(err, str, req) { var title = 'Error in ' + req.method + ' ' + req.url; notifier.notify({ title: title, message: str, }); } ``` ## License [MIT](https://github.com/expressjs/errorhandler/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/errorhandler --- ## method-override middleware URL: https://expressjs.com/en/resources/middleware/method-override Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `method-override` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API **NOTE** It is very important that this module is used **before** any module that needs to know the method of the request (for example, it _must_ be used prior to the `csurf` module). ### methodOverride(getter, options) Create a new middleware function to override the `req.method` property with a new value. This value will be pulled from the provided `getter`. - `getter` - The getter to use to look up the overridden request method for the request. (default: `X-HTTP-Method-Override`) - `options.methods` - The allowed methods the original request must be in to check for a method override value. (default: `['POST']`) If the found method is supported by node.js core, then `req.method` will be set to this value, as if it has originally been that value. The previous `req.method` value will be stored in `req.originalMethod`. #### getter This is the method of getting the override value from the request. If a function is provided, the `req` is passed as the first argument, the `res` as the second argument and the method is expected to be returned. If a string is provided, the string is used to look up the method with the following rules: - If the string starts with `X-`, then it is treated as the name of a header and that header is used for the method override. If the request contains the same header multiple times, the first occurrence is used. - All other strings are treated as a key in the URL query string. #### options.methods This allows the specification of what methods(s) the request _MUST_ be in in order to check for the method override value. This defaults to only `POST` methods, which is the only method the override should arrive in. More methods may be specified here, but it may introduce security issues and cause weird behavior when requests travel through caches. This value is an array of methods in upper-case. `null` can be specified to allow all methods. ## Examples ### override using a header To use a header to override the method, specify the header name as a string argument to the `methodOverride` function. To then make the call, send a `POST` request to a URL with the overridden method as the value of that header. This method of using a header would typically be used in conjunction with `XMLHttpRequest` on implementations that do not support the method you are trying to use. ```js const express = require('express'); const methodOverride = require('method-override'); const app = express(); // override with the X-HTTP-Method-Override header in the request app.use(methodOverride('X-HTTP-Method-Override')); ``` Example call with header override using `XMLHttpRequest`: {/* eslint-env browser */} ```js const xhr = new XMLHttpRequest(); xhr.onload = onload; xhr.open('post', '/resource', true); xhr.setRequestHeader('X-HTTP-Method-Override', 'DELETE'); xhr.send(); function onload() { alert('got response: ' + this.responseText); } ``` ### override using a query value To use a query string value to override the method, specify the query string key as a string argument to the `methodOverride` function. To then make the call, send a `POST` request to a URL with the overridden method as the value of that query string key. This method of using a query value would typically be used in conjunction with plain HTML `
` elements when trying to support legacy browsers but still use newer methods. ```js const express = require('express'); const methodOverride = require('method-override'); const app = express(); // override with POST having ?_method=DELETE app.use(methodOverride('_method')); ``` Example call with query override using HTML ``: ```html
``` ### multiple format support ```js const express = require('express'); const methodOverride = require('method-override'); const app = express(); // override with different headers; last one takes precedence app.use(methodOverride('X-HTTP-Method')); // Microsoft app.use(methodOverride('X-HTTP-Method-Override')); // Google/GData app.use(methodOverride('X-Method-Override')); // IBM ``` ### custom logic You can implement any kind of custom logic with a function for the `getter`. The following implements the logic for looking in `req.body` that was in `method-override@1`: ```js const bodyParser = require('body-parser'); const express = require('express'); const methodOverride = require('method-override'); const app = express(); // NOTE: when using req.body, you must fully parse the request body // before you call methodOverride() in your middleware stack, // otherwise req.body will not be populated. app.use(bodyParser.urlencoded()); app.use( methodOverride(function (req, res) { if (req.body && typeof req.body === 'object' && '_method' in req.body) { // look in urlencoded POST bodies and delete it const method = req.body._method; delete req.body._method; return method; } }) ); ``` Example call with query override using HTML `
`: ```html {/* enctype must be set to the type you will parse before methodOverride() */}
``` ## License [MIT](https://github.com/expressjs/method-override/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/method-override [downloads-url]: https://npmjs.org/package/method-override --- ## morgan middleware URL: https://expressjs.com/en/resources/middleware/morgan HTTP request logger middleware for node.js > Named after [Dexter](https://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion. ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `morgan` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API For ES Modules: {/* eslint-disable no-unused-vars */} ```js ``` For CommonJS: {/* eslint-disable no-unused-vars */} ```js var morgan = require('morgan'); ``` ### morgan(format, options) Create a new morgan logger middleware function using the given `format` and `options`. The `format` argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry. The `format` function will be called with three arguments `tokens`, `req`, and `res`, where `tokens` is an object with all defined tokens, `req` is the HTTP request and `res` is the HTTP response. The function is expected to return a string that will be the log line, or `undefined` / `null` to skip logging. #### Using a predefined format string {/* eslint-disable no-undef */} ```js morgan('tiny'); ``` #### Using format string of predefined tokens {/* eslint-disable no-undef */} ```js morgan(':method :url :status :res[content-length] - :response-time ms'); ``` #### Using a custom format function {/* eslint-disable no-undef */} ```js morgan(function (tokens, req, res) { return [ tokens.method(req, res), tokens.url(req, res), tokens.status(req, res), tokens.res(req, res, 'content-length'), '-', tokens['response-time'](req, res), 'ms', ].join(' '); }); ``` #### Options Morgan accepts these properties in the options object. ##### immediate Write log line on request instead of response. This means that requests will be logged even if the server crashes, _but data from the response (like the response code, content length, etc.) cannot be logged_. ##### skip Function to determine if logging is skipped, defaults to `false`. This function will be called as `skip(req, res)`. {/* eslint-disable no-undef */} ```js // EXAMPLE: only log error responses morgan('combined', { skip: function (req, res) { return res.statusCode < 400; }, }); ``` ##### stream Output stream for writing log lines, defaults to `process.stdout`. If the stream is in object mode (`stream.writableObjectMode` is `true`) and the format function returns an object, the object is written to the stream as-is, without a trailing newline. This allows passing structured log entries to loggers that accept objects: {/* eslint-disable no-undef */} ```js morgan( function (tokens, req, res) { return { method: tokens.method(req, res), url: tokens.url(req, res), status: Number(tokens.status(req, res)), }; }, { stream: { writableObjectMode: true, write: function (entry) { // entry is the object returned by the format function }, }, } ); ``` #### Predefined Formats There are various pre-defined formats provided: ##### combined Standard Apache combined log output. ``` :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" # will output ::1 - - [27/Nov/2024:06:21:42 +0000] "GET /combined HTTP/1.1" 200 2 "-" "curl/8.7.1" ``` ##### common Standard Apache common log output. ``` :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] # will output ::1 - - [27/Nov/2024:06:21:46 +0000] "GET /common HTTP/1.1" 200 2 ``` ##### dev Concise output colored by response status for development use. The `:status` token will be colored green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for information codes. ``` :method :url :status :response-time ms - :res[content-length] # will output GET /dev 200 0.224 ms - 2 ``` Coloring is disabled when the [`NO_COLOR`](https://no-color.org) environment variable is set to any non-empty value, in which case the output above is written without any escape sequences. The variable is read once, when `morgan` is first required. ##### short Shorter than default, also including response time. ``` :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms # will output ::1 - GET /short HTTP/1.1 200 2 - 0.283 ms ``` ##### tiny The minimal output. ``` :method :url :status :res[content-length] - :response-time ms # will output GET /tiny 200 2 - 0.188 ms ``` #### Tokens ##### Creating new tokens To define a token, simply invoke `morgan.token()` with the name and a callback function. This callback function is expected to return a string value. The value returned is then available as ":type" in this case: {/* eslint-disable no-undef */} ```js morgan.token('type', function (req, res) { return req.headers['content-type']; }); ``` Calling `morgan.token()` using the same name as an existing token will overwrite that token definition. The token function is expected to be called with the arguments `req` and `res`, representing the HTTP request and HTTP response. Additionally, the token can accept further arguments of its choosing to customize behavior. ##### :date[format] The current date and time in UTC. The available formats are: - `clf` for the common log format (`"10/Oct/2000:13:55:36 +0000"`) - `iso` for the common ISO 8601 date time format (`2000-10-10T13:55:36.000Z`) - `web` for the common RFC 1123 date time format (`Tue, 10 Oct 2000 13:55:36 GMT`) If no format is given, then the default is `web`. ##### :http-version The HTTP version of the request. ##### :method The HTTP method of the request. ##### :pid The process ID of the Node.js process handling the request. ##### :referrer The Referrer header of the request. This will use the standard mis-spelled Referer header if it exists, otherwise Referrer. ##### :remote-addr The remote address of the request. This will use `req.ip`, otherwise the standard `req.connection.remoteAddress` value (socket address). ##### :remote-user The user authenticated as part of Basic auth for the request. ##### :req[header] The given `header` of the request. If the header is not present, the value will be displayed as `"-"` in the log. ##### :res[header] The given `header` of the response. If the header is not present, the value will be displayed as `"-"` in the log. ##### :response-time[digits] The time between the request coming into `morgan` and when the response headers are written, in milliseconds. The `digits` argument is a number that specifies the number of digits to include on the number, defaulting to `3`, which provides microsecond precision. ##### :status The status code of the response. If the request/response cycle completes before a response was sent to the client (for example, the TCP socket closed prematurely by a client aborting the request), then the status will be empty (displayed as `"-"` in the log). ##### :total-time[digits] The time between the request coming into `morgan` and when the response has finished being written out to the connection, in milliseconds. The `digits` argument is a number that specifies the number of digits to include on the number, defaulting to `3`, which provides microsecond precision. ##### :url The URL of the request. This will use `req.originalUrl` if it exists, otherwise `req.url`. ##### :user-agent The contents of the User-Agent header of the request. ### morgan.compile(format) Compile a format string into a `format` function for use by `morgan`. A format string is a string that represents a single log line and can utilize token syntax. Tokens are referenced by `:token-name`. If tokens accept arguments, they can be passed using `[]`, for example: `:token-name[pretty]` would pass the string `'pretty'` as an argument to the token `token-name`. The function returned from `morgan.compile` takes three arguments `tokens`, `req`, and `res`, where `tokens` is an object with all defined tokens, `req` is the HTTP request and `res` is the HTTP response. The function will return a string that will be the log line, or `undefined` / `null` to skip logging. Normally formats are defined using `morgan.format(name, format)`, but for certain advanced uses, this compile function is directly available. ## Examples ### express/connect Sample app that will log all requests in the Apache combined format to STDOUT ```js var express = require('express'); var morgan = require('morgan'); var app = express(); app.use(morgan('combined')); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ### vanilla http server Sample app that will log all requests in the Apache combined format to STDOUT ```js var finalhandler = require('finalhandler'); var http = require('http'); var morgan = require('morgan'); // create "middleware" var logger = morgan('combined'); http.createServer(function (req, res) { var done = finalhandler(req, res); logger(req, res, function (err) { if (err) return done(err); // respond to request res.setHeader('content-type', 'text/plain'); res.end('hello, world!'); }); }); ``` ### write logs to a file #### single file Sample app that will log all requests in the Apache combined format to the file `access.log`. ```js var express = require('express'); var fs = require('fs'); var morgan = require('morgan'); var path = require('path'); var app = express(); // create a write stream (in append mode) var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }); // setup the logger app.use(morgan('combined', { stream: accessLogStream })); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` #### log file rotation Sample app that will log all requests in the Apache combined format to one log file per day in the `log/` directory using the [rotating-file-stream module](https://www.npmjs.com/package/rotating-file-stream). ```js var express = require('express'); var morgan = require('morgan'); var path = require('path'); var rfs = require('rotating-file-stream'); // version 2.x var app = express(); // create a rotating write stream var accessLogStream = rfs.createStream('access.log', { interval: '1d', // rotate daily path: path.join(__dirname, 'log'), }); // setup the logger app.use(morgan('combined', { stream: accessLogStream })); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ### split / dual logging The `morgan` middleware can be used as many times as needed, enabling combinations like: - Log entry on request and one on response - Log all requests to file, but errors to console - ... and more! Sample app that will log all requests to a file using Apache format, but error responses are logged to the console: ```js var express = require('express'); var fs = require('fs'); var morgan = require('morgan'); var path = require('path'); var app = express(); // log only 4xx and 5xx responses to console app.use( morgan('dev', { skip: function (req, res) { return res.statusCode < 400; }, }) ); // log all requests to access.log app.use( morgan('common', { stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }), }) ); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ### use custom token formats Sample app that will use custom token formats. This adds an ID to all requests and displays it using the `:id` token. ```js var express = require('express'); var morgan = require('morgan'); var uuid = require('uuid'); morgan.token('id', function getId(req) { return req.id; }); var app = express(); app.use(assignId); app.use(morgan(':id :method :url :response-time')); app.get('/', function (req, res) { res.send('hello, world!'); }); function assignId(req, res, next) { req.id = uuid.v4(); next(); } ``` ## License [MIT](https://github.com/expressjs/morgan/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/morgan --- ## multer middleware URL: https://expressjs.com/en/resources/middleware/multer Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written on top of [busboy](https://github.com/mscdex/busboy) for maximum efficiency. **NOTE**: Multer will not process any form which is not multipart (`multipart/form-data`). ## Installation `multer` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## Usage Multer adds a `body` object and a `file` or `files` object to the `request` object. The `body` object contains the values of the text fields of the form, the `file` or `files` object contains the files uploaded via the form. Basic usage example: Don't forget the `enctype="multipart/form-data"` in your form. ```html
``` ```javascript const express = require('express'); const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); const app = express(); app.post('/profile', upload.single('avatar'), function (req, res, next) { // req.file is the `avatar` file // req.body will hold the text fields, if there were any }); app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) { // req.files is array of `photos` files // req.body will contain the text fields, if there were any }); const uploadMiddleware = upload.fields([ { name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }, ]); app.post('/cool-profile', uploadMiddleware, function (req, res, next) { // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files // // e.g. // req.files['avatar'][0] -> File // req.files['gallery'] -> Array // // req.body will contain the text fields, if there were any }); ``` In case you need to handle a text-only multipart form, you should use the `.none()` method: ```javascript const express = require('express'); const app = express(); const multer = require('multer'); const upload = multer(); app.post('/profile', upload.none(), function (req, res, next) { // req.body contains the text fields }); ``` Here's an example on how multer is used in a HTML form. Take special note of the `enctype="multipart/form-data"` and `name="uploaded_file"` fields: ```html
``` Then in your javascript file you would add these lines to access both the file and the body. It is important that you use the `name` field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail: ```javascript const multer = require('multer'); const upload = multer({ dest: './public/data/uploads/' }); app.post('/stats', upload.single('uploaded_file'), function (req, res) { // req.file is the name of your file in the form above, here 'uploaded_file' // req.body will hold the text fields, if there were any console.log(req.file, req.body); }); ``` Complete client-side and server-side examples (browser `FormData` uploads of a blob and of an image) are in the [`examples/`](https://github.com/expressjs/multer/blob/HEAD/examples/) folder. ## API ### File information Each file contains the following information: | Key | Description | Note | | -------------- | ----------------------------------------------------------------------------------- | --------------- | | `fieldname` | Field name specified in the form | | `originalname` | Name of the file on the user's computer, or the full path when `preservePath: true` | | `encoding` | Encoding type of the file | | `mimetype` | Mime type of the file | | `size` | Size of the file in bytes | | `destination` | The folder to which the file has been saved | `DiskStorage` | | `filename` | The name of the file within the `destination` | `DiskStorage` | | `path` | The full path to the uploaded file | `DiskStorage` | | `buffer` | A `Buffer` of the entire file | `MemoryStorage` | ### `multer(opts)` Multer accepts an options object, the most basic of which is the `dest` property, which tells Multer where to upload the files. In case you omit the options object, the files will be kept in memory and never written to disk. By default, Multer will rename the files so as to avoid naming conflicts. The renaming function can be customized according to your needs. The following are the options that can be passed to Multer. | Key | Description | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `defCharset` | Default character set to use for text field values that do not declare one. Default: `'utf8'` | | `defParamCharset` | Default character set to use for values of part header parameters (e.g. filename) that are not extended parameters (that contain an explicit charset). Default: `'latin1'` | | `dest` or `storage` | Where to store the files | | `fileFilter` | Function to control which files are accepted | | `fileHwm` | `highWaterMark` of each file stream (`file.stream`). Default: busboy's default | | `highWaterMark` | `highWaterMark` of the multipart parser stream. Default: busboy's default | | `limits` | Limits of the uploaded data | | `preservePath` | Keep the full client-supplied path in `file.originalname` instead of just the base name | | `streamHandler` | Function that feeds the request body to busboy; defaults to `req.pipe(busboy)` | In an average web app, only `dest` might be required, and configured as shown in the following example. ```javascript const upload = multer({ dest: 'uploads/' }); ``` When `preservePath` is enabled, Multer passes the incoming filename through with any path segments provided by the client. This is exposed as `file.originalname`; it does not change the destination folder, create directories, or sanitize the path for you. `file.originalname` is always client-supplied and should be treated as untrusted; with `preservePath` it additionally contains the path segments the client sent. Normalize or validate it before using it in a custom `filename` or storage engine. If you want more control over your uploads, you'll want to use the `storage` option instead of `dest`. Multer ships with storage engines `DiskStorage` and `MemoryStorage`; More engines are available from third parties. #### `.single(fieldname)` Accept a single file with the name `fieldname`. The single file will be stored in `req.file`. #### `.array(fieldname[, maxCount])` Accept an array of files, all with the name `fieldname`. Optionally error out if more than `maxCount` files are uploaded. The array of files will be stored in `req.files`. Files skipped by `fileFilter` do not count towards `maxCount`. Use `limits.files` to bound how many files are read from a request. #### `.fields(fields)` Accept a mix of files, specified by `fields`. An object with arrays of files will be stored in `req.files`. `fields` should be an array of objects with `name` and optionally a `maxCount`. Example: ```javascript [ { name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }, ]; ``` #### `.none()` Accept only text fields. If any file upload is made, error with code `LIMIT_UNEXPECTED_FILE` will be issued. #### `.any()` Accepts all files that come over the wire. An array of files will be stored in `req.files`. **WARNING:** Make sure that you always handle the files that a user uploads. Never add multer as a global middleware since a malicious user could upload files to a route that you didn't anticipate. Only use this function on routes where you are handling the uploaded files. ### `storage` #### `DiskStorage` The disk storage engine gives you full control on storing files to disk. ```javascript const crypto = require('crypto'); const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, '/tmp/my-uploads'); }, filename: function (req, file, cb) { crypto.randomBytes(16, function (err, raw) { if (err) return cb(err); cb(null, file.fieldname + '-' + raw.toString('hex')); }); }, }); const upload = multer({ storage: storage }); ``` There are three options available: `destination`, `filename` and `flush`. All of them except `flush` are functions that determine where the file should be stored. `destination` is used to determine within which folder the uploaded files should be stored. This can also be given as a `string` (e.g. `'/tmp/uploads'`). If no `destination` is given, the operating system's default directory for temporary files is used. **Note:** You are responsible for creating the directory when providing `destination` as a function. When passing a string, multer will make sure that the directory is created for you. `filename` is used to determine what the file should be named inside the folder. If no `filename` is given, each file will be given a random name that doesn't include any file extension. **Note:** Multer will not append any file extension for you, your function should return a filename complete with a file extension. Each function gets passed both the request (`req`) and some information about the file (`file`) to aid with the decision. Note that `req.body` might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server. For understanding the calling convention used in the callback (needing to pass null as the first param), refer to [Node.js error handling](https://web.archive.org/web/20220417042018/https://www.joyent.com/node-js/production/design/errors) `flush` is an optional boolean. When set to `true`, the file data is flushed to disk with an `fsync` call before the upload handler runs, which prevents data loss if the process or the system crashes while the data is still sitting in the operating system's page cache. It is disabled by default because forcing a disk flush on every upload has a performance cost. Note that this syncs the file contents only; if the new directory entry must survive a crash as well, fsync the destination directory yourself. #### `MemoryStorage` The memory storage engine stores the files in memory as `Buffer` objects. It doesn't have any options. ```javascript const storage = multer.memoryStorage(); const upload = multer({ storage: storage }); ``` When using memory storage, the file info will contain a field called `buffer` that contains the entire file. **WARNING**: Uploading very large files, or relatively small files in large numbers very quickly, can cause your application to run out of memory when memory storage is used. ### `limits` An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found on [busboy's page](https://github.com/mscdex/busboy#exports). `limits` can also be a function that receives the request and returns such an object. It is called once per request, before parsing starts, so limits can depend on e.g. the authenticated user: ```javascript const upload = multer({ limits: function (req) { return { fileSize: req.user.maxUploadSize }; }, }); ``` Limits apply to the whole request; there is no per-file limit. To restrict individual files by type or name, use `fileFilter` or a custom storage engine. The following integer values are available: | Key | Description | Default | | ---------------------- | ------------------------------------------------------------------------------- | -------- | | `fieldNameSize` | Max field name size | Infinity | | `fieldSize` | Max field value size (in bytes) | 1MB | | `fields` | Max number of non-file fields | Infinity | | `fileSize` | For multipart forms, the max file size (in bytes) | Infinity | | `files` | For multipart forms, the max number of file fields | Infinity | | `parts` | For multipart forms, the max number of parts (fields + files) | Infinity | | `headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 | | `fieldNestingDepth` | Max number of nesting levels for field names (e.g. `a[b][c]` has 2 levels) | Infinity | | `fieldArrayIndexLimit` | Max numeric array index accepted inside a field name (e.g. `a[3]` uses index 3) | Infinity | Specifying the limits can help protect your site against denial of service (DoS) attacks. ### `fileFilter` Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this: ```javascript function fileFilter(req, file, cb) { // The function should call `cb` with a boolean // to indicate if the file should be accepted // To reject this file pass `false`, like so: cb(null, false); // To accept the file pass `true`, like so: cb(null, true); // You can always pass an error if something goes wrong: cb(new Error("I don't have a clue!")); } ``` ### `streamHandler` By default Multer reads the request with `req.pipe(busboy)`. Some platforms consume the request body before your handlers run, so there is nothing left to pipe. Google Cloud Functions and Firebase Functions, for example, expose the already-read body as `req.rawBody`. Provide a `streamHandler` to feed busboy yourself in that case: ```javascript const upload = multer({ storage: multer.memoryStorage(), streamHandler: function (req, busboy) { if (req.rawBody) { busboy.end(req.rawBody); } else { req.pipe(busboy); } }, }); ``` The function receives the request and the busboy instance and must write the whole multipart body to busboy and end it. ## Security Specifying the [limits](#limits) can help protect your site against denial of service (DoS) attacks. The following limits are recommended for most applications: - `fileSize` -- set to the maximum expected file size for your use case - `files` -- set to the maximum number of files per request - `fields` -- set to the maximum number of text fields per request - `fieldNestingDepth` -- set to the minimum depth your field names require (e.g. `3` for `a[b][c]`) - `fieldArrayIndexLimit` -- set to the largest array index your field names require (e.g. `100` for `a[99]`) ## Error handling When encountering an error, Multer will delegate the error to Express. You can display a nice error page using [the standard express way](/guide/error-handling/). If you want to catch errors specifically from Multer, you can call the middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/main/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`). Multer errors carry a `code` (e.g. `LIMIT_FILE_SIZE`) and, when the error concerns a specific field, its name in `field`. Errors about a specific file (`LIMIT_FILE_SIZE`, `LIMIT_UNEXPECTED_FILE`) also expose the client-supplied file name in `filename`; treat it as untrusted input, like `file.originalname`. ```javascript const multer = require('multer'); const upload = multer().single('avatar'); app.post('/profile', function (req, res) { upload(req, res, function (err) { if (err instanceof multer.MulterError) { // A Multer error occurred when uploading. } else if (err) { // An unknown error occurred when uploading. } // Everything went fine. }); }); ``` ## Custom storage engine For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/main/StorageEngine.md). ## License [MIT](https://github.com/expressjs/multer/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/multer [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/multer/badge [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/multer --- ## response-time middleware URL: https://expressjs.com/en/resources/middleware/response-time Response time for Node.js servers. This module creates a middleware that records the response time for requests in HTTP servers. The "response time" is defined here as the elapsed time from when a request enters this middleware to when the headers are written out to the client. ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `response-time` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API {/* eslint-disable no-unused-vars */} ```js var responseTime = require('response-time'); ``` ### responseTime([options]) Create a middleware that adds a `X-Response-Time` header to responses. If you don't want to use this module to automatically set a header, please see the section about [`responseTime(fn)`](#responsetimefn). #### Options The `responseTime` function accepts an optional `options` object that may contain any of the following keys: ##### digits The fixed number of digits to include in the output, which is always in milliseconds, defaults to `3` (ex: `2.300ms`). ##### header The name of the header to set, defaults to `X-Response-Time`. ##### suffix Boolean to indicate if units of measurement suffix should be added to the output, defaults to `true` (ex: `2.300ms` vs `2.300`). ### responseTime(fn) Create a new middleware that records the response time of a request and makes this available to your own function `fn`. The `fn` argument will be invoked as `fn(req, res, time)`, where `time` is a number in milliseconds. ## Examples ### express/connect ```js var express = require('express'); var responseTime = require('response-time'); var app = express(); app.use(responseTime()); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ### vanilla http server ```js var finalhandler = require('finalhandler'); var http = require('http'); var responseTime = require('response-time'); // create "middleware" var _responseTime = responseTime(); http.createServer(function (req, res) { var done = finalhandler(req, res); _responseTime(req, res, function (err) { if (err) return done(err); // respond to request res.setHeader('content-type', 'text/plain'); res.end('hello, world!'); }); }); ``` ### response time metrics ```js var express = require('express'); var responseTime = require('response-time'); var StatsD = require('node-statsd'); var app = express(); var stats = new StatsD(); stats.socket.on('error', function (error) { console.error(error.stack); }); app.use( responseTime(function (req, res, time) { var stat = (req.method + req.url).toLowerCase().replace(/[:.]/g, '').replace(/\//g, '_'); stats.timing(stat, time); }) ); app.get('/', function (req, res) { res.send('hello, world!'); }); ``` ## License [MIT](https://github.com/expressjs/response-time/blob/HEAD/LICENSE) [npm-url]: https://npmjs.org/package/response-time [node-url]: https://nodejs.org/en/download --- ## serve-favicon middleware URL: https://expressjs.com/en/resources/middleware/serve-favicon Node.js middleware for serving a favicon. A favicon is a visual cue that client software, like browsers, use to identify a site. For an example and more information, please visit [the Wikipedia article on favicons](https://en.wikipedia.org/wiki/Favicon). Why use this module? - User agents request `favicon.ico` frequently and indiscriminately, so you may wish to exclude these requests from your logs by using this middleware before your logger middleware. - This module caches the icon in memory to improve performance by skipping disk access. - This module provides an `ETag` based on the contents of the icon, rather than file system properties. - This module will serve with the most compatible `Content-Type`. **Note** This module is exclusively for serving the "default, implicit favicon", which is `GET /favicon.ico`. For additional vendor-specific icons that require HTML markup, additional middleware is required to serve the relevant files, for example [serve-static](https://npmjs.org/package/serve-static). ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `serve-favicon` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ### favicon(path, options) Create new middleware to serve a favicon from the given `path` to a favicon file. `path` may also be a `Buffer` of the icon to serve. #### Options Serve favicon accepts these properties in the options object. ##### maxAge The `cache-control` `max-age` directive in `ms`, defaulting to 1 year. This can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) module. ## Examples Typically this middleware will come very early in your stack (maybe even first) to avoid processing any other middleware if we already know the request is for `/favicon.ico`. ### express ```javascript var express = require('express'); var favicon = require('serve-favicon'); var path = require('path'); var app = express(); app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); // Add your routes here, etc. app.listen(3000); ``` ### connect ```javascript var connect = require('connect'); var favicon = require('serve-favicon'); var path = require('path'); var app = connect(); app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); // Add your middleware here, etc. app.listen(3000); ``` ### vanilla http server This middleware can be used anywhere, even outside express/connect. It takes `req`, `res`, and `callback`. ```javascript var http = require('http'); var favicon = require('serve-favicon'); var finalhandler = require('finalhandler'); var path = require('path'); var _favicon = favicon(path.join(__dirname, 'public', 'favicon.ico')); var server = http.createServer(function onRequest(req, res) { var done = finalhandler(req, res); _favicon(req, res, function onNext(err) { if (err) return done(err); // continue to process the request here, etc. res.statusCode = 404; res.end('oops'); }); }); server.listen(3000); ``` ## License [MIT](https://github.com/expressjs/serve-favicon/blob/HEAD/LICENSE) [downloads-url]: https://npmjs.org/package/serve-favicon [npm-url]: https://npmjs.org/package/serve-favicon [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/serve-favicon/badge [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/serve-favicon --- ## serve-index middleware URL: https://expressjs.com/en/resources/middleware/serve-index Serves pages that contain directory listings for a given path. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `serve-index` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var serveIndex = require('serve-index'); ``` ### serveIndex(path, options) Returns middleware that serves an index of the directory in the given `path`. The `path` is based off the `req.url` value, so a `req.url` of `'/some/dir` with a `path` of `'public'` will look at `'public/some/dir'`. If you are using something like `express`, you can change the URL "base" with `app.use` (see the express example). #### Options Serve index accepts these properties in the options object. ##### filter Apply this filter function to files. Defaults to `false`. The `filter` function is called for each file, with the signature `filter(filename, index, files, dir)` where `filename` is the name of the file, `index` is the array index, `files` is the array of files and `dir` is the absolute path the file is located (and thus, the directory the listing is for). ##### hidden Display hidden (dot) files. Defaults to `false`. ##### icons Display icons. Defaults to `false`. ##### stylesheet Optional path to a CSS stylesheet. Defaults to a built-in stylesheet. ##### template Optional path to an HTML template or a function that will render a HTML string. Defaults to a built-in template. When given a string, the string is used as a file path to load and then the following tokens are replaced in templates: - `{directory}` with the name of the directory. - `{files}` with the HTML of an unordered list of file links. - `{linked-path}` with the HTML of a link to the directory. - `{style}` with the specified stylesheet and embedded images. When given as a function, the function is called as `template(locals, callback)` and it needs to invoke `callback(error, htmlString)`. The following are the provided locals: - `directory` is the directory being displayed (where `/` is the root). - `displayIcons` is a Boolean for if icons should be rendered or not. - `fileList` is a sorted array of files in the directory. The array contains objects with the following properties: - `name` is the relative name for the file. - `stat` is a `fs.Stats` object for the file. - `path` is the full filesystem path to `directory`. - `style` is the default stylesheet or the contents of the `stylesheet` option. - `viewName` is the view name provided by the `view` option. ##### view Display mode. `tiles` and `details` are available. Defaults to `tiles`. ## Examples ### Serve directory indexes with vanilla node.js http server ```js var finalhandler = require('finalhandler'); var http = require('http'); var serveIndex = require('serve-index'); var serveStatic = require('serve-static'); // Serve directory indexes for public/ftp folder (with icons) var index = serveIndex('public/ftp', { icons: true }); // Serve up public/ftp folder files var serve = serveStatic('public/ftp'); // Create server var server = http.createServer(function onRequest(req, res) { var done = finalhandler(req, res); serve(req, res, function onNext(err) { if (err) return done(err); index(req, res, done); }); }); // Listen server.listen(3000); ``` ### Serve directory indexes with express ```js var express = require('express'); var serveIndex = require('serve-index'); var app = express(); // Serve URLs like /ftp/thing as public/ftp/thing // The express.static serves the file contents // The serveIndex is this module serving the directory app.use('/ftp', express.static('public/ftp'), serveIndex('public/ftp', { icons: true })); // Listen app.listen(3000); ``` ## License [MIT](https://github.com/expressjs/serve-index/blob/HEAD/LICENSE). The [Silk](https://web.archive.org/web/20230105212205/http://www.famfamfam.com/lab/icons/silk/) icons are created by/copyright of [FAMFAMFAM](https://web.archive.org/web/20230109095739/http://www.famfamfam.com/). [appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-index [downloads-url]: https://npmjs.org/package/serve-index [npm-url]: https://npmjs.org/package/serve-index --- ## serve-static middleware URL: https://expressjs.com/en/resources/middleware/serve-static ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `serve-static` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js const serveStatic = require('serve-static'); ``` ### serveStatic(root, options) Create a new middleware function to serve files from within a given root directory. The file to serve will be determined by combining `req.url` with the provided root directory. When a file is not found, instead of sending a 404 response, this module will instead call `next()` to move on to the next middleware, allowing for stacking and fall-backs. #### Options ##### acceptRanges Enable or disable accepting ranged requests, defaults to true. Disabling this will not send `Accept-Ranges` and ignore the contents of the `Range` request header. ##### cacheControl Enable or disable setting `Cache-Control` response header, defaults to true. Disabling this will ignore the `immutable` and `maxAge` options. ##### dotfiles Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). Note this check is done on the path itself without checking if the path actually exists on the disk. If `root` is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when set to "deny"). - `'allow'` No special treatment for dotfiles. - `'deny'` Deny a request for a dotfile and 403/`next()`. - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. The default value is `'ignore'`. ##### etag Enable or disable etag generation, defaults to true. ##### extensions Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for. The first that exists will be served. Example: `['html', 'htm']`. The default value is `false`. ##### fallthrough Set the middleware to have client errors fall-through as just unhandled requests, otherwise forward a client error. The difference is that client errors like a bad request or a request to a non-existent file will cause this middleware to simply `next()` to your next middleware when this value is `true`. When this value is `false`, these errors (even 404s), will invoke `next(err)`. Typically `true` is desired such that multiple physical directories can be mapped to the same web address or for routes to fill in non-existent files. The value `false` can be used if this middleware is mounted at a path that is designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods. The default value is `true`. ##### immutable Enable or disable the `immutable` directive in the `Cache-Control` response header, defaults to `false`. If set to `true`, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. ##### index By default this module will send "index.html" files in response to a request on a directory. To disable this set `false` or to supply a new index pass a string or an array in preferred order. ##### lastModified Enable or disable `Last-Modified` header, defaults to true. Uses the file system's last modified value. ##### maxAge Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) module. ##### redirect Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. ##### setHeaders Function to set custom headers on response. Alterations to the headers need to occur synchronously. The function is called as `fn(res, path, stat)`, where the arguments are: - `res` the response object - `path` the file path that is being sent - `stat` the stat object of the file that is being sent ## Examples ### Serve files with vanilla node.js http server ```js const finalhandler = require('finalhandler'); const http = require('http'); const serveStatic = require('serve-static'); // Serve up public/ftp folder const serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] }); // Create server const server = http.createServer((req, res) => { serve(req, res, finalhandler(req, res)); }); // Listen server.listen(3000); ``` ### Serve all files as downloads ```js const contentDisposition = require('content-disposition'); const finalhandler = require('finalhandler'); const http = require('http'); const serveStatic = require('serve-static'); // Serve up public/ftp folder const serve = serveStatic('public/ftp', { index: false, setHeaders: setHeaders, }); // Set header to force download function setHeaders(res, path) { res.setHeader('Content-Disposition', contentDisposition(path)); } // Create server const server = http.createServer((req, res) => { serve(req, res, finalhandler(req, res)); }); // Listen server.listen(3000); ``` ### Serving using express #### Simple This is a simple example of using Express. ```js const express = require('express'); const serveStatic = require('serve-static'); const app = express(); app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] })); app.listen(3000); ``` #### Multiple roots This example shows a simple way to search through multiple directories. Files are searched for in `public-optimized/` first, then `public/` second as a fallback. ```js const express = require('express'); const path = require('path'); const serveStatic = require('serve-static'); const app = express(); app.use(serveStatic(path.join(__dirname, 'public-optimized'))); app.use(serveStatic(path.join(__dirname, 'public'))); app.listen(3000); ``` #### Different settings for paths This example shows how to set a different max age depending on the served file. In this example, HTML files are not cached, while everything else is for 1 day. ```js const express = require('express'); const path = require('path'); const serveStatic = require('serve-static'); const app = express(); app.use( serveStatic(path.join(__dirname, 'public'), { maxAge: '1d', setHeaders: setCustomCacheControl, }) ); app.listen(3000); function setCustomCacheControl(res, file) { if (path.extname(file) === '.html') { // Custom Cache-Control for HTML files res.setHeader('Cache-Control', 'public, max-age=0'); } } ``` ## License [MIT](https://github.com/expressjs/serve-static/blob/HEAD/LICENSE) [node-url]: https://nodejs.org/en/download/ [npm-url]: https://npmjs.org/package/serve-static --- ## session middleware URL: https://expressjs.com/en/resources/middleware/session ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): `express-session` does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) as a development dependency: ## API ```js var session = require('express-session'); ``` ### session(options) Create a session middleware with the given `options`. **Note** Session data is _not_ saved in the cookie itself, just the session ID. Session data is stored server-side. **Note** Since version 1.5.0, the [`cookie-parser` middleware](https://www.npmjs.com/package/cookie-parser) no longer needs to be used for this module to work. This module now directly reads and writes cookies on `req`/`res`. Using `cookie-parser` may result in issues if the `secret` is not the same between this module and `cookie-parser`. **Warning** The default server-side session storage, `MemoryStore`, is _purposely_ not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing. For a list of stores, see [compatible session stores](#compatible-session-stores). #### Options `express-session` accepts these properties in the options object. ##### cookie Settings object for the session ID cookie. The default value is `{ path: '/', httpOnly: true, secure: false, maxAge: null }`. In addition to providing a static object, you can also pass a callback function to dynamically generate the cookie options for each request. The callback receives the `req` object as its argument and should return an object containing the cookie settings. ```js var app = express(); app.use( session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: function (req) { var match = req.url.match(/^\/([^/]+)/); return { path: match ? '/' + match[1] : '/', httpOnly: true, secure: req.secure || false, maxAge: 60000, }; }, }) ); ``` The following are options that can be set in this object. ##### cookie.domain Specifies the value for the `Domain` `Set-Cookie` attribute. By default, no domain is set, and most clients will consider the cookie to apply to only the current domain. ##### cookie.expires Specifies the `Date` object to be the value for the `Expires` `Set-Cookie` attribute. By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application. **Note** If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used. **Note** The `expires` option should not be set directly; instead only use the `maxAge` option. ##### cookie.httpOnly Specifies the `boolean` value for the `HttpOnly` `Set-Cookie` attribute. When truthy, the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is set. **Note** be careful when setting this to `true`, as compliant clients will not allow client-side JavaScript to see the cookie in `document.cookie`. ##### cookie.maxAge Specifies the `number` (in milliseconds) to use when calculating the `Expires` `Set-Cookie` attribute. This is done by taking the current server time and adding `maxAge` milliseconds to the value to calculate an `Expires` datetime. By default, no maximum age is set. **Note** If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used. ##### cookie.partitioned Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`][rfc-cutler-httpbis-partitioned-cookies] attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the `Partitioned` attribute is not set. **Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it. More information about can be found in [the proposal](https://github.com/privacycg/CHIPS). ##### cookie.path Specifies the value for the `Path` `Set-Cookie`. By default, this is set to `'/'`, which is the root path of the domain. Since 1.19.1, path matching follows [RFC 6265 section 5.1.4][rfc-6265-5.1.4]. This means the session middleware will only activate when the request path is an exact match or falls under a segment boundary of the cookie path. For example, a cookie path of `/admin` will match `/admin` and `/admin/users` but will **not** match `/administrator`. Prior versions used a simple prefix check that did not enforce segment boundaries. ##### cookie.priority Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1]. - `'low'` will set the `Priority` attribute to `Low`. - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. - `'high'` will set the `Priority` attribute to `High`. More information about the different priority levels can be found in [the specification][rfc-west-cookie-priority-00-4.1]. **Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it. ##### cookie.sameSite Specifies the `boolean` or `string` to be the value for the `SameSite` `Set-Cookie` attribute. By default, this is `false`. - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. - `false` will not set the `SameSite` attribute. - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. - `'auto'` will set the `SameSite` attribute to `None` for secure connections and `Lax` for non-secure connections. More information about the different enforcement levels can be found in [the specification][rfc-6265bis-03-4.1.2.7]. **Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it. **Note** There is a [draft spec](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01) that requires that the `Secure` attribute be set to `true` when the `SameSite` attribute has been set to `'none'`. Some web browsers or other clients may be adopting this specification. The `cookie.sameSite` option can also be set to the special value `'auto'` to have this setting automatically match the determined security of the connection. When the connection is secure (HTTPS), the `SameSite` attribute will be set to `None` to enable cross-site usage. When the connection is not secure (HTTP), the `SameSite` attribute will be set to `Lax` for better security while maintaining functionality. This is useful when the Express `"trust proxy"` setting is properly setup to simplify development vs production configuration, particularly for SAML authentication scenarios. ##### cookie.secure Specifies the `boolean` value for the `Secure` `Set-Cookie` attribute. When truthy, the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. **Note** be careful when setting this to `true`, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection. Please note that `secure: true` is a **recommended** option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If `secure` is set, and you access your site over HTTP, the cookie will not be set. If you have your node.js behind a proxy and are using `secure: true`, you need to set "trust proxy" in express: ```js var app = express(); app.set('trust proxy', 1); // trust first proxy app.use( session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true }, }) ); ``` For using secure cookies in production, but allowing for testing in development, the following is an example of enabling this setup based on `NODE_ENV` in express: ```js var app = express(); var sess = { secret: 'keyboard cat', cookie: {}, }; if (app.get('env') === 'production') { app.set('trust proxy', 1); // trust first proxy sess.cookie.secure = true; // serve secure cookies } app.use(session(sess)); ``` The `cookie.secure` option can also be set to the special value `'auto'` to have this setting automatically match the determined security of the connection. Be careful when using this setting if the site is available both as HTTP and HTTPS, as once the cookie is set on HTTPS, it will no longer be visible over HTTP. This is useful when the Express `"trust proxy"` setting is properly setup to simplify development vs production configuration. ##### genid Function to call to generate a new session ID. Provide a function that returns a string that will be used as a session ID. The function is given `req` as the first argument if you want to use some value attached to `req` when generating the ID. The default value is a function which uses the `uid-safe` library to generate IDs. **NOTE** be careful to generate unique IDs so your sessions do not conflict. ```js app.use( session({ genid: function (req) { return genuuid(); // use UUIDs for session IDs }, secret: 'keyboard cat', }) ); ``` ##### name The name of the session ID cookie to set in the response (and read from in the request). The default value is `'connect.sid'`. **Note** if you have multiple apps running on the same hostname (this is just the name, i.e. `localhost` or `127.0.0.1`; different schemes and ports do not name a different hostname), then you need to separate the session cookies from each other. The simplest method is to simply set different `name`s per app. ##### proxy Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto" header). The default value is `undefined`. - `true` The "X-Forwarded-Proto" header will be used. - `false` All headers are ignored and the connection is considered secure only if there is a direct TLS/SSL connection. - `undefined` Uses the "trust proxy" setting from express ##### resave Forces the session to be saved back to the session store, even if the session was never modified during the request. Depending on your store this may be necessary, but it can also create race conditions where a client makes two parallel requests to your server and changes made to the session in one request may get overwritten when the other request ends, even if it made no changes (this behavior also depends on what store you're using). The default value is `true`, but using the default has been deprecated, as the default will change in the future. Please research into this setting and choose what is appropriate to your use-case. Typically, you'll want `false`. How do I know if this is necessary for my store? The best way to know is to check with your store if it implements the `touch` method. If it does, then you can safely set `resave: false`. If it does not implement the `touch` method and your store sets an expiration date on stored sessions, then you likely need `resave: true`. ##### rolling Force the session identifier cookie to be set on every response. The expiration is reset to the original [`maxAge`](#cookiemaxage), resetting the expiration countdown. The default value is `false`. With this enabled, the session identifier cookie will expire in [`maxAge`](#cookiemaxage) since the last response was sent instead of in [`maxAge`](#cookiemaxage) since the session was last modified by the server. This is typically used in conjunction with short, non-session-length [`maxAge`](#cookiemaxage) values to provide a quick timeout of the session data with reduced potential of it occurring during on going server interactions. **Note** When this option is set to `true` but the `saveUninitialized` option is set to `false`, the cookie will not be set on a response with an uninitialized session. This option only modifies the behavior when an existing session was loaded for the request. ##### saveUninitialized Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified. Choosing `false` is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie. Choosing `false` will also help with race conditions where a client makes multiple parallel requests without a session. The default value is `true`, but using the default has been deprecated, as the default will change in the future. Please research into this setting and choose what is appropriate to your use-case. **Note** if you are using Session in conjunction with PassportJS, Passport will add an empty Passport object to the session for use after a user is authenticated, which will be treated as a modification to the session, causing it to be saved. _This has been fixed in PassportJS 0.3.0_ ##### secret **Required option** This is the secret used to sign the session ID cookie. The secret can be any type of value that is supported by Node.js `crypto.createHmac` (like a string or a `Buffer`). This can be either a single secret, or an array of multiple secrets. If an array of secrets is provided, only the first element will be used to sign the session ID cookie, while all the elements will be considered when verifying the signature in requests. The secret itself should be not easily parsed by a human and would best be a random set of characters. A best practice may include: - The use of environment variables to store the secret, ensuring the secret itself does not exist in your repository. - Periodic updates of the secret, while ensuring the previous secret is in the array. Using a secret that cannot be guessed will reduce the ability to hijack a session to only guessing the session ID (as determined by the `genid` option). Changing the secret value will invalidate all existing sessions. In order to rotate the secret without invalidating sessions, provide an array of secrets, with the new secret as first element of the array, and including previous secrets as the later elements. **Note** HMAC-256 is used to sign the session ID. For this reason, the secret should contain at least 32 bytes of entropy. ##### store The session store instance, defaults to a new `MemoryStore` instance. ##### unset Control the result of unsetting `req.session` (through `delete`, setting to `null`, etc.). The default value is `'keep'`. - `'destroy'` The session will be destroyed (deleted) when the response ends. - `'keep'` The session in the store will be kept, but modifications made during the request are ignored and not saved. ### req.session To store or access session data, simply use the request property `req.session`, which is (generally) serialized as JSON by the store, so nested objects are typically fine. For example below is a user-specific view counter: ```js // Use the session middleware app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 } })); // Access the session as req.session app.get('/', function (req, res, next) { if (req.session.views) { req.session.views++; res.setHeader('Content-Type', 'text/html'); res.write('

views: ' + req.session.views + '

'); res.write('

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

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