# Express.js — Guides (v5) > 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). --- ## 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`. --- ## 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.