# Express.js — API Reference (v5)
> Fast, unopinionated, minimalist web framework for Node.js
---
## 5.x API Reference
URL: https://expressjs.com/en/5x/api
This section provides an overview of the modules and APIs available in Express 5.x for building web applications and HTTP services.
```cjs title="index.cjs"
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('hello world');
});
app.listen(3000);
```
```mjs title="index.mjs"
const app = express();
app.get('/', (req, res) => {
res.send('hello world');
});
app.listen(3000);
```
```ts title="index.ts"
const app: Express = express();
app.get('/', (req: Request, res: Response) => {
res.send('hello world');
});
app.listen(3000);
```
Express 5.x requires **Node.js 18 or higher**.
With express v5.x, you can define routes, configure middleware, and start handling HTTP requests using the application instance created by the `express()` function. The API is organized into the following sections:
---
## Application Object
URL: https://expressjs.com/en/5x/api/application
The `app` object conventionally denotes the Express application.
Create it by calling the top-level `express()` function exported by the Express module:
```cjs title="index.cjs"
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('hello world');
});
app.listen(3000);
```
```mjs title="index.mjs"
const app = express();
app.get('/', function (req, res) {
res.send('hello world');
});
app.listen(3000);
```
```ts title="index.ts"
const app: Express = express();
app.get('/', function (req: Request, res: Response) {
res.send('hello world');
});
app.listen(3000);
```
The `app` object has methods for
- Routing HTTP requests; see for example, [app.METHOD](#appmethod) and [app.param](#appparam).
- Configuring middleware; see [app.route](#approute).
- Rendering HTML views; see [app.render](#apprender).
- Registering a template engine; see [app.engine](#appengine).
It also has settings (properties) that affect how the application behaves;
for more information, see [Application settings](#application-settings).
The Express application object can be referred from the [request object](/api/request/) and the [response object](/api/response/) as `req.app`, and `res.app`, respectively.
## Properties
### app.locals
Type: Object.
The `app.locals` object has properties that are local variables within the application,
and will be available in templates rendered with [res.render](/api/response/#resrender).
The `locals` object is used by view engines to render a response. The object keys may be
particularly sensitive and should not contain user-controlled input, as it may affect the
operation of the view engine or provide a path to cross-site scripting. Consult the documentation
for the used view engine for additional considerations.
```js
console.dir(app.locals.title);
// => 'My App'
console.dir(app.locals.email);
// => 'me@myapp.com'
```
Once set, the value of `app.locals` properties persist throughout the life of the application,
in contrast with [res.locals](/api/response/#reslocals) properties that
are valid only for the lifetime of the request.
You can access local variables in templates rendered within the application.
This is useful for providing helper functions to templates, as well as application-level data.
Local variables are available in middleware via `req.app.locals` (see [req.app](/api/request/#reqapp))
```js
app.locals.title = 'My App';
app.locals.strftime = require('strftime');
app.locals.email = 'me@myapp.com';
```
### app.mountpath
Type: String | String[].
The `app.mountpath` property contains one or more path patterns on which a sub-app was mounted.
A sub-app is an instance of `express` that may be used for handling the request to a route.
```cjs title="index.cjs"
const express = require('express');
const app = express(); // the main app
const admin = express(); // the sub app
admin.get('/', (req, res) => {
console.log(admin.mountpath); // /admin
res.send('Admin Homepage');
});
app.use('/admin', admin); // mount the sub app
```
```mjs title="index.mjs"
const app = express(); // the main app
const admin = express(); // the sub app
admin.get('/', (req, res) => {
console.log(admin.mountpath); // /admin
res.send('Admin Homepage');
});
app.use('/admin', admin); // mount the sub app
```
```ts title="index.ts"
const app: Express = express(); // the main app
const admin: Express = express(); // the sub app
admin.get('/', (req: Request, res: Response) => {
console.log(admin.mountpath); // /admin
res.send('Admin Homepage');
});
app.use('/admin', admin); // mount the sub app
```
It is similar to the [baseUrl](/api/request/#reqbaseurl) property of the `req` object, except `req.baseUrl`
returns the matched URL path, instead of the matched patterns.
If a sub-app is mounted on multiple path patterns, `app.mountpath` returns the list of
patterns it is mounted on, as shown in the following example.
```js
const admin = express();
admin.get('/', (req, res) => {
console.log(admin.mountpath); // [ '/adm{*splat}n', '/manager' ]
res.send('Admin Homepage');
});
const secret = express();
secret.get('/', (req, res) => {
console.log(secret.mountpath); // /secr{*splat}t
res.send('Admin Secret');
});
admin.use('/secr{*splat}t', secret); // load the 'secret' router on '/secr{*splat}t', on the 'admin' sub app
app.use(['/adm{*splat}n', '/manager'], admin); // load the 'admin' router on '/adm{*splat}n' and '/manager', on the parent app
```
```ts
const admin: Express = express();
admin.get('/', (req: Request, res: Response) => {
console.log(admin.mountpath); // [ '/adm{*splat}n', '/manager' ]
res.send('Admin Homepage');
});
const secret: Express = express();
secret.get('/', (req: Request, res: Response) => {
console.log(secret.mountpath); // /secr{*splat}t
res.send('Admin Secret');
});
admin.use('/secr{*splat}t', secret); // load the 'secret' router on '/secr{*splat}t', on the 'admin' sub app
app.use(['/adm{*splat}n', '/manager'], admin); // load the 'admin' router on '/adm{*splat}n' and '/manager', on the parent app
```
### app.router
Type: Router.
The application's in-built instance of router. This is created lazily, on first access.
```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = app.router;
router.get('/', (req, res) => {
res.send('hello world');
});
app.listen(3000);
```
```mjs title="index.mjs"
const app = express();
const router = app.router;
router.get('/', (req, res) => {
res.send('hello world');
});
app.listen(3000);
```
```ts title="index.ts"
const app: Express = express();
const router = app.router;
router.get('/', (req: Request, res: Response) => {
res.send('hello world');
});
app.listen(3000);
```
You can add middleware and HTTP method routes to the `router` just like an application.
For more information, see [Router](/api/router/).
## Events
### app.on('mount')
Arguments:
- callback (Function):
The listener called when the `mount` event fires. It receives the parent app as its only
argument: `callback(parent)`.
The `mount` event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.
Sub-apps will:
- Not inherit the value of settings that have a default value. You must set the value in the sub-app.
- Inherit the value of settings with no default value.
For details, see [Application settings](#application-settings).
```js
const admin = express();
admin.on('mount', (parent) => {
console.log('Admin Mounted');
console.log(parent); // refers to the parent app
});
admin.get('/', (req, res) => {
res.send('Admin Homepage');
});
app.use('/admin', admin);
```
```ts
const admin: Express = express();
admin.on('mount', (parent: Application) => {
console.log('Admin Mounted');
console.log(parent); // refers to the parent app
});
admin.get('/', (req: Request, res: Response) => {
res.send('Admin Homepage');
});
app.use('/admin', admin);
```
## Methods
### app.all()
Arguments:
- path (String | RegExp | Array):
The path to match for this route: a string, a regular expression, or an array of either.
String patterns match the whole request path. See [Path examples](#path-examples) for syntax.
- callback (Function | Function[]):
Callback functions; can be: a middleware function, a series of middleware functions (separated
by commas), an array of middleware functions, or a combination of all of the above. You can
provide multiple callback functions that behave just like middleware, except that these
callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use
this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if
there is no reason to proceed with the current route. Since [router](/api/router/) and
[app](/api/application/) implement the middleware interface, you can use them as you would any
other middleware function. For examples, see [Middleware callback function
examples](#middleware-callback-function-examples).
This method is like the standard [app.METHOD()](#appmethod) methods,
except it matches all HTTP verbs.
#### Examples
The following callback is executed for requests to `/secret` whether using
GET, POST, PUT, DELETE, or any other HTTP request method:
```js
app.all('/secret', (req, res, next) => {
console.log('Accessing the secret section ...');
next(); // pass control to the next handler
});
```
```ts
app.all('/secret', (req: Request, res: Response, next: NextFunction) => {
console.log('Accessing the secret section ...');
next(); // pass control to the next handler
});
```
The `app.all()` method is useful for mapping "global" logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other
route definitions, it requires that all routes from that point on
require authentication, and automatically load a user. Keep in mind
that these callbacks do not have to act as end-points: `loadUser`
can perform a task, then call `next()` to continue matching subsequent
routes.
```js
app.all('{*splat}', requireAuthentication, loadUser);
```
Or the equivalent:
```js
app.all('{*splat}', requireAuthentication);
app.all('{*splat}', loadUser);
```
Another example is white-listed "global" functionality.
The example is similar to the ones above, but it only restricts paths that start with
"/api":
```js
app.all('/api/{*splat}', requireAuthentication);
```
### app.delete()
Arguments:
- path (String | RegExp | Array):
The path to match for this route: a string, a regular expression, or an array of either.
String patterns match the whole request path. See [Path examples](#path-examples) for syntax.
- callback (Function | Function[]):
Callback functions; can be: a middleware function, a series of middleware functions (separated
by commas), an array of middleware functions, or a combination of all of the above. You can
provide multiple callback functions that behave just like middleware, except that these
callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use
this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if
there is no reason to proceed with the current route. Since [router](/api/router/) and
[app](/api/application/) implement the middleware interface, you can use them as you would any
other middleware function. For examples, see [Middleware callback function
examples](#middleware-callback-function-examples).
Routes HTTP DELETE requests to the specified path with the specified callback functions.
For more information, see the [routing guide](/guide/routing/).
#### Example
```js
app.delete('/', (req, res) => {
res.send('DELETE request to homepage');
});
```
```ts
app.delete('/', (req: Request, res: Response) => {
res.send('DELETE request to homepage');
});
```
### app.disable()
Returns: Application.
Arguments:
- name (String):
The name of the Boolean setting to disable; one of the properties from the [app settings
table](#application-settings).
Sets the Boolean setting `name` to `false`, where `name` is one of the properties from the [app settings table](#application-settings).
Calling `app.set('foo', false)` for a Boolean property is the same as calling `app.disable('foo')`.
For example:
```js
app.disable('trust proxy');
app.get('trust proxy');
// => false
```
### app.disabled()
Returns: Boolean.
Arguments:
- name (String):
The name of the Boolean setting to test; one of the properties from the [app settings
table](#application-settings).
Returns `true` if the Boolean setting `name` is disabled (`false`), where `name` is one of the properties from
the [app settings table](#application-settings).
```js
app.disabled('trust proxy');
// => true
app.enable('trust proxy');
app.disabled('trust proxy');
// => false
```
### app.enable()
Returns: Application.
Arguments:
- name (String):
The name of the Boolean setting to enable; one of the properties from the [app settings
table](#application-settings).
Sets the Boolean setting `name` to `true`, where `name` is one of the properties from the [app settings table](#application-settings).
Calling `app.set('foo', true)` for a Boolean property is the same as calling `app.enable('foo')`.
```js
app.enable('trust proxy');
app.get('trust proxy');
// => true
```
### app.enabled()
Returns: Boolean.
Arguments:
- name (String):
The name of the setting to test; one of the properties from the [app settings
table](#application-settings).
Returns `true` if the setting `name` is enabled (`true`), where `name` is one of the
properties from the [app settings table](#application-settings).
```js
app.enabled('trust proxy');
// => false
app.enable('trust proxy');
app.enabled('trust proxy');
// => true
```
### app.engine()
Returns: Application.
Arguments:
- ext (String):
The file extension the template engine is registered for (for example, `pug` or `html`).
- callback (Function):
The template engine function used to render files with the given extension.
Registers the given template engine `callback` as `ext`.
By default, Express will `require()` the engine based on the file extension.
For example, if you try to render a "foo.pug" file, Express invokes the
following internally, and caches the `require()` on subsequent calls to increase
performance.
```js
app.engine('pug', require('pug').__express);
```
Use this method for engines that do not provide `.__express` out of the box,
or if you wish to "map" a different extension to the template engine.
For example, to map the EJS template engine to ".html" files:
```js
app.engine('html', require('ejs').renderFile);
```
In this case, EJS provides a `.renderFile()` method with
the same signature that Express expects: `(path, options, callback)`,
though note that it aliases this method as `ejs.__express` internally
so if you're using ".ejs" extensions you don't need to do anything.
Some template engines do not follow this convention. The
[consolidate.js](https://github.com/tj/consolidate.js) library maps Node template engines to follow this convention,
so they work seamlessly with Express.
```cjs title="index.cjs"
const engines = require('consolidate');
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);
```
```mjs title="index.mjs"
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);
```
### app.get(name)
Returns: any.
Arguments:
- name (String):
The name of the setting to read; one of the strings in the [app settings
table](#application-settings).
Returns the value of `name` app setting, where `name` is one of the strings in the
[app settings table](#application-settings). For example:
```js
app.get('title');
// => undefined
app.set('title', 'My Site');
app.get('title');
// => 'My Site'
```
### app.get()
Arguments:
- path (String | RegExp | Array):
The path to match for this route: a string, a regular expression, or an array of either.
String patterns match the whole request path. See [Path examples](#path-examples) for syntax.
- callback (Function | Function[]):
Callback functions; can be: a middleware function, a series of middleware functions (separated
by commas), an array of middleware functions, or a combination of all of the above. You can
provide multiple callback functions that behave just like middleware, except that these
callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use
this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if
there is no reason to proceed with the current route. Since [router](/api/router/) and
[app](/api/application/) implement the middleware interface, you can use them as you would any
other middleware function. For examples, see [Middleware callback function
examples](#middleware-callback-function-examples).
Routes HTTP GET requests to the specified path with the specified callback functions.
For more information, see the [routing guide](/guide/routing/).
#### Example
```js
app.get('/', (req, res) => {
res.send('GET request to homepage');
});
```
```ts
app.get('/', (req: Request, res: Response) => {
res.send('GET request to homepage');
});
```
### app.listen()
Returns: http.Server.
Arguments:
- port (Number, optional):
The TCP port to listen on. If omitted or `0`, the OS assigns an arbitrary unused port.
- host (String, optional):
The host on which to accept connections.
- backlog (Number, optional):
The maximum length of the queue of pending connections.
- path (String, optional):
The path of a UNIX socket to listen on, as an alternative to host and port.
- callback (Function, optional):
A function called once the server is listening. If the server emits an `error` event (for
example `EADDRINUSE`), the error is passed to this callback as its argument.
Binds and listens for connections on the specified host and port, or starts a
UNIX socket and listens for connections on the given path. This method is
identical to Node's [http.Server.listen()](https://nodejs.org/api/http.html#serverlisten).
If port is omitted or is 0, the operating system will assign an arbitrary unused
port, which is useful for cases like automated tasks (tests, etc.).
```cjs title="index.cjs"
const express = require('express');
const app = express();
app.listen(3000); // bind and listen on a TCP port
app.listen('/tmp/sock'); // or listen on a UNIX socket
```
```mjs title="index.mjs"
const app = express();
app.listen(3000); // bind and listen on a TCP port
app.listen('/tmp/sock'); // or listen on a UNIX socket
```
```ts title="index.ts"
const app: Express = express();
app.listen(3000); // bind and listen on a TCP port
app.listen('/tmp/sock'); // or listen on a UNIX socket
```
When the server emits an `error` event (such as `EADDRINUSE`), the error is passed to the provided
`callback`. Handle it inside the callback:
```js
const server = app.listen(8080, '0.0.0.0', (error) => {
if (error) {
throw error; // e.g. EADDRINUSE
}
console.log(`Listening on ${JSON.stringify(server.address())}`);
});
```
The `app` returned by `express()` is in fact a JavaScript
`Function`, designed to be passed to Node's HTTP servers as a callback
to handle requests. This makes it easy to provide both HTTP and HTTPS versions of
your app with the same code base, as the app does not inherit from these
(it is simply a callback):
```cjs title="index.cjs"
const express = require('express');
const https = require('https');
const http = require('http');
const app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
```
```mjs title="index.mjs"
const app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
```
```ts title="index.ts"
const app: Express = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
```
The `app.listen()` method returns an [http.Server](https://nodejs.org/api/http.html#class-httpserver) object and (for HTTP) is a convenience method for the following:
```js
app.listen = function () {
const server = http.createServer(this);
return server.listen.apply(server, arguments);
};
```
All the forms of Node's
[http.Server.listen()](https://nodejs.org/api/http.html#serverlisten) method are in fact
actually supported.
### app.METHOD()
Arguments:
- path (String | RegExp | Array):
The path to match for this route: a string, a regular expression, or an array of either.
String patterns match the whole request path. See [Path examples](#path-examples) for syntax.
- callback (Function | Function[]):
Callback functions; can be: a middleware function, a series of middleware functions (separated
by commas), an array of middleware functions, or a combination of all of the above. You can
provide multiple callback functions that behave just like middleware, except that these
callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use
this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if
there is no reason to proceed with the current route. Since [router](/api/router/) and
[app](/api/application/) implement the middleware interface, you can use them as you would any
other middleware function. For examples, see [Middleware callback function
examples](#middleware-callback-function-examples).
Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET,
PUT, POST, and so on, in lowercase. Thus, the actual methods are `app.get()`,
`app.post()`, `app.put()`, and so on. See [Routing methods](#routing-methods) below for the complete list.
String route patterns match the whole request path. For example, `app.get('/apple', ...)` matches
`/apple`, but not `/apple/images`. With the same path, [app.use()](#appuse) matches both.
Regular expressions can match part of the path. `app.get(/apple/, ...)` matches `/apple/images`.
Use `^` and `$` for a full match: `app.get(/^\/apple$/, ...)` matches only `/apple`.
#### Routing methods
Express supports the following routing methods corresponding to the HTTP methods of the same names:
- `checkout`
- `copy`
- [`delete`](#appdelete)
- [`get`](#appget)
- `head`
- `lock`
- `merge`
- `mkactivity`
- `mkcol`
- `move`
- `m-search`
- `notify`
- `options`
- `patch`
- [`post`](#apppost)
- `purge`
- [`put`](#appput)
- [`query`](#appquery)
- `report`
- `search`
- `subscribe`
- `trace`
- `unlock`
- `unsubscribe`
The API documentation has explicit entries only for the most popular HTTP methods `app.get()`,
`app.post()`, `app.put()`, `app.delete()`, and `app.query()`.
However, the other methods listed above work in exactly the same way.
To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, `app['m-search']('/', function ...`.
```js ins={10}
app.get('/', (req, res) => {
res.send('GET request to homepage');
});
app.post('/', (req, res) => {
res.send('POST request to homepage');
});
// methods that are invalid JavaScript variable names use bracket notation
app['m-search']('/', (req, res) => {
res.send('M-SEARCH request to homepage');
});
```
```ts
app.get('/', (req: Request, res: Response) => {
res.send('GET request to homepage');
});
app.post('/', (req: Request, res: Response) => {
res.send('POST request to homepage');
});
// methods that are invalid JavaScript variable names use bracket notation
app['m-search']('/', (req: Request, res: Response) => {
res.send('M-SEARCH request to homepage');
});
```
The `app.get()` function is automatically called for the HTTP `HEAD` method in addition to the
`GET` method if `app.head()` was not called for the path before `app.get()`.
The method, `app.all()`, is not derived from any HTTP method and loads middleware at
the specified path for _all_ HTTP request methods.
For more information, see [app.all](#appall).
For more information on routing, see the [routing guide](/guide/routing/).
### app.param()
Arguments:
- name (String | String[]):
The name of the route parameter, or an array of names.
- callback (Function):
The trigger called as `callback(req, res, next, value, name)`: the request object, the
response object, the next middleware, the value of the parameter, and the name of the
parameter, in that order.
Add callback triggers to [route parameters](/guide/routing/#route-parameters), where `name` is the name of the parameter or an array of them, and `callback` is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order.
If `name` is an array, the `callback` trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to `next` inside the callback will call the callback for the next declared parameter. For the last parameter, a call to `next` will call the next middleware in place for the route currently being processed, just like it would if `name` were just a string.
For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input.
```js
app.param('user', (req, res, next, id) => {
// try to get the user details from the User model and attach it to the request object
User.find(id, (err, user) => {
if (err) {
next(err);
} else if (user) {
req.user = user;
next();
} else {
next(new Error('failed to load user'));
}
});
});
```
Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on `app` will be triggered only by route parameters defined on `app` routes.
All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.
```js
app.param('id', (req, res, next, id) => {
console.log('CALLED ONLY ONCE');
next();
});
app.get('/user/:id', (req, res, next) => {
console.log('although this matches');
next();
});
app.get('/user/:id', (req, res) => {
console.log('and this matches too');
res.end();
});
```
```ts
app.param('id', (req: Request, res: Response, next: NextFunction, id: string) => {
console.log('CALLED ONLY ONCE');
next();
});
app.get('/user/:id', (req: Request, res: Response, next: NextFunction) => {
console.log('although this matches');
next();
});
app.get('/user/:id', (req: Request, res: Response) => {
console.log('and this matches too');
res.end();
});
```
On `GET /user/42`, the following is printed:
```
CALLED ONLY ONCE
although this matches
and this matches too
```
```js
app.param(['id', 'page'], (req, res, next, value) => {
console.log('CALLED ONLY ONCE with', value);
next();
});
app.get('/user/:id/:page', (req, res, next) => {
console.log('although this matches');
next();
});
app.get('/user/:id/:page', (req, res) => {
console.log('and this matches too');
res.end();
});
```
```ts
app.param(['id', 'page'], (req: Request, res: Response, next: NextFunction, value: string) => {
console.log('CALLED ONLY ONCE with', value);
next();
});
app.get('/user/:id/:page', (req: Request, res: Response, next: NextFunction) => {
console.log('although this matches');
next();
});
app.get('/user/:id/:page', (req: Request, res: Response) => {
console.log('and this matches too');
res.end();
});
```
On `GET /user/42/3`, the following is printed:
```
CALLED ONLY ONCE with 42
CALLED ONLY ONCE with 3
although this matches
and this matches too
```
### app.path()
Returns: String.
Returns the canonical path of the app, a string.
```js title="index.js"
const app = express();
const blog = express();
const blogAdmin = express();
app.use('/blog', blog);
blog.use('/admin', blogAdmin);
console.log(app.path()); // ''
console.log(blog.path()); // '/blog'
console.log(blogAdmin.path()); // '/blog/admin'
```
```ts title="index.ts"
const app: Express = express();
const blog: Express = express();
const blogAdmin: Express = express();
app.use('/blog', blog);
blog.use('/admin', blogAdmin);
console.log(app.path()); // ''
console.log(blog.path()); // '/blog'
console.log(blogAdmin.path()); // '/blog/admin'
```
The behavior of this method can become very complicated in complex cases of mounted apps:
it is usually better to use [req.baseUrl](/api/request/#reqbaseurl) to get the canonical path of the app.
### app.post()
Arguments:
- path (String | RegExp | Array):
The path to match for this route: a string, a regular expression, or an array of either.
String patterns match the whole request path. See [Path examples](#path-examples) for syntax.
- callback (Function | Function[]):
Callback functions; can be: a middleware function, a series of middleware functions (separated
by commas), an array of middleware functions, or a combination of all of the above. You can
provide multiple callback functions that behave just like middleware, except that these
callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use
this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if
there is no reason to proceed with the current route. Since [router](/api/router/) and
[app](/api/application/) implement the middleware interface, you can use them as you would any
other middleware function. For examples, see [Middleware callback function
examples](#middleware-callback-function-examples).
Routes HTTP POST requests to the specified path with the specified callback functions.
For more information, see the [routing guide](/guide/routing/).
#### Example
```js
app.post('/', (req, res) => {
res.send('POST request to homepage');
});
```
```ts
app.post('/', (req: Request, res: Response) => {
res.send('POST request to homepage');
});
```
### app.put()
Arguments:
- path (String | RegExp | Array):
The path to match for this route: a string, a regular expression, or an array of either.
String patterns match the whole request path. See [Path examples](#path-examples) for syntax.
- callback (Function | Function[]):
Callback functions; can be: a middleware function, a series of middleware functions (separated
by commas), an array of middleware functions, or a combination of all of the above. You can
provide multiple callback functions that behave just like middleware, except that these
callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use
this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if
there is no reason to proceed with the current route. Since [router](/api/router/) and
[app](/api/application/) implement the middleware interface, you can use them as you would any
other middleware function. For examples, see [Middleware callback function
examples](#middleware-callback-function-examples).
Routes HTTP PUT requests to the specified path with the specified callback functions.
#### Example
```js
app.put('/', (req, res) => {
res.send('PUT request to homepage');
});
```
```ts
app.put('/', (req: Request, res: Response) => {
res.send('PUT request to homepage');
});
```
### app.query()
Requires runtime: Node.js >=20.19.3 <21 || >=22.2.0.
Arguments:
- path (String | RegExp | Array):
The path to match for this route: a string, a regular expression, or an array of either.
String patterns match the whole request path. See [Path examples](#path-examples) for syntax.
- callback (Function | Function[]):
Callback functions; can be: a middleware function, a series of middleware functions (separated
by commas), an array of middleware functions, or a combination of all of the above. You can
provide multiple callback functions that behave just like middleware, except that these
callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use
this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if
there is no reason to proceed with the current route. Since [router](/api/router/) and
[app](/api/application/) implement the middleware interface, you can use them as you would any
other middleware function. For examples, see [Middleware callback function
examples](#middleware-callback-function-examples).
Routes HTTP QUERY requests to the specified path with the specified callback functions.
For more information, see the [routing guide](/guide/routing/).
The HTTP QUERY method was standardized on June 15, 2026 as [RFC 10008](https://www.rfc-editor.org/rfc/rfc10008.html).
Client and intermediary support is still limited. Verify that your target environments support the QUERY verb before relying on it in production.
The HTTP QUERY method ([RFC 10008](https://www.rfc-editor.org/rfc/rfc10008.html)) is designed for
queries whose input is too large or too sensitive to encode in the URL. Unlike `GET`, a QUERY
request carries a body containing the query input. Unlike `POST`, it is explicitly **safe and
idempotent**, intermediaries and caches can retry it automatically, and the response is cacheable
(with the request body included in the cache key).
Use `app.query()` when query parameters would exceed URL length limits, contain sensitive data that
should not appear in server logs or browser history, or are too complex to express cleanly as a URL
query string, such as deeply nested filters or structured criteria.
Because the query input travels in the request body, `req.body` is `undefined` until you mount a
body-parsing middleware such as [`express.json()`](/api/express/#expressjson) or
[`express.urlencoded()`](/api/express/#expressurlencoded) that matches the request's `Content-Type`.
#### Example
```js title="index.js"
app.use(express.json()); // populate req.body for application/json payloads
app.query('/search', (req, res) => {
// complex filter criteria arrive in req.body, not the URL
const results = db.search(req.body);
res.json(results);
});
```
```ts title="index.ts"
app.use(express.json()); // populate req.body for application/json payloads
app.query('/search', (req: Request, res: Response) => {
// complex filter criteria arrive in req.body, not the URL
const results = db.search(req.body);
res.json(results);
});
```
### app.render()
Arguments:
- view (String):
The name of the view to render.
- locals (Object, optional):
An object whose properties define local variables for the view.
- callback (Function):
The callback invoked as `callback(err, html)` with the rendered HTML.
Returns the rendered HTML of a view via the `callback` function. It accepts an optional parameter
that is an object containing local variables for the view. It is like [res.render()](/api/response/#resrender),
except it cannot send the rendered view to the client on its own.
Think of `app.render()` as a utility function for generating rendered view strings. Internally
`res.render()` uses `app.render()` to render views.
The `view` argument performs file system operations like reading a file from disk and evaluating
Node.js modules, and as so for security reasons should not contain input from the end-user.
The `locals` object is used by view engines to render a response. The object keys may be
particularly sensitive and should not contain user-controlled input, as it may affect the
operation of the view engine or provide a path to cross-site scripting. Consult the documentation
for the used view engine for additional considerations.
The local variable `cache` is reserved for enabling view cache. Set it to `true`, if you want to
cache view during development; view caching is enabled in production by default.
```js
app.render('email', (err, html) => {
// ...
});
app.render('email', { name: 'Tobi' }, (err, html) => {
// ...
});
```
### app.route()
Returns: Route.
Arguments:
- path (String):
The path of the route to create.
Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware.
Use `app.route()` to avoid duplicate route names (and thus typo errors).
```js
const app = express();
app
.route('/events')
.all((req, res, next) => {
// runs for all HTTP verbs first
// think of it as route specific middleware!
})
.get((req, res, next) => {
res.json({});
})
.post((req, res, next) => {
// maybe add a new event...
});
```
```ts
const app: Express = express();
app
.route('/events')
.all((req: Request, res: Response, next: NextFunction) => {
// runs for all HTTP verbs first
// think of it as route specific middleware!
})
.get((req: Request, res: Response, next: NextFunction) => {
res.json({});
})
.post((req: Request, res: Response, next: NextFunction) => {
// maybe add a new event...
});
```
### app.set()
Returns: Application.
Arguments:
- name (String):
The name of the setting to assign. Certain names configure the server's behavior; see the [app
settings table](#application-settings).
- value (any):
The value to assign to the setting.
Assigns setting `name` to `value`. You may store any value that you want,
but certain names can be used to configure the behavior of the server. These
special names are listed in the [app settings table](#application-settings).
Calling `app.set('foo', true)` for a Boolean property is the same as calling
`app.enable('foo')`. Similarly, calling `app.set('foo', false)` for a Boolean
property is the same as calling `app.disable('foo')`.
Retrieve the value of a setting with [`app.get()`](#appgetname).
```js
app.set('title', 'My Site');
app.get('title'); // "My Site"
```
#### Application Settings
The following table lists application settings.
Sub-apps will:
- Not inherit the value of settings that have a default value. You must set the value in the sub-app.
- Inherit the value of settings with no default value; these are explicitly noted in the table below.
Exceptions: Sub-apps will inherit the value of `trust proxy` even though it has a default value (for backward-compatibility);
Sub-apps will not inherit the value of `view cache` in production (when `NODE_ENV` is "production").
Settings:
- case sensitive routing (Boolean, default: N/A (undefined)):
Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same.
Sub-apps will inherit the value of this setting.
- env (String, default: process.env.NODE_ENV (NODE_ENV environment variable) or "development" if NODE_ENV is not set.):
Environment mode. Be sure to set to "production" in a production environment; see [Production best practices: performance and reliability](/advanced/best-practice-performance#things-to-do-in-your-environment--setup).
- etag (Boolean | String | Function, default: weak):
Set the ETag response header. For possible values, see the `etag` options table below. [More about the HTTP ETag header](https://en.wikipedia.org/wiki/HTTP_ETag).
- jsonp callback name (String, default: "callback"):
Specifies the default JSONP callback name.
- json escape (Boolean, default: N/A (undefined)):
Enable escaping JSON responses from the `res.json`, `res.jsonp`, and `res.send` APIs. This will escape the characters `<`, `>`, and `&` as Unicode escape sequences in JSON. The purpose of this is to assist with [mitigating certain types of persistent XSS attacks](https://blog.mozilla.org/security/2017/07/18/web-service-audits-firefox-accounts/) when clients sniff responses for HTML.
Sub-apps will inherit the value of this setting.
- json replacer (Function | Array, default: N/A (undefined)):
The ['replacer' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter).
Sub-apps will inherit the value of this setting.
- json spaces (Number | String, default: N/A (undefined)):
The ['space' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_space_parameter). This is typically set to the number of spaces to use to indent prettified JSON.
Sub-apps will inherit the value of this setting.
- query parser (Boolean | String | Function, default: "simple"):
Disable query parsing by setting the value to `false`, or set the query parser to use either "simple" or "extended" or a custom query string parsing function. The simple query parser is based on Node's native query parser, [querystring](https://nodejs.org/api/querystring.html). The extended query parser is based on [qs](https://www.npmjs.com/package/qs). A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values.
- strict routing (Boolean, default: N/A (undefined)):
Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same.
Sub-apps will inherit the value of this setting.
- subdomain offset (Number, default: 2):
The number of dot-separated parts of the host to remove to access subdomain.
- trust proxy (Boolean | String | Number | Function | Array, default: false (disabled)):
Indicates the app is behind a front-facing proxy, and to use the `X-Forwarded-*` headers to determine the connection and the IP address of the client.
`X-Forwarded-*` headers are easily spoofed and the detected IP addresses are unreliable.
When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table below. The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation.
Sub-apps _will_ inherit the value of this setting, even though it has a default value.
- views (String | Array, default: process.cwd() + '/views'):
A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.
- view cache (Boolean, default: true in production, otherwise undefined.):
Enables view template compilation caching.
Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production").
- view engine (String, default: N/A (undefined)):
The default engine extension to use when omitted.
Sub-apps will inherit the value of this setting.
- x-powered-by (Boolean, default: true):
Enables the "X-Powered-By: Express" HTTP header.
#### Options for `trust proxy` setting
Read [Express behind proxies](/guide/behind-proxies) for more information.
**Boolean**: If `true`, the client's IP address is understood as the left-most entry in the `X-Forwarded-*` header. If `false`, the app is understood as directly facing the Internet and the client's IP address is derived from `req.connection.remoteAddress`. This is the default setting.
**String / String containing comma-separated values / Array of strings**: An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are:
- loopback - `127.0.0.1/8`, `::1/128`
- linklocal - `169.254.0.0/16`, `fe80::/10`
- uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7`
Set IP addresses in any of the following ways:
Specify a single subnet:
```js
app.set('trust proxy', 'loopback');
```
Specify a subnet and an address:
```js
app.set('trust proxy', 'loopback, 123.123.123.123');
```
Specify multiple subnets as CSV:
```js
app.set('trust proxy', 'loopback, linklocal, uniquelocal');
```
Specify multiple subnets as an array:
```js
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);
```
When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client's IP address.
**Number**: Trust the *n*th hop from the front-facing proxy server as the client.
**Function**: Custom trust implementation. Use this only if you know what you are doing.
```js
app.set('trust proxy', (ip) => {
if (ip === '127.0.0.1' || ip === '123.123.123.123')
return true; // trusted IPs
else return false;
});
```
#### Options for `etag` setting
These settings apply only to dynamic files, not static files. The `express.static` middleware ignores these settings.
The ETag functionality is implemented using the [etag](https://www.npmjs.com/package/etag) package. For more information, see its documentation.
Values:
- Boolean:
`true` enables weak ETag. This is the default setting. `false` disables ETag altogether.
- String:
If "strong", enables strong ETag. If "weak", enables weak ETag.
- Function:
Custom ETag function implementation. Use this only if you know what you are doing.
```js
app.set('etag', (body, encoding) => {
return generateHash(body, encoding); // consider the function is defined
});
```
### app.use()
Arguments:
- path (String | RegExp | Array, optional):
The path for which the middleware function is invoked; can be any of: a string representing a
path, a path pattern, a regular expression pattern to match paths, or an array of combinations
of any of the above. For examples, see [Path examples](#path-examples).
- callback (Function | Function[]):
Callback functions; can be: a middleware function, a series of middleware functions (separated
by commas), an array of middleware functions, or a combination of all of the above. You can
provide multiple callback functions that behave just like middleware, except that these
callbacks can invoke `next('route')` to bypass the remaining route callback(s). You can use
this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if
there is no reason to proceed with the current route. Since [router](/api/router/) and
[app](/api/application/) implement the middleware interface, you can use them as you would any
other middleware function. For examples, see [Middleware callback function
examples](#middleware-callback-function-examples).
Mounts the specified [middleware](/guide/using-middleware) function or functions
at the specified path:
the middleware function is executed when the base of the requested path matches `path`.
#### Description
With a string path, `app.use()` matches that path and its subpaths. For example,
`app.use('/apple', ...)` matches `/apple`, `/apple/images`, and `/apple/images/news`,
but not `/apples`.
Since `path` defaults to "/", middleware mounted without a path will be executed for every request to the app.
For example, this middleware function will be executed for _every_ request to the app:
```js
app.use((req, res, next) => {
console.log('Time: %d', Date.now());
next();
});
```
```ts
app.use((req: Request, res: Response, next: NextFunction) => {
console.log('Time: %d', Date.now());
next();
});
```
Sub-apps will:
- Not inherit the value of settings that have a default value. You must set the value in the sub-app.
- Inherit the value of settings with no default value.
For details, see [Application settings](#application-settings).
Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.
```js
// this middleware will not allow the request to go beyond it
app.use((req, res, next) => {
res.send('Hello World');
});
// requests will never reach this route
app.get('/', (req, res) => {
res.send('Welcome');
});
```
```ts
// this middleware will not allow the request to go beyond it
app.use((req: Request, res: Response, next: NextFunction) => {
res.send('Hello World');
});
// requests will never reach this route
app.get('/', (req: Request, res: Response) => {
res.send('Welcome');
});
```
**Error-handling middleware**
Error-handling middleware always takes _four_ arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don't need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: [Error handling](/guide/error-handling).
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`):
```js
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
```
```ts
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
```
#### Path examples
The following table provides some simple examples of valid `path` values for
mounting middleware.
**Path**: Matches the exact path `/abcd` and any sub-paths starting with `/abcd/` (for example, `/abcd/foo`):
```js
app.use('/abcd', (req, res, next) => {
next();
});
```
```ts
app.use('/abcd', (req: Request, res: Response, next: NextFunction) => {
next();
});
```
**Path Pattern**: This will match paths starting with `/abcd` and `/abd`:
```js
app.use('/ab{c}d', (req, res, next) => {
next();
});
```
```ts
app.use('/ab{c}d', (req: Request, res: Response, next: NextFunction) => {
next();
});
```
**Regular Expression**: This will match paths starting with `/abc` and `/xyz`:
```js
app.use(/\/abc|\/xyz/, (req, res, next) => {
next();
});
```
```ts
app.use(/\/abc|\/xyz/, (req: Request, res: Response, next: NextFunction) => {
next();
});
```
**Array**: This will match paths starting with `/abcd`, `/xyza`, `/lmn`, and `/pqr`:
```js
app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], (req, res, next) => {
next();
});
```
```ts
app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], (req: Request, res: Response, next: NextFunction) => {
next();
});
```
#### Middleware callback function examples
The following table provides some simple examples of middleware functions that
can be used as the `callback` argument to `app.use()`, `app.METHOD()`, and `app.all()`.
**Single Middleware**: You can define and mount a middleware function locally.
```js
app.use((req, res, next) => {
next();
});
```
```ts
app.use((req: Request, res: Response, next: NextFunction) => {
next();
});
```
A router is valid middleware.
```js
const router = express.Router();
router.get('/', (req, res, next) => {
next();
});
app.use(router);
```
```ts
const router = express.Router();
router.get('/', (req: Request, res: Response, next: NextFunction) => {
next();
});
app.use(router);
```
An Express app is valid middleware.
```js
const subApp = express();
subApp.get('/', (req, res, next) => {
next();
});
app.use(subApp);
```
```ts
const subApp: Express = express();
subApp.get('/', (req: Request, res: Response, next: NextFunction) => {
next();
});
app.use(subApp);
```
**Series of Middleware**: You can specify more than one middleware function at the same mount path.
```js
const r1 = express.Router();
r1.get('/', (req, res, next) => {
next();
});
const r2 = express.Router();
r2.get('/', (req, res, next) => {
next();
});
app.use(r1, r2);
```
```ts
const r1 = express.Router();
r1.get('/', (req: Request, res: Response, next: NextFunction) => {
next();
});
const r2 = express.Router();
r2.get('/', (req: Request, res: Response, next: NextFunction) => {
next();
});
app.use(r1, r2);
```
**Array**: Use an array to group middleware logically.
```js
const r1 = express.Router();
r1.get('/', (req, res, next) => {
next();
});
const r2 = express.Router();
r2.get('/', (req, res, next) => {
next();
});
app.use([r1, r2]);
```
```ts
const r1 = express.Router();
r1.get('/', (req: Request, res: Response, next: NextFunction) => {
next();
});
const r2 = express.Router();
r2.get('/', (req: Request, res: Response, next: NextFunction) => {
next();
});
app.use([r1, r2]);
```
**Combination**: You can combine all the above ways of mounting middleware.
```js
function mw1(req, res, next) {
next();
}
function mw2(req, res, next) {
next();
}
const r1 = express.Router();
r1.get('/', (req, res, next) => {
next();
});
const r2 = express.Router();
r2.get('/', (req, res, next) => {
next();
});
const subApp = express();
subApp.get('/', (req, res, next) => {
next();
});
app.use(mw1, [mw2, r1, r2], subApp);
```
```ts
function mw1(req: Request, res: Response, next: NextFunction) {
next();
}
function mw2(req: Request, res: Response, next: NextFunction) {
next();
}
const r1 = express.Router();
r1.get('/', (req: Request, res: Response, next: NextFunction) => {
next();
});
const r2 = express.Router();
r2.get('/', (req: Request, res: Response, next: NextFunction) => {
next();
});
const subApp: Express = express();
subApp.get('/', (req: Request, res: Response, next: NextFunction) => {
next();
});
app.use(mw1, [mw2, r1, r2], subApp);
```
Following are some examples of using the [express.static](/guide/using-middleware/#built-in-middleware)
middleware in an Express app.
Serve static content for the app from the "public" directory in the application directory:
```js
// GET /style.css etc
app.use(express.static(path.join(__dirname, 'public')));
```
Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static":
```js
// GET /static/style.css etc.
app.use('/static', express.static(path.join(__dirname, 'public')));
```
Disable logging for static content requests by loading the logger middleware after the static middleware:
```js
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger());
```
Serve static files from multiple directories, but give precedence to "./public" over the others:
```js
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'files')));
app.use(express.static(path.join(__dirname, 'uploads')));
```
---
## Express Object
URL: https://expressjs.com/en/5x/api/express
Creates an Express application. The `express()` function is a top-level function exported by the `express` module.
```cjs title="index.cjs"
const express = require('express');
const app = express();
```
```mjs title="index.mjs"
const app = express();
```
```ts title="index.ts"
const app: Express = express();
```
## Methods
The Express object has the following methods that can be used to create middleware functions, routers and have some built-in middleware:
### express.json()
Returns: Function.
Arguments:
- options (Object, optional):
Configures how the JSON body is parsed; it accepts the properties below.
Properties:
- defaultCharset (String, default: "utf-8"):
Specify the default character set for the JSON content if the charset is not specified in
the `Content-Type` header of the request.
- inflate (Boolean, default: true):
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies
are rejected.
- limit (Number | String, default: "100kb"):
Controls the maximum request body size. If this is a number, then the value specifies the
number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing.
- reviver (Function, default: null):
The `reviver` option is passed directly to `JSON.parse` as the second argument. You can
find more information on this argument [in the MDN documentation about
JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
```js
app.use(express.json({
reviver: (key, value) => key === 'createdAt' ? new Date(value) : value,
}));
// Body: {"createdAt":"2026-01-01T00:00:00Z"}
// req.body.createdAt is a Date.
```
- strict (Boolean, default: true):
Enables or disables only accepting arrays and objects; when disabled will accept anything
`JSON.parse` accepts.
```js
app.use(express.json({ strict: false }));
// Body: 42 -> req.body is the number 42.
// With strict: true (the default), this body is rejected with status 400.
```
- type (String | String[] | Function, default: "application/json"):
This is used to determine what media type the middleware will parse. This option can be a
string, array of strings, or a function. If not a function, `type` option is passed
directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this
can be an extension name (like `json`), a mime type (like `application/json`), or a mime
type with a wildcard (like `*/*` or `*/json`). If a function, the `type` option is called
as `fn(req)` and the request is parsed if it returns a truthy value.
- verify (Function, default: undefined):
This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a
`Buffer` of the raw request body and `encoding` is the encoding of the request. The
parsing can be aborted by throwing an error.
```js
app.use(express.json({
verify: (req, res, buf) => {
req.rawBody = buf;
},
}));
// req.rawBody contains the original Buffer, before JSON parsing.
```
This is a built-in middleware function in Express. It parses incoming requests
with JSON payloads and is based on
[body-parser](/resources/middleware/body-parser).
Returns middleware that only parses JSON and only looks at requests where
the `Content-Type` header matches the `type` option. This parser accepts any
Unicode encoding of the body and supports automatic inflation of `gzip` and
`deflate` encodings.
A new `body` object containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`), or `undefined` if
there was no body to parse, the `Content-Type` was not matched, or an error
occurred.
As `req.body`'s shape is based on user-controlled input, all properties and values in this object
are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may
fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString`
may not be a function and instead a string or other user-input.
```cjs title="index.cjs" ins={5}
const express = require('express');
const app = express();
// parse requests with a Content-Type of application/json
app.use(express.json());
app.post('/profile', (req, res) => {
console.dir(req.body);
res.json(req.body);
});
```
```mjs title="index.mjs" ins={6}
const app = express();
// parse requests with a Content-Type of application/json
app.use(express.json());
app.post('/profile', (req, res) => {
console.dir(req.body);
res.json(req.body);
});
```
```ts title="index.ts"
const app: Express = express();
// parse requests with a Content-Type of application/json
app.use(express.json());
app.post('/profile', (req: Request, res: Response) => {
console.dir(req.body);
res.json(req.body);
});
```
### express.raw()
Returns: Function.
Arguments:
- options (Object, optional):
Configures how the request body is parsed; it accepts the properties below.
Properties:
- inflate (Boolean, default: true):
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies
are rejected.
- limit (Number | String, default: "100kb"):
Controls the maximum request body size. If this is a number, then the value specifies the
number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing.
- type (String | String[] | Function, default: "application/octet-stream"):
This is used to determine what media type the middleware will parse. This option can be a
string, array of strings, or a function. If not a function, `type` option is passed
directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this
can be an extension name (like `bin`), a mime type (like `application/octet-stream`), or a
mime type with a wildcard (like `*/*` or `application/*`). If a function, the `type`
option is called as `fn(req)` and the request is parsed if it returns a truthy value.
- verify (Function, default: undefined):
This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a
`Buffer` of the raw request body and `encoding` is the encoding of the request. The
parsing can be aborted by throwing an error.
This is a built-in middleware function in Express. It parses incoming request
payloads into a `Buffer` and is based on
[body-parser](/resources/middleware/body-parser).
Returns middleware that parses all bodies as a `Buffer` and only looks at requests
where the `Content-Type` header matches the `type` option. This parser accepts
any Unicode encoding of the body and supports automatic inflation of `gzip` and
`deflate` encodings.
A new `body` `Buffer` containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`), or `undefined` if
there was no body to parse, the `Content-Type` was not matched, or an error
occurred.
As `req.body`'s shape is based on user-controlled input, all properties and values in this object
are untrusted and should be validated before trusting. For example, `req.body.toString()` may fail
in multiple ways, for example stacking multiple parsers `req.body` may be from a different parser.
Testing that `req.body` is a `Buffer` before calling buffer methods is recommended.
```cjs title="index.cjs" ins={5}
const express = require('express');
const app = express();
// parse requests with a Content-Type of application/octet-stream into a Buffer
app.use(express.raw());
app.post('/upload', (req, res) => {
console.dir(Buffer.isBuffer(req.body)); // => true
res.send(`received ${req.body.length} bytes`);
});
```
```mjs title="index.mjs" ins={6}
const app = express();
// parse requests with a Content-Type of application/octet-stream into a Buffer
app.use(express.raw());
app.post('/upload', (req, res) => {
console.dir(Buffer.isBuffer(req.body)); // => true
res.send(`received ${req.body.length} bytes`);
});
```
```ts title="index.ts"
const app: Express = express();
// parse requests with a Content-Type of application/octet-stream into a Buffer
app.use(express.raw());
app.post('/upload', (req: Request, res: Response) => {
console.dir(Buffer.isBuffer(req.body)); // => true
res.send(`received ${req.body.length} bytes`);
});
```
### express.Router()
Returns: Router.
Arguments:
- caseSensitive (Boolean, default: false):
Enable case sensitivity. Disabled by default, treating `/Foo` and `/foo` as the same.
```js
// caseSensitive: treat "/Foo" and "/foo" as different routes
const router = express.Router({ caseSensitive: true });
router.get('/Foo', (req, res) => res.send('Matched /Foo exactly'));
```
- mergeParams (Boolean, default: false):
Preserve the `req.params` values from the parent router. If the parent and the child have
conflicting param names, the child's value take precedence.
```js
// mergeParams: access parent route params in child router
const parent = express.Router();
const child = express.Router({ mergeParams: true });
parent.use('/user/:userId', child);
child.get('/comments', (req, res) => {
// req.params.userId is available because mergeParams: true
res.send(`Comments for user ${req.params.userId}`);
});
```
- strict (Boolean, default: false):
Enable strict routing. Disabled by default, `/foo` and `/foo/` are treated the same by the
router.
```js
// strict: treat "/foo" and "/foo/" as different routes
const strictRouter = express.Router({ strict: true });
strictRouter.get('/foo/', (req, res) => res.send('Matched /foo/ with trailing slash'));
```
Creates a new [router](/api/router/) object.
```js
const router = express.Router([options]);
```
You can add middleware and HTTP method routes (such as `get`, `put`, `post`, and
so on) to `router` just like an application.
For more information, see [Router](/api/router/).
### express.static()
Returns: Function.
Arguments:
- root (String):
The root directory from which to serve static assets.
- options (Object, optional):
Configures how files are served; it accepts the properties below. See also the [example
below](#example-of-expressstatic).
Properties:
- dotfiles (String, default: "ignore"):
Determines how dotfiles (files or directories that begin with a dot ".") are treated. See
[dotfiles](#dotfiles) below.
- etag (Boolean, default: true):
Enable or disable etag generation.
`express.static` always sends weak ETags.
- extensions (String[] | Boolean, default: false):
Sets file extension fallbacks: If a file is not found, search for files with the specified
extensions and serve the first one found. Example: `['html', 'htm']`.
- fallthrough (Boolean, default: true):
Let client errors fall-through as unhandled requests, otherwise forward a client error.
See [fallthrough](#fallthrough) below.
```js
app.use('/assets', express.static('public', { fallthrough: true }));
app.use('/assets', (req, res) => {
res.status(404).send('Asset not found');
});
// Missing files reach the fallback above.
// With fallthrough: false, they reach error-handling middleware instead.
```
- immutable (Boolean, default: false):
Enable or disable the `immutable` directive in the `Cache-Control` response header. If
enabled, the `maxAge` option should also be specified to enable caching. The `immutable`
directive will prevent supported clients from making conditional requests during the life
of the `maxAge` option to check if the file has changed.
```js
// Use filenames that change whenever the file contents change.
app.use('/assets', express.static('public', {
maxAge: '1y',
immutable: true,
}));
// Cache-Control: public, max-age=31536000, immutable
```
- index (String | Boolean, default: "index.html"):
Sends the specified directory index file. Set to `false` to disable directory indexing.
- lastModified (Boolean, default: true):
Set the `Last-Modified` header to the last modified date of the file on the OS.
- maxAge (Number, default: 0):
Set the max-age property of the Cache-Control header in milliseconds or a string in [ms
format](https://www.npmjs.com/package/ms).
- redirect (Boolean, default: true):
Redirect to trailing "/" when the pathname is a directory.
- setHeaders (Function):
Function for setting HTTP headers to serve with the file. See [setHeaders](#setheaders)
below.
- acceptRanges (Boolean, default: true):
Enable or disable accepting ranged requests. Disabling this will not send the
`Accept-Ranges` header and will ignore the contents of the Range request header.
- cacheControl (Boolean, default: true):
Enable or disable setting the `Cache-Control` response header. Disabling this will ignore
the immutable and maxAge options.
This is a built-in middleware function in Express.
It serves static files and is based on [serve-static](/resources/middleware/serve-static).
For best results, [use a reverse
proxy](/advanced/best-practice-performance#use-a-reverse-proxy) cache to improve performance of
serving static assets.
The `root` argument specifies the root directory from which to serve static assets.
The function determines the file to serve by combining `req.url` with the provided `root` directory.
When a file is not found, instead of sending a 404 response, it instead calls `next()`
to move on to the next middleware, allowing for stacking and fall-backs.
For more information, see [Serving static files in Express](/starter/static-files).
and [Using middleware - Built-in middleware](/guide/using-middleware/#built-in-middleware).
#### dotfiles
Possible values for this option are:
- "allow" - No special treatment for dotfiles.
- "deny" - Deny a request for a dotfile, respond with `403`, then call `next()`.
- "ignore" - Act as if the dotfile does not exist, respond with `404`, then call `next()`.
#### fallthrough
When this option is `true`, client errors such as a bad request or a request to a non-existent
file will cause this middleware to simply call `next()` to invoke the next middleware in the stack.
When false, these errors (even 404s), will invoke `next(err)`.
Set this option to `true` so you can map multiple physical directories
to the same web address or for routes to fill in non-existent files.
Use `false` if you have mounted this middleware at a path designed
to be strictly a single file system directory, which allows for short-circuiting 404s
for less overhead. This middleware will also reply to all methods.
#### setHeaders
For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.
The signature of the function is:
```js
fn(res, path, stat);
```
Arguments:
- `res`, the [response object](/api/response/).
- `path`, the file path that is being sent.
- `stat`, the `stat` object of the file that is being sent.
#### Example of express.static
Here is an example of using the `express.static` middleware function with an elaborate options object:
```cjs title="index.cjs" ins={16}
const express = require('express');
const app = express();
const options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders(res, path, stat) {
res.set('x-timestamp', Date.now());
},
};
app.use(express.static('public', options));
```
```mjs title="index.mjs" ins={17}
const app = express();
const options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders(res, path, stat) {
res.set('x-timestamp', Date.now());
},
};
app.use(express.static('public', options));
```
```ts title="index.ts"
const app: Express = express();
const options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders(res, path, stat) {
res.set('x-timestamp', Date.now());
},
};
app.use(express.static('public', options));
```
### express.text()
Returns: Function.
Arguments:
- options (Object, optional):
Configures how the text body is parsed; it accepts the properties below.
Properties:
- defaultCharset (String, default: "utf-8"):
Specify the default character set for the text content if the charset is not specified in
the `Content-Type` header of the request.
- inflate (Boolean, default: true):
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies
are rejected.
- limit (Number | String, default: "100kb"):
Controls the maximum request body size. If this is a number, then the value specifies the
number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing.
- type (String | String[] | Function, default: "text/plain"):
This is used to determine what media type the middleware will parse. This option can be a
string, array of strings, or a function. If not a function, `type` option is passed
directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this
can be an extension name (like `txt`), a mime type (like `text/plain`), or a mime type
with a wildcard (like `*/*` or `text/*`). If a function, the `type` option is called as
`fn(req)` and the request is parsed if it returns a truthy value.
- verify (Function, default: undefined):
This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a
`Buffer` of the raw request body and `encoding` is the encoding of the request. The
parsing can be aborted by throwing an error.
This is a built-in middleware function in Express. It parses incoming request
payloads into a string and is based on
[body-parser](/resources/middleware/body-parser).
Returns middleware that parses all bodies as a string and only looks at requests
where the `Content-Type` header matches the `type` option. This parser accepts
any Unicode encoding of the body and supports automatic inflation of `gzip` and
`deflate` encodings.
A new `body` string containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`), or `undefined` if
there was no body to parse, the `Content-Type` was not matched, or an error
occurred.
As `req.body`'s shape is based on user-controlled input, all properties and values in this object
are untrusted and should be validated before trusting. For example, `req.body.trim()` may fail in
multiple ways, for example stacking multiple parsers `req.body` may be from a different parser.
Testing that `req.body` is a string before calling string methods is recommended.
```cjs title="index.cjs" ins={5}
const express = require('express');
const app = express();
// parse requests with a Content-Type of text/plain into a string
app.use(express.text());
app.post('/', (req, res) => {
console.dir(typeof req.body); // => 'string'
res.send(req.body);
});
```
```mjs title="index.mjs" ins={6}
const app = express();
// parse requests with a Content-Type of text/plain into a string
app.use(express.text());
app.post('/', (req, res) => {
console.dir(typeof req.body); // => 'string'
res.send(req.body);
});
```
```ts title="index.ts"
const app: Express = express();
// parse requests with a Content-Type of text/plain into a string
app.use(express.text());
app.post('/', (req: Request, res: Response) => {
console.dir(typeof req.body); // => 'string'
res.send(req.body);
});
```
### express.urlencoded()
Returns: Function.
Arguments:
- options (Object, optional):
Configures how the URL-encoded body is parsed; it accepts the properties below.
Properties:
- extended (Boolean, default: false):
This option allows you to choose between parsing the URL-encoded data with the `querystring`
library (when `false`) or the `qs` library (when `true`). The "extended" syntax allows for
rich objects and arrays to be encoded into the URL-encoded format, allowing for a
JSON-like experience with URL-encoded. For more information, please [see the qs
library](https://www.npmjs.com/package/qs#readme).
```js
// Form body: user[name]=Tobi
app.post('/simple', express.urlencoded({ extended: false }), (req, res) => {
res.json(req.body); // => { 'user[name]': 'Tobi' }
});
app.post('/extended', express.urlencoded({ extended: true }), (req, res) => {
res.json(req.body); // => { user: { name: 'Tobi' } }
});
```
- inflate (Boolean, default: true):
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies
are rejected.
- limit (Number | String, default: "100kb"):
Controls the maximum request body size. If this is a number, then the value specifies the
number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing.
- parameterLimit (Number, default: 1000):
This option controls the maximum number of parameters that are allowed in the URL-encoded
data. If a request contains more parameters than this value, an error will be raised.
- type (String | String[] | Function, default: "application/x-www-form-urlencoded"):
This is used to determine what media type the middleware will parse. This option can be a
string, array of strings, or a function. If not a function, `type` option is passed
directly to the [type-is](https://www.npmjs.com/package/type-is#readme) library and this
can be an extension name (like `urlencoded`), a mime type (like
`application/x-www-form-urlencoded`), or a mime type with a wildcard (like
`*/x-www-form-urlencoded`). If a function, the `type` option is called as `fn(req)` and
the request is parsed if it returns a truthy value.
- verify (Function, default: undefined):
This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a
`Buffer` of the raw request body and `encoding` is the encoding of the request. The
parsing can be aborted by throwing an error.
- defaultCharset (String, default: "utf-8"):
The default charset to parse as, if not specified in content-type. Must be either `utf-8`
or `iso-8859-1`.
- charsetSentinel (Boolean, default: false):
Whether to let the value of the `utf8` parameter take precedence as the charset selector.
It requires the form to contain a parameter named `utf8` with a value of `✓`.
- interpretNumericEntities (Boolean, default: false):
Whether to decode numeric entities such as `☺` when parsing an iso-8859-1 form.
- depth (Number, default: 32):
Configure the maximum depth of the `qs` library when `extended` is `true`. This allows you
to limit the amount of keys that are parsed and can be useful to prevent certain types of
abuse. It is recommended to keep this value as low as possible.
This is a built-in middleware function in Express. It parses incoming requests
with urlencoded payloads and is based on [body-parser](/resources/middleware/body-parser).
Returns middleware that only parses urlencoded bodies and only looks at
requests where the `Content-Type` header matches the `type` option. This
parser accepts only UTF-8 encoding of the body and supports automatic
inflation of `gzip` and `deflate` encodings.
A new `body` object containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`), or `undefined` if
there was no body to parse, the `Content-Type` was not matched, or an error
occurred. This object will contain key-value pairs, where the value can be
a string or array (when `extended` is `false`), or any type (when `extended`
is `true`).
As `req.body`'s shape is based on user-controlled input, all properties and values in this object
are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may
fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString`
may not be a function and instead a string or other user-input.
```cjs title="index.cjs" ins={5}
const express = require('express');
const app = express();
// parse requests with a Content-Type of application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
app.post('/profile', (req, res) => {
console.dir(req.body);
res.json(req.body);
});
```
```mjs title="index.mjs" ins={6}
const app = express();
// parse requests with a Content-Type of application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
app.post('/profile', (req, res) => {
console.dir(req.body);
res.json(req.body);
});
```
```ts title="index.ts"
const app: Express = express();
// parse requests with a Content-Type of application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
app.post('/profile', (req: Request, res: Response) => {
console.dir(req.body);
res.json(req.body);
});
```
---
## Request Object
URL: https://expressjs.com/en/5x/api/request
The `req` object represents the HTTP request and has properties for the
request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention,
the object is always referred to as `req` (and the HTTP response is `res`) but its actual name is determined
by the parameters to the callback function in which you're working.
For example:
```js
app.get('/user/:id', (req, res) => {
res.send(`user ${req.params.id}`);
});
```
```ts
app.get('/user/:id', (req: Request, res: Response) => {
res.send(`user ${req.params.id}`);
});
```
But you could just as well have:
```js
app.get('/user/:id', (request, response) => {
response.send(`user ${request.params.id}`);
});
```
```ts
app.get('/user/:id', (request: Request, response: Response) => {
response.send(`user ${request.params.id}`);
});
```
The `req` object is an enhanced version of Node's own request object
and supports all [built-in fields and methods](https://nodejs.org/api/http.html#class-httpincomingmessage).
## Properties
The `req` object contains a number of properties that provide information about the HTTP request, such as headers, query parameters, and more.
### req.app
Type: Application.
This property holds a reference to the instance of the Express application that is using the middleware.
If you follow the pattern in which you create a module that just exports a middleware function
and `require()` it in your main file, then the middleware can access the Express instance via `req.app`
For example:
```cjs title="index.cjs"
app.get('/viewdirectory', require('./mymiddleware.cjs'));
```
```mjs title="index.mjs"
app.get('/viewdirectory', mymiddleware);
```
And the middleware module itself:
```cjs title="mymiddleware.cjs"
module.exports = (req, res) => {
res.send(`The views directory is ${req.app.get('views')}`);
};
```
```mjs title="mymiddleware.mjs"
export default (req, res) => {
res.send(`The views directory is ${req.app.get('views')}`);
};
```
```ts title="mymiddleware.ts"
export default (req: Request, res: Response) => {
res.send(`The views directory is ${req.app.get('views')}`);
};
```
### req.baseUrl
Type: String.
The URL path on which a router instance was mounted.
The `req.baseUrl` property is similar to the [mountpath](/api/application/#appmountpath) property of the `app` object,
except `app.mountpath` returns the matched path pattern(s).
For example:
```js
const greet = express.Router();
greet.get('/jp', (req, res) => {
console.log(req.baseUrl); // /greet
res.send('Konnichiwa!');
});
app.use('/greet', greet); // load the router on '/greet'
```
```ts
const greet = express.Router();
greet.get('/jp', (req: Request, res: Response) => {
console.log(req.baseUrl); // /greet
res.send('Konnichiwa!');
});
app.use('/greet', greet); // load the router on '/greet'
```
Even if you use a path pattern or a set of path patterns to load the router,
the `baseUrl` property returns the matched string, not the pattern(s). In the
following example, the `greet` router is loaded on two path patterns.
```js
app.use(['/gre:"param"t', '/hel{l}o'], greet); // load the router on '/gre:"param"t' and '/hel{l}o'
```
When a request is made to `/greet/jp`, `req.baseUrl` is "/greet". When a request is
made to `/hello/jp`, `req.baseUrl` is "/hello".
### req.body
Type: Object.
Contains key-value pairs of data submitted in the request body.
By default, it is `undefined`, and is populated when you use body-parsing middleware such
as [`express.json()`](/api/express/#expressjson) or [`express.urlencoded()`](/api/express/#expressurlencoded).
As `req.body`'s shape is based on user-controlled input, all properties and values in this object
are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may
fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString`
may not be a function and instead a string or other user-input.
The following example shows how to use body-parsing middleware to populate `req.body`.
```cjs title="index.cjs"
const express = require('express');
const app = express();
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', (req, res, next) => {
console.log(req.body);
res.json(req.body);
});
```
```mjs title="index.mjs"
const app = express();
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', (req, res, next) => {
console.log(req.body);
res.json(req.body);
});
```
```ts title="index.ts"
const app: Express = express();
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', (req: Request, res: Response, next: NextFunction) => {
console.log(req.body);
res.json(req.body);
});
```
### req.cookies
Type: Object.
When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property is an object that
contains cookies sent by the request. If the request contains no cookies, it defaults to `{}`.
```js
// Cookie: name=tj
console.dir(req.cookies.name);
// => 'tj'
```
If the cookie has been signed, you have to use [req.signedCookies](#reqsignedcookies).
For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser).
### req.fresh
Type: Boolean.
When the response is still "fresh" in the client's cache `true` is returned, otherwise `false` is returned to indicate that the client cache is now stale and the full response should be sent.
When a client sends the `Cache-Control: no-cache` request header to indicate an end-to-end reload request, this module will return `false` to make handling these requests transparent.
Further details for how cache validation works can be found in the
[HTTP/1.1 Caching Specification](https://tools.ietf.org/html/rfc7234).
```js
console.dir(req.fresh);
// => true
```
### req.hostname
Type: String.
Contains the hostname derived from the `Host` HTTP header.
When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting)
does not evaluate to `false`, this property will instead get the value
from the `X-Forwarded-Host` header field. This header can be set by
the client or by the proxy.
If there is more than one `X-Forwarded-Host` header in the request, the
value of the first header is used. This includes a single header with
comma-separated values, in which the first value is used.
```js
// Host: "example.com:3000"
console.dir(req.hostname);
// => 'example.com'
```
### req.host
Type: String.
Contains the host derived from the `Host` HTTP header.
When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting)
does not evaluate to `false`, this property will instead get the value
from the `X-Forwarded-Host` header field. This header can be set by
the client or by the proxy.
If there is more than one `X-Forwarded-Host` header in the request, the
value of the first header is used. This includes a single header with
comma-separated values, in which the first value is used.
```js
// Host: "example.com:3000"
console.dir(req.host);
// => 'example.com:3000'
// Host: "[::1]:3000"
console.dir(req.host);
// => '[::1]:3000'
```
### req.ip
Type: String.
Contains the remote IP address of the request.
When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting) does not evaluate to `false`,
the value of this property is derived from the left-most entry in the
`X-Forwarded-For` header. This header can be set by the client or by the proxy.
```js
console.dir(req.ip);
// => '127.0.0.1'
```
### req.ips
Type: String[].
When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting) does not evaluate to `false`,
this property contains an array of IP addresses
specified in the `X-Forwarded-For` request header. Otherwise, it contains an
empty array. This header can be set by the client or by the proxy.
For example, if `X-Forwarded-For` is `client, proxy1, proxy2`, `req.ips` would be
`["client", "proxy1", "proxy2"]`, where `proxy2` is the furthest downstream.
```js
// normal request, or `trust proxy` disabled (the default)
console.dir(req.ips);
// => []
// app.set('trust proxy', true) and
// request header `X-Forwarded-For: client, proxy1, proxy2`
console.dir(req.ips);
// => ['client', 'proxy1', 'proxy2']
```
### req.method
Type: String.
Contains a string corresponding to the HTTP method of the request:
`GET`, `POST`, `PUT`, and so on.
```js
app.use((req, res, next) => {
console.dir(req.method);
// => 'GET'
next();
});
```
```ts
app.use((req: Request, res: Response, next: NextFunction) => {
console.dir(req.method);
// => 'GET'
next();
});
```
### req.originalUrl
Type: String.
`req.url` is not a native Express property, it is inherited from Node's [http
module](https://nodejs.org/api/http.html#messageurl).
This property is much like `req.url`; however, it retains the original request URL,
allowing you to rewrite `req.url` freely for internal routing purposes. For example,
the "mounting" feature of [app.use()](/api/application/#appuse) will rewrite `req.url` to strip the mount point.
```js
// GET /search?q=something
console.dir(req.originalUrl);
// => '/search?q=something'
```
`req.originalUrl` is available both in middleware and router objects, and is a
combination of `req.baseUrl` and `req.url`. Consider following example:
```js
// GET 'http://www.example.com/admin/new?sort=desc'
app.use('/admin', (req, res, next) => {
console.dir(req.originalUrl); // '/admin/new?sort=desc'
console.dir(req.baseUrl); // '/admin'
console.dir(req.path); // '/new'
next();
});
```
```ts
// GET 'http://www.example.com/admin/new?sort=desc'
app.use('/admin', (req: Request, res: Response, next: NextFunction) => {
console.dir(req.originalUrl); // '/admin/new?sort=desc'
console.dir(req.baseUrl); // '/admin'
console.dir(req.path); // '/new'
next();
});
```
### req.params
Type: Object.
This property is an object containing properties mapped to the [named route "parameters"](/guide/routing/#route-parameters). For example, if you have the route `/user/:name`, then the "name" property is available as `req.params.name`. This object defaults to `Object.create(null)` when using string paths, but remains a standard object with a normal prototype when the path is defined with a regular expression.
```js
// GET /user/tj
console.dir(req.params.name);
// => 'tj'
```
Properties corresponding to wildcard parameters are arrays containing separate path segments split on `/`:
```js
app.get('/files/*file', (req, res) => {
console.dir(req.params.file);
// GET /files/note.txt
// => [ 'note.txt' ]
// GET /files/images/image.png
// => [ 'images', 'image.png' ]
});
```
```ts
app.get('/files/*file', (req: Request, res: Response) => {
console.dir(req.params.file);
// GET /files/note.txt
// => [ 'note.txt' ]
// GET /files/images/image.png
// => [ 'images', 'image.png' ]
});
```
Parameters defined in [optional segments](/guide/routing/#optional-segments) that are not present in the request URL are omitted from `req.params` entirely.
When you use a regular expression for the route definition, capture groups are provided as integer keys using `req.params[n]`, where `n` is the nth capture group.
```js
app.use(/^\/file\/(.*)$/, (req, res) => {
// GET /file/javascripts/jquery.js
console.dir(req.params[0]);
// => 'javascripts/jquery.js'
});
```
```ts
app.use(/^\/file\/(.*)$/, (req: Request, res: Response) => {
// GET /file/javascripts/jquery.js
console.dir(req.params[0]);
// => 'javascripts/jquery.js'
});
```
Named capturing groups in regular expressions behave like named route parameters. For example the group from `/^\/file\/(?.*)$/` expression is available as `req.params.path`.
If you need to make changes to a key in `req.params`, use the [app.param](/api/application/#appparam) handler. Changes are applicable only to [parameters](/guide/routing/#route-parameters) already defined in the route path.
Any changes made to the `req.params` object in a middleware or route handler will be reset.
Express automatically decodes the values in `req.params` (using `decodeURIComponent`).
### req.path
Type: String.
Contains the path part of the request URL.
```js
// example.com/users?sort=desc
console.dir(req.path);
// => '/users'
```
When called from a middleware, the mount point is not included in `req.path`. See
[app.use()](/api/application/#appuse) for more details.
### req.protocol
Type: String.
Contains the request protocol string: either `http` or (for TLS requests) `https`.
When the [`trust proxy` setting](/api/application/#options-for-trust-proxy-setting) does not evaluate to `false`,
this property will use the value of the `X-Forwarded-Proto` header field if present.
This header can be set by the client or by the proxy.
```js
console.dir(req.protocol);
// => 'http'
```
### req.query
Type: Object.
This property is an object containing a property for each query string parameter in the route.
When [query parser](/api/application/#application-settings) is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.
As `req.query`'s shape is based on user-controlled input, all properties and values in this object
are untrusted and should be validated before trusting. For example, `req.query.foo.toString()` may
fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString`
may not be a function and instead a string or other user-input.
The value of this property can be configured with the [query parser application setting](/api/application/#application-settings) to work how your application needs it. A very popular query string parser is the [`qs` module](https://www.npmjs.com/package/qs), and this is used by default. The `qs` module is very configurable with many settings, and it may be desirable to use different settings than the default to populate `req.query`:
```cjs title="index.cjs"
const qs = require('qs');
app.set('query parser', (str) =>
qs.parse(str, {
/* custom options */
})
);
```
```mjs title="index.mjs"
app.set('query parser', (str) =>
qs.parse(str, {
/* custom options */
})
);
```
```ts title="index.ts"
app.set('query parser', (str: string) =>
qs.parse(str, {
/* custom options */
})
);
```
Check out the [query parser application setting](/api/application/#application-settings) documentation for other customization options.
### req.res
Type: Response.
This property holds a reference to the [response object](/api/response)
that relates to this request object.
```js
app.get('/', (req, res) => {
console.dir(req.res === res);
// => true
res.send('OK');
});
```
```ts
app.get('/', (req: Request, res: Response) => {
console.dir(req.res === res);
// => true
res.send('OK');
});
```
### req.route
Type: Route.
Contains the currently-matched route (a `Route` object). For example:
```js
app.get('/user/{:id}', (req, res) => {
console.dir(req.route, { depth: null });
res.send('GET');
});
```
```ts
app.get('/user/{:id}', (req: Request, res: Response) => {
console.dir(req.route, { depth: null });
res.send('GET');
});
```
Example output from the previous snippet:
```
Route {
path: '/user/{:id}',
stack: [
Layer {
handle: [Function (anonymous)],
keys: [],
name: '',
params: undefined,
path: undefined,
slash: false,
matchers: [ [Function: match] ],
method: 'get'
}
],
methods: [Object: null prototype] { get: true }
}
```
### req.secure
Type: Boolean.
A Boolean property that is true if a TLS connection is established. Equivalent to the following:
{/* */}
```js
req.protocol === 'https';
```
### req.signedCookies
Type: Object.
When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property
contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside
in a different object to show developer intent; otherwise, a malicious attack could be placed on
`req.cookie` values (which are easy to spoof). Note that signing a cookie does not make it "hidden"
or encrypted; but simply prevents tampering (because the secret used to sign is private).
If no signed cookies are sent, the property defaults to `{}`.
```js
// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3
console.dir(req.signedCookies.user);
// => 'tobi'
```
For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser).
### req.stale
Type: Boolean.
Indicates whether the request is "stale," and is the opposite of `req.fresh`.
For more information, see [req.fresh](#reqfresh).
```js
console.dir(req.stale);
// => true
```
### req.subdomains
Type: String[].
An array of subdomains in the domain name of the request.
```js
// Host: "tobi.ferrets.example.com"
console.dir(req.subdomains);
// => ['ferrets', 'tobi']
```
The application property `subdomain offset`, which defaults to 2, is used for determining the
beginning of the subdomain segments. To change this behavior, change its value
using [app.set](/api/application/#appset).
### req.xhr
Type: Boolean.
A Boolean property that is `true` if the request's `X-Requested-With` header field is
"XMLHttpRequest", indicating that the request was issued by a client library such as jQuery.
```js
console.dir(req.xhr);
// => true
```
## Methods
The `req` object also contains a number of methods that can be used to perform various tasks related to the HTTP request, such as checking the content type, retrieving header values, and more.
### req.accepts()
Returns: String | false.
Arguments:
- types (String | String[]):
The content type(s) to check: a MIME type (such as `application/json`), an extension name
(such as `json`), a comma-delimited list, or an array.
Checks if the specified content types are acceptable, based on the request's `Accept` HTTP header field.
The method returns the best match, or if none of the specified content types is acceptable, returns
`false` (in which case, the application should respond with `406 "Not Acceptable"`).
The `type` value may be a single MIME type string (such as "application/json"),
an extension name such as "json", a comma-delimited list, or an array. For a
list or array, the method returns the _best_ match (if any).
```js
// Accept: text/html
req.accepts('html');
// => 'html'
// Accept: text/*, application/json
req.accepts('html');
// => 'html'
req.accepts('text/html');
// => 'text/html'
req.accepts(['json', 'text']);
// => 'json'
req.accepts('application/json');
// => 'application/json'
// Accept: text/*, application/json
req.accepts('image/png');
req.accepts('png');
// => false
// Accept: text/*;q=.5, application/json
req.accepts(['html', 'json']);
// => 'json'
```
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsCharsets()
Returns: String | false.
Arguments:
- charset (String | String[]):
One or more character sets to test against the request's `Accept-Charset` header.
Returns the first accepted charset of the specified character sets,
based on the request's `Accept-Charset` HTTP header field.
If none of the specified charsets is accepted, returns `false`.
```js
// Accept-Charset: utf-8, iso-8859-1;q=0.5
req.acceptsCharsets('utf-8', 'iso-8859-1');
// => 'utf-8'
req.acceptsCharsets('us-ascii');
// => false
```
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsEncodings()
Returns: String | false.
Arguments:
- encoding (String | String[]):
One or more encodings to test against the request's `Accept-Encoding` header.
Returns the first accepted encoding of the specified encodings,
based on the request's `Accept-Encoding` HTTP header field.
If none of the specified encodings is accepted, returns `false`.
```js
// Accept-Encoding: gzip, deflate
req.acceptsEncodings('gzip', 'deflate');
// => 'gzip'
req.acceptsEncodings('br');
// => false
```
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsLanguages()
Returns: String | String[] | false.
Arguments:
- lang (String | String[], optional):
One or more languages to test against the request's `Accept-Language` header. If omitted, all
accepted languages are returned as an array.
Returns the first accepted language of the specified languages,
based on the request's `Accept-Language` HTTP header field.
If none of the specified languages is accepted, returns `false`.
If no `lang` argument is given, then `req.acceptsLanguages()`
returns all languages from the HTTP `Accept-Language` header
as an `Array`.
```js
// Accept-Language: en;q=0.8, es
req.acceptsLanguages('en', 'es');
// => 'es'
req.acceptsLanguages();
// => ['es', 'en']
```
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
Express (5.x) source: [request.js line 172](https://github.com/expressjs/express/blob/v5.1.0/lib/request.js#L172)
Accepts (2.0) source: [index.js line 195](https://github.com/jshttp/accepts/blob/2.0.0/index.js#L195)
### req.get()
Returns: String | undefined.
Arguments:
- field (String):
The name of the HTTP request header to read (case-insensitive). `Referrer` and `Referer` are
interchangeable.
Returns the specified HTTP request header field (case-insensitive match).
The `Referrer` and `Referer` fields are interchangeable.
```js
req.get('Content-Type');
// => 'text/plain'
req.get('content-type');
// => 'text/plain'
req.get('Something');
// => undefined
```
Aliased as `req.header(field)`.
### req.is()
Returns: String | false | null.
Arguments:
- type (String | String[]):
The MIME type(s) or extension name(s) to match against the request's `Content-Type` header.
Returns the matching content type if the incoming request's "Content-Type" HTTP header field
matches the MIME type specified by the `type` parameter. If the request has no body, returns `null`.
Returns `false` otherwise.
```js
// With Content-Type: text/html; charset=utf-8
req.is('html'); // => 'html'
req.is('text/html'); // => 'text/html'
req.is('text/*'); // => 'text/*'
// When Content-Type is application/json
req.is('json'); // => 'json'
req.is('application/json'); // => 'application/json'
req.is('application/*'); // => 'application/*'
// Using arrays
// When Content-Type is application/json
req.is(['json', 'html']); // => 'json'
// Using multiple arguments
// When Content-Type is application/json
req.is('json', 'html'); // => 'json'
req.is('html'); // => false
req.is(['xml', 'yaml']); // => false
req.is('xml', 'yaml'); // => false
```
For more information, or if you have issues or concerns, see [type-is](https://github.com/expressjs/type-is).
### req.range()
Returns: Array | Number.
Arguments:
- size (Number):
The maximum size of the resource.
- options (Object, optional):
Options for parsing the `Range` header.
Properties:
- combine (Boolean, default: false):
Specify if overlapping and adjacent ranges should be combined. When `true`, ranges are
combined and returned as if they were specified that way in the header.
```js
// Range: bytes=0-99,50-149
const separate = req.range(1000, { combine: false });
console.log(separate[0]); // => { start: 0, end: 99 }
console.log(separate[1]); // => { start: 50, end: 149 }
const combined = req.range(1000, { combine: true });
console.log(combined[0]); // => { start: 0, end: 149 }
```
`Range` header parser.
An array of ranges will be returned or negative numbers indicating an error parsing.
- `-2` signals a malformed header string
- `-1` signals an unsatisfiable range
```js
// parse header from request
const range = req.range(1000);
// the type of the range
if (range.type === 'bytes') {
// the ranges
range.forEach((r) => {
// do something with r.start and r.end
});
}
```
---
## Response
URL: https://expressjs.com/en/5x/api/response
The `res` object represents the HTTP response that an Express app sends when it gets an HTTP request.
In this documentation and by convention,
the object is always referred to as `res` (and the HTTP request is `req`) but its actual name is determined
by the parameters to the callback function in which you're working.
For example:
```js
app.get('/user/:id', (req, res) => {
res.send(`user ${req.params.id}`);
});
```
```ts
app.get('/user/:id', (req: Request, res: Response) => {
res.send(`user ${req.params.id}`);
});
```
But you could just as well have:
```js
app.get('/user/:id', (request, response) => {
response.send(`user ${request.params.id}`);
});
```
```ts
app.get('/user/:id', (request: Request, response: Response) => {
response.send(`user ${request.params.id}`);
});
```
The `res` object is an enhanced version of Node's own response object
and supports all [built-in fields and methods](https://nodejs.org/api/http.html#class-httpserverresponse).
## Properties
### res.app
Type: Application.
This property holds a reference to the instance of the Express application that is using the middleware.
`res.app` is identical to the [req.app](/api/request/#reqapp) property in the request object.
```js
app.get('/', (req, res) => {
console.dir(res.app.get('view engine'));
console.dir(res.app === req.app);
// => true
res.send('OK');
});
```
```ts
app.get('/', (req: Request, res: Response) => {
console.dir(res.app.get('view engine'));
console.dir(res.app === req.app);
// => true
res.send('OK');
});
```
### res.headersSent
Type: Boolean.
Boolean property that indicates if the app sent HTTP headers for the response.
```js
app.get('/', (req, res) => {
console.log(res.headersSent); // false
res.send('OK');
console.log(res.headersSent); // true
});
```
```ts
app.get('/', (req: Request, res: Response) => {
console.log(res.headersSent); // false
res.send('OK');
console.log(res.headersSent); // true
});
```
### res.locals
Type: Object.
Use this property to set variables accessible in templates rendered with [res.render](#resrender).
The variables set on `res.locals` are available within a single request-response cycle, and will not
be shared between requests.
The `locals` object is used by view engines to render a response. The object keys may be
particularly sensitive and should not contain user-controlled input, as it may affect the
operation of the view engine or provide a path to cross-site scripting. Consult the documentation
for the used view engine for additional considerations.
In order to keep local variables for use in template rendering between requests, use
[app.locals](/api/application/#applocals) instead.
This property is useful for exposing request-level information such as the request path name,
authenticated user, user settings, and so on to templates rendered within the application.
```js
app.use((req, res, next) => {
// Make `user` and `authenticated` available in templates
res.locals.user = req.user;
res.locals.authenticated = !req.user.anonymous;
next();
});
```
```ts
app.use((req: Request, res: Response, next: NextFunction) => {
// Make `user` and `authenticated` available in templates
res.locals.user = req.user;
res.locals.authenticated = !req.user.anonymous;
next();
});
```
### res.req
Type: Request.
This property holds a reference to the [request object](/api/request/)
that relates to this response object.
```js
app.get('/', (req, res) => {
console.dir(res.req === req);
// => true
res.send('OK');
});
```
```ts
app.get('/', (req: Request, res: Response) => {
console.dir(res.req === req);
// => true
res.send('OK');
});
```
## Methods
### res.append()
Returns: Response.
Arguments:
- field (String):
The name of the HTTP response header to append to.
- value (String | String[], optional):
The value(s) to append to the header.
Appends the specified `value` to the HTTP response header `field`. If the header is not already set,
it creates the header with the specified value. The `value` parameter can be a string or an array.
calling `res.set()` after `res.append()` will reset the previously-set header value.
```js
res.append('Link', ['', '']);
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
res.append('Warning', '199 Miscellaneous warning');
```
### res.attachment()
Returns: Response.
Arguments:
- filename (String, optional):
The file name used to set the `Content-Disposition` "filename=" parameter and the
`Content-Type` (from its extension).
Sets the HTTP response `Content-Disposition` header field to "attachment". If a `filename` is given,
then it sets the `Content-Type` based on the extension name via `res.type()`,
and sets the `Content-Disposition` "filename=" parameter.
```js
res.attachment();
// Content-Disposition: attachment
res.attachment('path/to/logo.png');
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png
```
### res.clearCookie()
Returns: Response.
Arguments:
- name (String):
The name of the cookie to clear.
- options (Object, optional):
Cookie options, which should match those given to [res.cookie()](#rescookie) (excluding
`expires` and `maxAge`).
Clears the cookie with the specified `name` by sending a `Set-Cookie` header that sets its expiration date in the past.
This instructs the client that the cookie has expired and is no longer valid. For more information
about available `options`, see [res.cookie()](#rescookie).
The `expires` and `maxAge` options are being ignored completely.
Web browsers and other compliant clients will only clear the cookie if the given `options` is
identical to those given to [res.cookie()](#rescookie)
```js
res.cookie('name', 'tobi', { path: '/admin' });
res.clearCookie('name', { path: '/admin' });
```
### res.cookie()
Returns: Response.
Arguments:
- name (String):
The name of the cookie.
- value (String | Object):
The cookie value; an object is serialized as JSON.
- options (Object, optional):
Options for the `Set-Cookie` header.
Properties:
- domain (String):
Domain name for the cookie. Defaults to the domain name of the app.
- encode (Function):
A synchronous function used for cookie value encoding. Defaults to `encodeURIComponent`.
- expires (Date):
Expiry date of the cookie in GMT. If not specified or set to `0`, creates a session cookie.
- httpOnly (Boolean):
Flags the cookie to be accessible only by the web server.
- maxAge (Number):
Convenient option for setting the expiry time relative to the current time in milliseconds.
- path (String, default: "/"):
Path for the cookie. Defaults to "/".
- partitioned (Boolean):
Indicates that the cookie should be stored using partitioned storage. See [CHIPS](https://developer.mozilla.org/en-US/docs/Web/Privacy/Guides/Third-party_cookies/Partitioned_cookies) for more details.
- priority (String):
Value of the "Priority" **Set-Cookie** attribute.
- secure (Boolean):
Marks the cookie to be used with HTTPS only.
- signed (Boolean):
Indicates if the cookie should be signed.
- sameSite (Boolean | String):
Value of the "SameSite" **Set-Cookie** attribute.
Sets cookie `name` to `value`. The `value` parameter may be a string or object converted to JSON.
All `res.cookie()` does is set the HTTP `Set-Cookie` header with the options provided. Any option
not specified defaults to the value stated in [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265).
For example:
```js
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
res.cookie('remember_me', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
```
You can set multiple cookies in a single response by calling `res.cookie` multiple times, for example:
```js
res
.status(201)
.cookie('access_token', `Bearer ${token}`, {
expires: new Date(Date.now() + 8 * 3600000), // cookie will be removed after 8 hours
})
.cookie('test', 'test')
.redirect(301, '/admin');
```
The `encode` option allows you to choose the function used for cookie value encoding.
Does not support asynchronous functions.
Example use case: You need to set a domain-wide cookie for another site in your organization.
This other site (not under your administrative control) does not use URI-encoded cookie values.
```js
// Default encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' });
// Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/'
// Custom encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', {
domain: 'example.com',
encode: String,
});
// Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;'
```
The `maxAge` option is a convenience option for setting "expires" relative to the current time in milliseconds.
The following is equivalent to the second example above.
```js
res.cookie('remember_me', '1', { maxAge: 900000, httpOnly: true });
```
You can pass an object as the `value` parameter; it is then serialized as JSON and parsed by `bodyParser()` middleware.
```js
res.cookie('cart', { items: [1, 2, 3] });
res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });
```
When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this method also
supports signed cookies. Simply include the `signed` option set to `true`.
Then, `res.cookie()` will use the secret passed to `cookieParser(secret)` to sign the value.
```js
res.cookie('name', 'tobi', { signed: true });
```
Later, you may access this value through the [req.signedCookies](/api/request/#reqsignedcookies) object.
### res.download()
Arguments:
- path (String):
The path to the file to transfer. If relative, it is resolved against the current working directory or the `root` option.
- filename (String, optional):
The file name for the `Content-Disposition` "filename=" parameter; overrides the name derived from `path`.
- options (Object, optional):
Options forwarded to [res.sendFile()](#ressendfile).
Properties:
- maxAge (Number | String, default: 0):
Sets the max-age property of the `Cache-Control` header in milliseconds, or a string in [ms format](https://www.npmjs.com/package/ms).
- root (String):
Root directory for relative file names.
- lastModified (Boolean, default: true):
Sets the `Last-Modified` header to the last modified date of the file on the OS. Set `false` to disable it.
- headers (Object):
Object containing HTTP headers to serve with the file.
- dotfiles (String, default: "ignore"):
Option for serving dotfiles. Possible values are `"allow"`, `"deny"`, and `"ignore"`.
- acceptRanges (Boolean, default: true):
Enable or disable accepting ranged requests.
- cacheControl (Boolean, default: true):
Enable or disable setting the `Cache-Control` response header.
- immutable (Boolean, default: false):
Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching.
- fn (Function, optional):
Callback `fn(err)` invoked when the transfer completes or an error occurs.
Transfers the file at `path` as an "attachment". Typically, browsers will prompt the user for download.
By default, the `Content-Disposition` header "filename=" parameter is derived from the `path` argument, but can be overridden with the `filename` parameter.
If `path` is relative, then it will be based on the current working directory of the process or
the `root` option, if provided.
This API provides access to data on the running file system. Ensure that either (a) the way in
which the `path` argument was constructed is secure if it contains user input or (b) set the `root`
option to the absolute path of a directory to contain access within.
When the `root` option is provided, Express will validate that the relative path provided as
`path` will resolve within the given `root` option.
The method invokes the callback function `fn(err)` when the transfer is complete
or when an error occurs. If the callback function is specified and an error occurs,
the callback function must explicitly handle the response process either by
ending the request-response cycle, or by passing control to the next route.
```js
res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
res.download('/report-12345.pdf', 'report.pdf', (err) => {
if (err) {
// Handle error, but keep in mind the response may be partially-sent
// so check res.headersSent
} else {
// decrement a download credit, etc.
}
});
```
### res.end()
Returns: Response.
Arguments:
- data (String | Buffer, optional):
Data to write before ending the response.
- encoding (String, optional):
The encoding for `data` when it is a string.
- callback (Function, optional):
Called once the response has finished.
Ends the response process. This method actually comes from Node core, specifically the [response.end() method of http.ServerResponse](https://nodejs.org/api/http.html#responseenddata-encoding-callback).
Use to quickly end the response without any data. If you need to respond with data, instead use methods such as [res.send()](#ressend) and [res.json()](#resjson).
```js
res.end();
res.status(404).end();
```
### res.format()
Returns: Response.
Arguments:
- object (Object):
An object whose keys are MIME types (or extension names) mapped to handler functions,
optionally with a `default` handler.
Performs content-negotiation on the `Accept` HTTP header on the request object, when present.
It uses [req.accepts()](/api/request/#reqaccepts) to select a handler for the request, based on the acceptable
types ordered by their quality values. If the header is not specified, the first callback is invoked.
When no match is found, the server responds with 406 "Not Acceptable", or invokes the `default` callback.
The `Content-Type` response header is set when a callback is selected. However, you may alter
this within the callback using methods such as `res.set()` or `res.type()`.
The following example would respond with `{ "message": "hey" }` when the `Accept` header field is set
to "application/json" or "\*/json" (however, if it is "\*/\*", then the response will be "hey").
```js
res.format({
'text/plain'() {
res.send('hey');
},
'text/html'() {
res.send('hey
');
},
'application/json'() {
res.send({ message: 'hey' });
},
default() {
// log the request and respond with 406
res.status(406).send('Not Acceptable');
},
});
```
In addition to canonicalized MIME types, you may also use extension names mapped
to these types for a slightly less verbose implementation:
```js
res.format({
text() {
res.send('hey');
},
html() {
res.send('hey
');
},
json() {
res.send({ message: 'hey' });
},
});
```
### res.get()
Returns: String.
Arguments:
- field (String):
The name of the response header to read (case-insensitive).
Returns the HTTP response header specified by `field`.
The match is case-insensitive.
```js
res.get('Content-Type');
// => 'text/plain'
```
### res.json()
Returns: Response.
Arguments:
- body (any, optional):
The value to send as JSON. Can be any JSON type: object, array, string, Boolean, number, or
null.
Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a
JSON string using [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
The parameter can be any JSON type, including object, array, string, Boolean, number, or null,
and you can also use it to convert other values to JSON.
```js
res.json(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });
```
### res.jsonp()
Returns: Response.
Arguments:
- body (any, optional):
The value to send as a JSONP response. Can be any JSON type.
Sends a JSON response with JSONP support. This method is identical to `res.json()`,
except that it opts-in to JSONP callback support.
```js
res.jsonp(null);
// => callback(null)
res.jsonp({ user: 'tobi' });
// => callback({ "user": "tobi" })
res.status(500).jsonp({ error: 'message' });
// => callback({ "error": "message" })
```
By default, the JSONP callback name is simply `callback`. Override this with the
[jsonp callback name](/api/application/#application-settings) setting.
The following are some examples of JSONP responses using the same code:
```js
// ?callback=foo
res.jsonp({ user: 'tobi' });
// => foo({ "user": "tobi" })
app.set('jsonp callback name', 'cb');
// ?cb=foo
res.status(500).jsonp({ error: 'message' });
// => foo({ "error": "message" })
```
### res.links()
Returns: Response.
Arguments:
- links (Record):
An object whose properties (such as `next` and `last`) populate the `Link` response header.
Each value can be a single URL string, or an array of URL strings to emit multiple links for
the same relation.
Joins the `links` provided as properties of the parameter to populate the response's
`Link` HTTP header field.
For example, the following call:
```js
res.links({
next: 'http://api.example.com/users?page=2',
last: 'http://api.example.com/users?page=5',
});
```
Yields the following results:
```
Link: ; rel="next",
; rel="last"
```
### res.location()
Returns: Response.
Arguments:
- path (String):
The URL to set in the `Location` header.
Sets the response `Location` HTTP header to the specified `path` parameter.
```js
res.location('/foo/bar');
res.location('http://example.com');
```
After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the `Location` header,
without any validation.
Browsers take the responsibility of deriving the intended URL from the current URL
or the referring URL, and the URL specified in the `Location` header; and redirect the user accordingly.
### res.redirect()
Arguments:
- status (Number, optional):
The HTTP status code to use. Defaults to `302` (Found).
- path (String):
The URL to redirect to.
Redirects to the URL derived from the specified `path`, with specified `status`, a positive integer
that corresponds to an [HTTP status code](https://www.rfc-editor.org/rfc/rfc9110#name-status-codes).
If not specified, `status` defaults to `302 "Found"`.
```js
res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');
```
Redirects can be a fully-qualified URL for redirecting to a different site:
```js
res.redirect('https://google.com');
```
Redirects can be relative to the root of the host name. For example, if the
application is on `http://example.com/admin/post/new`, the following
would redirect to the URL `http://example.com/admin`:
```js
res.redirect('/admin');
```
Redirects can be relative to the current URL. For example,
from `http://example.com/blog/admin/` (notice the trailing slash), the following
would redirect to the URL `http://example.com/blog/admin/post/new`.
```js
res.redirect('post/new');
```
Redirecting to `post/new` from `http://example.com/blog/admin` (no trailing slash),
will redirect to `http://example.com/blog/post/new`.
If you found the above behavior confusing, think of path segments as directories
(with trailing slashes) and files, it will start to make sense.
Path-relative redirects are also possible. If you were on
`http://example.com/admin/post/new`, the following would redirect to
`http://example.com/admin/post`:
```js
res.redirect('..');
```
See also [Security best practices: Prevent open redirect
vulnerabilities](/advanced/best-practice-security/#prevent-open-redirects).
### res.render()
Arguments:
- view (String):
The file path of the view to render (absolute or relative to the `views` setting).
- locals (Object, optional):
An object whose properties define local variables for the view.
- callback (Function, optional):
Called as `callback(err, html)`. When provided, the rendered HTML is not sent automatically.
Renders a `view` and sends the rendered HTML string to the client.
Optional parameters:
- `locals`, an object whose properties define local variables for the view.
- `callback`, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes `next(err)` internally.
The `view` argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the `views` setting. If the path does not contain a file extension, then the `view engine` setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via `require()`) and render it using the loaded module's `__express` function.
For more information, see [Using template engines with Express](/guide/using-template-engines).
The `view` argument performs file system operations like reading a file from disk and evaluating
Node.js modules, and as so for security reasons should not contain input from the end-user.
The `locals` object is used by view engines to render a response. The object keys may be
particularly sensitive and should not contain user-controlled input, as it may affect the
operation of the view engine or provide a path to cross-site scripting. Consult the documentation
for the used view engine for additional considerations.
The local variable `cache` enables view caching. Set it to `true`, to cache the view during
development; view caching is enabled in production by default.
```js
// send the rendered view to the client
res.render('index');
// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', (err, html) => {
res.send(html);
});
// pass a local variable to the view
res.render('user', { name: 'Tobi' }, (err, html) => {
// ...
});
```
### res.send()
Returns: Response.
Arguments:
- body (String | Buffer | Object | Array | Boolean, optional):
The response body. Strings are sent as HTML; objects and arrays as JSON; Buffers as binary.
Sends the HTTP response.
The `body` parameter can be a `Buffer` object, a `String`, an object, `Boolean`, or an `Array`.
For example:
```js
res.send(Buffer.from('whoop'));
res.send({ some: 'json' });
res.send('some html
');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });
```
This method performs many useful tasks for simple non-streaming responses:
For example, it automatically assigns the `Content-Length` HTTP response header field
and provides automatic HEAD and HTTP cache freshness support.
When the parameter is a `Buffer` object, the method sets the `Content-Type`
response header field to "application/octet-stream", unless previously defined as shown below:
```js
res.set('Content-Type', 'text/html');
res.send(Buffer.from('some html
'));
```
When the parameter is a `String`, the method sets the `Content-Type` to "text/html":
```js
res.send('some html
');
```
When the parameter is an `Array` or `Object`, Express responds with the JSON representation:
```js
res.send({ user: 'tobi' });
res.send([1, 2, 3]);
```
### res.sendFile()
Arguments:
- path (String):
The path to the file to transfer. Must be absolute unless the `root` option is set.
- options (Object, optional):
Options for serving the file.
Properties:
- maxAge (Number | String, default: 0):
Sets the max-age property of the `Cache-Control` header in milliseconds, or a string in [ms format](https://www.npmjs.com/package/ms).
- root (String):
Root directory for relative file names.
- lastModified (Boolean, default: true):
Sets the `Last-Modified` header to the last modified date of the file on the OS. Set `false` to disable it.
- headers (Object):
Object containing HTTP headers to serve with the file.
- dotfiles (String, default: "ignore"):
Option for serving dotfiles. Possible values are `"allow"`, `"deny"`, and `"ignore"`.
- acceptRanges (Boolean, default: true):
Enable or disable accepting ranged requests.
- cacheControl (Boolean, default: true):
Enable or disable setting the `Cache-Control` response header.
- immutable (Boolean, default: false):
Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching.
- fn (Function, optional):
Callback `fn(err)` invoked when the transfer completes or an error occurs.
Transfers the file at the given `path`. Sets the `Content-Type` response HTTP header field
based on the filename's extension. Unless the `root` option is set in
the options object, `path` must be an absolute path to the file.
This API provides access to data on the running file system. Ensure that either (a) the way in
which the `path` argument was constructed into an absolute path is secure if it contains user
input or (b) set the `root` option to the absolute path of a directory to contain access within.
When the `root` option is provided, the `path` argument is allowed to be a relative path,
including containing `..`. Express will validate that the relative path provided as `path` will
resolve within the given `root` option.
The method invokes the callback function `fn(err)` when the transfer is complete
or when an error occurs. If the callback function is specified and an error occurs,
the callback function must explicitly handle the response process either by
ending the request-response cycle, or by passing control to the next route.
Here is an example of using `res.sendFile` with all its arguments.
```js
app.get('/file/:name', (req, res, next) => {
const options = {
root: path.join(__dirname, 'public'),
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true,
},
};
const fileName = req.params.name;
res.sendFile(fileName, options, (err) => {
if (err) {
next(err);
} else {
console.log('Sent:', fileName);
}
});
});
```
```ts
app.get('/file/:name', (req: Request, res: Response, next: NextFunction) => {
const options = {
root: path.join(__dirname, 'public'),
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true,
},
};
const fileName = req.params.name;
res.sendFile(fileName, options, (err) => {
if (err) {
next(err);
} else {
console.log('Sent:', fileName);
}
});
});
```
The following example illustrates using
`res.sendFile` to provide fine-grained support for serving files:
```js
app.get('/user/:uid/photos/:file', (req, res) => {
const uid = req.params.uid;
const file = req.params.file;
req.user.mayViewFilesFrom(uid, (yes) => {
if (yes) {
res.sendFile(`/uploads/${uid}/${file}`);
} else {
res.status(403).send("Sorry! You can't see that.");
}
});
});
```
```ts
app.get('/user/:uid/photos/:file', (req: Request, res: Response) => {
const uid = req.params.uid;
const file = req.params.file;
req.user.mayViewFilesFrom(uid, (yes) => {
if (yes) {
res.sendFile(`/uploads/${uid}/${file}`);
} else {
res.status(403).send("Sorry! You can't see that.");
}
});
});
```
For more information, or if you have issues or concerns, see [send](https://github.com/pillarjs/send).
### res.sendStatus()
Returns: Response.
Arguments:
- statusCode (Number):
The HTTP status code to set; its registered status message becomes the response body.
Sets the response HTTP status code to `statusCode` and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.
```js
res.sendStatus(404);
```
Some versions of Node.js will throw when `res.statusCode` is set to an invalid HTTP status code
(outside of the range `100` to `599`). Consult the HTTP server documentation for the Node.js
version being used.
[More about HTTP Status Codes](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)
### res.set()
Returns: Response.
Arguments:
- field (String | Object):
The header name, or an object of header name/value pairs to set multiple headers at once.
- value (String | String[], optional):
The header value (when `field` is a string).
Sets the response's HTTP header `field` to `value`.
To set multiple fields at once, pass an object as the parameter.
```js
res.set('Content-Type', 'text/plain');
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
ETag: '12345',
});
```
Aliased as `res.header(field [, value])`.
### res.status()
Returns: Response.
Arguments:
- code (Number):
The HTTP status code for the response.
Sets the HTTP status for the response.
It is a chainable alias of Node's [response.statusCode](https://nodejs.org/api/http.html#responsestatuscode).
```js
res.status(403).end();
res.status(400).send('Bad Request');
res.status(404).sendFile('/absolute/path/to/404.png');
```
### res.type()
Returns: Response.
Arguments:
- type (String):
The MIME type, or a file extension that is looked up to a MIME type. If it contains `/`, it is
used as-is.
Sets the `Content-Type` HTTP header to the MIME type as determined by the specified `type`. If `type` contains the "/" character, then it sets the `Content-Type` to the exact value of `type`, otherwise it is assumed to be a file extension and the MIME type is looked up using the `contentType()` method of the `mime-types` package.
```js
res.type('.html'); // => 'text/html'
res.type('html'); // => 'text/html'
res.type('json'); // => 'application/json'
res.type('application/json'); // => 'application/json'
res.type('png'); // => 'image/png'
```
Aliased as `res.contentType(type)`.
### res.vary()
Returns: Response.
Arguments:
- field (String):
The header field name to add to the `Vary` response header.
Adds the field to the `Vary` response header, if it is not there already.
```js
res.vary('User-Agent').render('docs');
```
---
## Router
URL: https://expressjs.com/en/5x/api/router
A `router` object is an instance of middleware and routes. You can think of it
as a "mini-application," capable only of performing middleware and routing
functions. Every Express application has a built-in app router.
A router behaves like middleware itself, so you can use it as an argument to
[app.use()](/api/application/#appuse) or as the argument to another router's [use()](#routeruse) method.
The top-level `express` object has a [Router()](/api/express/#expressrouter) method that creates a new `router` object.
Once you've created a router object, you can add middleware and HTTP method routes (such as `get`, `put`, `post`,
and so on) to it just like an application. For example:
```js
// invoked for any requests passed to this router
router.use((req, res, next) => {
// .. some logic here .. like any other middleware
next();
});
// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', (req, res, next) => {
// ..
});
```
```ts
// invoked for any requests passed to this router
router.use((req: Request, res: Response, next: NextFunction) => {
// .. some logic here .. like any other middleware
next();
});
// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', (req: Request, res: Response, next: NextFunction) => {
// ..
});
```
You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.
```js
// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router);
```
## Methods
### Router()
Returns: Router.
Arguments:
- options (Object, optional):
Options that configure the router's behavior.
Properties:
- caseSensitive (Boolean, default: false):
Enable case sensitivity. Disabled by default, treating `/Foo` and `/foo` as the same.
- mergeParams (Boolean, default: false):
Preserve the `req.params` values from the parent router. If the parent and the child have conflicting param names, the child's value takes precedence.
- strict (Boolean, default: false):
Enable strict routing. Disabled by default, `/foo` and `/foo/` are treated the same by the router.
Creates a new router object.
```cjs title="index.cjs" ins={2}
const express = require('express');
const router = express.Router({ caseSensitive: true, strict: true });
router.get('/events', (req, res) => {
res.send('events');
});
// mount the router on an app
app.use('/calendar', router);
```
```mjs title="index.mjs" ins={3}
const router = express.Router({ caseSensitive: true, strict: true });
router.get('/events', (req, res) => {
res.send('events');
});
// mount the router on an app
app.use('/calendar', router);
```
```ts title="index.ts"
const router = express.Router({ caseSensitive: true, strict: true });
router.get('/events', (req: Request, res: Response) => {
res.send('events');
});
// mount the router on an app
app.use('/calendar', router);
```
### router.all()
Returns: Router.
Arguments:
- path (String | RegExp | Array):
The path for which the route callbacks are invoked.
- callback (Function | Function[]):
One or more middleware/handler functions. Each may call `next('route')` to skip the remaining
callbacks.
This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
This method is extremely useful for
mapping "global" logic for specific path prefixes or arbitrary matches.
For example, if you placed the following route at the top of all other
route definitions, it would require that all routes from that point on
would require authentication, and automatically load a user. Keep in mind
that these callbacks do not have to act as end points; `loadUser`
can perform a task, then call `next()` to continue matching subsequent
routes.
```js
router.all('{*splat}', requireAuthentication, loadUser);
```
Or the equivalent:
```js
router.all('{*splat}', requireAuthentication);
router.all('{*splat}', loadUser);
```
Another example of this is white-listed "global" functionality. Here,
the example is much like before, but it only restricts paths prefixed with
"/api":
```js
router.all('/api/{*splat}', requireAuthentication);
```
### router.METHOD()
Returns: Router.
Arguments:
- path (String | RegExp | Array):
The path for which the route callbacks are invoked.
- callback (Function | Function[]):
One or more middleware/handler functions. Each may call `next('route')` to skip the remaining
callbacks.
The `router.METHOD()` methods provide the routing functionality in Express,
where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on,
in lowercase. Thus, the actual methods are `router.get()`, `router.post()`,
`router.put()`, and so on.
The `router.get()` function is automatically called for the HTTP `HEAD` method in addition to the
`GET` method if `router.head()` was not called for the path before `router.get()`.
`router.query()` routes HTTP `QUERY` requests, mirroring [`app.query()`](/api/application/#appquery). The `QUERY` method is gated by the runtime and requires Node.js `>=20.19.3 <21 || >=22.2.0`.
You can provide multiple callbacks, and all are treated equally, and behave just
like middleware, except that these callbacks may invoke `next('route')`
to bypass the remaining route callback(s). You can use this mechanism to perform
pre-conditions on a route then pass control to subsequent routes when there is no
reason to proceed with the route matched.
The following snippet illustrates the most simple route definition possible.
Express translates the path strings to regular expressions, used internally
to match incoming requests. Query strings are _not_ considered when performing
these matches, for example "GET /" would match the following route, as would
"GET /?name=tobi".
```js
router.get('/', (req, res) => {
res.send('hello world');
});
```
```ts
router.get('/', (req: Request, res: Response) => {
res.send('hello world');
});
```
You can also use regular expressions—useful if you have very specific
constraints, for example the following would match "GET /commits/71dbb9c" as well
as "GET /commits/71dbb9c..4c084f9".
```js
router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, (req, res) => {
const from = req.params[0];
const to = req.params[1] || 'HEAD';
res.send(`commit range ${from}..${to}`);
});
```
```ts
router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, (req: Request, res: Response) => {
const from = req.params[0];
const to = req.params[1] || 'HEAD';
res.send(`commit range ${from}..${to}`);
});
```
You can use `next` primitive to implement a flow control between different
middleware functions, based on a specific program state. Invoking `next` with
the string `'router'` will cause all the remaining route callbacks on that router
to be bypassed.
The following example illustrates `next('router')` usage.
```js
function fn(req, res, next) {
console.log('I come here');
next('router');
}
router.get('/foo', fn, (req, res, next) => {
console.log("I don't come here");
});
router.get('/foo', (req, res, next) => {
console.log("I don't come here");
});
app.get('/foo', (req, res) => {
console.log(' I come here too');
res.end('good');
});
```
```ts
function fn(req: Request, res: Response, next: NextFunction) {
console.log('I come here');
next('router');
}
router.get('/foo', fn, (req: Request, res: Response, next: NextFunction) => {
console.log("I don't come here");
});
router.get('/foo', (req: Request, res: Response, next: NextFunction) => {
console.log("I don't come here");
});
app.get('/foo', (req: Request, res: Response) => {
console.log(' I come here too');
res.end('good');
});
```
### router.param()
Returns: Router.
Arguments:
- name (String):
The name of the route parameter to attach the trigger to. Unlike `app.param()`, this does not
accept an array.
- callback (Function):
The trigger called as `callback(req, res, next, value, name)`.
Adds callback triggers to route parameters, where `name` is the name of the parameter and `callback` is the callback function. The `name` parameter is required.
The parameters of the callback function are:
- `req`, the request object.
- `res`, the response object.
- `next`, indicating the next middleware function.
- The value of the `name` parameter.
- The name of the parameter.
Unlike `app.param()`, `router.param()` does not accept an array of route parameters.
For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input.
```js
router.param('user', (req, res, next, id) => {
// try to get the user details from the User model and attach it to the request object
User.find(id, (err, user) => {
if (err) {
next(err);
} else if (user) {
req.user = user;
next();
} else {
next(new Error('failed to load user'));
}
});
});
```
```ts
router.param('user', (req: Request, res: Response, next: NextFunction, id: string) => {
// try to get the user details from the User model and attach it to the request object
User.find(id, (err, user) => {
if (err) {
next(err);
} else if (user) {
req.user = user;
next();
} else {
next(new Error('failed to load user'));
}
});
});
```
Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on `router` will be triggered only by route parameters defined on `router` routes.
A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.
```js
router.param('id', (req, res, next, id) => {
console.log('CALLED ONLY ONCE');
next();
});
router.get('/user/:id', (req, res, next) => {
console.log('although this matches');
next();
});
router.get('/user/:id', (req, res) => {
console.log('and this matches too');
res.end();
});
```
```ts
router.param('id', (req: Request, res: Response, next: NextFunction, id: string) => {
console.log('CALLED ONLY ONCE');
next();
});
router.get('/user/:id', (req: Request, res: Response, next: NextFunction) => {
console.log('although this matches');
next();
});
router.get('/user/:id', (req: Request, res: Response) => {
console.log('and this matches too');
res.end();
});
```
On `GET /user/42`, the following is printed:
```
CALLED ONLY ONCE
although this matches
and this matches too
```
### router.route()
Returns: Route.
Arguments:
- path (String):
The path of the route to create.
Returns an instance of a single route which you can then use to handle HTTP verbs
with optional middleware. Use `router.route()` to avoid duplicate route naming and
thus typing errors.
Building on the `router.param()` example above, the following code shows how to use
`router.route()` to specify various HTTP method handlers.
```js
const router = express.Router();
router.param('user_id', (req, res, next, id) => {
// sample user, would actually fetch from DB, etc...
req.user = {
id,
name: 'TJ',
};
next();
});
router
.route('/users/:user_id')
.all((req, res, next) => {
// runs for all HTTP verbs first
// think of it as route specific middleware!
next();
})
.get((req, res, next) => {
res.json(req.user);
})
.put((req, res, next) => {
// just an example of maybe updating the user
req.user.name = req.params.name;
// save user ... etc
res.json(req.user);
})
.post((req, res, next) => {
next(new Error('not implemented'));
})
.delete((req, res, next) => {
next(new Error('not implemented'));
});
```
```ts title="index.ts"
const router = express.Router();
router.param('user_id', (req: Request, res: Response, next: NextFunction, id: string) => {
// sample user, would actually fetch from DB, etc...
req.user = {
id,
name: 'TJ',
};
next();
});
router
.route('/users/:user_id')
.all((req: Request, res: Response, next: NextFunction) => {
// runs for all HTTP verbs first
// think of it as route specific middleware!
next();
})
.get((req: Request, res: Response, next: NextFunction) => {
res.json(req.user);
})
.put((req: Request, res: Response, next: NextFunction) => {
// just an example of maybe updating the user
req.user.name = req.params.name;
// save user ... etc
res.json(req.user);
})
.post((req: Request, res: Response, next: NextFunction) => {
next(new Error('not implemented'));
})
.delete((req: Request, res: Response, next: NextFunction) => {
next(new Error('not implemented'));
});
```
This approach re-uses the single `/users/:user_id` path and adds handlers for
various HTTP methods.
When you use `router.route()`, middleware ordering is based on when the _route_ is created, not
when method handlers are added to the route. For this purpose, you can consider method handlers to
belong to the route to which they were added.
### router.use()
Returns: Router.
Arguments:
- path (String | RegExp | Array, optional):
The mount path for the middleware. Defaults to `/`.
- callback (Function | Function[]):
One or more middleware functions to mount.
Uses the specified middleware function or functions, with optional mount path `path`, that defaults to "/".
This method is similar to [app.use()](/api/application/#appuse). A simple example and use case is described below.
See [app.use()](/api/application/#appuse) for more information.
Middleware is like a plumbing pipe: requests start at the first middleware function defined
and work their way "down" the middleware stack processing for each path they match.
```cjs title="index.cjs"
const express = require('express');
const app = express();
const router = express.Router();
// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use((req, res, next) => {
console.log('%s %s %s', req.method, req.url, req.path);
next();
});
// this will only be invoked if the path starts with /bar from the mount point
router.use('/bar', (req, res, next) => {
// ... maybe some additional /bar logging ...
next();
});
// always invoked
router.use((req, res, next) => {
res.send('Hello World');
});
app.use('/foo', router);
app.listen(3000);
```
```mjs title="index.mjs"
const app = express();
const router = express.Router();
// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use((req, res, next) => {
console.log('%s %s %s', req.method, req.url, req.path);
next();
});
// this will only be invoked if the path starts with /bar from the mount point
router.use('/bar', (req, res, next) => {
// ... maybe some additional /bar logging ...
next();
});
// always invoked
router.use((req, res, next) => {
res.send('Hello World');
});
app.use('/foo', router);
app.listen(3000);
```
```ts title="index.ts"
const app = express();
const router = express.Router();
// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use((req: Request, res: Response, next: NextFunction) => {
console.log('%s %s %s', req.method, req.url, req.path);
next();
});
// this will only be invoked if the path starts with /bar from the mount point
router.use('/bar', (req: Request, res: Response, next: NextFunction) => {
// ... maybe some additional /bar logging ...
next();
});
// always invoked
router.use((req: Request, res: Response, next: NextFunction) => {
res.send('Hello World');
});
app.use('/foo', router);
app.listen(3000);
```
The "mount" path is stripped and is _not_ visible to the middleware function.
The main effect of this feature is that a mounted middleware function may operate without
code changes regardless of its "prefix" pathname.
The order in which you define middleware with `router.use()` is very important.
They are invoked sequentially, thus the order defines middleware precedence. For example,
usually a logger is the very first middleware you would use, so that every request gets logged.
```cjs title="index.cjs"
const logger = require('morgan');
router.use(logger());
router.use(express.static(path.join(__dirname, 'public')));
router.use((req, res) => {
res.send('Hello');
});
```
```mjs title="index.mjs"
router.use(logger());
router.use(express.static(path.join(__dirname, 'public')));
router.use((req, res) => {
res.send('Hello');
});
```
```ts title="index.ts"
router.use(logger());
router.use(express.static(path.join(__dirname, 'public')));
router.use((req: Request, res: Response) => {
res.send('Hello');
});
```
Now suppose you wanted to ignore logging requests for static files, but to continue
logging routes and middleware defined after `logger()`. You would simply move the call to `express.static()` to the top,
before adding the logger middleware:
```js
router.use(express.static(path.join(__dirname, 'public')));
router.use(logger());
router.use((req, res) => {
res.send('Hello');
});
```
```ts
router.use(express.static(path.join(__dirname, 'public')));
router.use(logger());
router.use((req: Request, res: Response) => {
res.send('Hello');
});
```
Another example is serving files from multiple directories,
giving precedence to "./public" over the others:
```js
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'files')));
app.use(express.static(path.join(__dirname, 'uploads')));
```
The `router.use()` method also supports named parameters so that your mount points
for other routers can benefit from preloading using named parameters.
Although these middleware functions are added via a particular router, _when_
they run is defined by the path they are attached to (not the router). Therefore,
middleware added via one router may run for other routers if its routes
match.
For example, this code shows two different routers mounted on the same path:
```js
const authRouter = express.Router();
const openRouter = express.Router();
authRouter.use(require('./authenticate').basic(usersdb));
authRouter.get('/:user_id/edit', (req, res, next) => {
// ... Edit user UI ...
});
openRouter.get('/', (req, res, next) => {
// ... List users ...
});
openRouter.get('/:user_id', (req, res, next) => {
// ... View user ...
});
app.use('/users', authRouter);
app.use('/users', openRouter);
```
```ts
const authRouter = express.Router();
const openRouter = express.Router();
authRouter.use(basic(usersdb));
authRouter.get('/:user_id/edit', (req: Request, res: Response, next: NextFunction) => {
// ... Edit user UI ...
});
openRouter.get('/', (req: Request, res: Response, next: NextFunction) => {
// ... List users ...
});
openRouter.get('/:user_id', (req: Request, res: Response, next: NextFunction) => {
// ... View user ...
});
app.use('/users', authRouter);
app.use('/users', openRouter);
```
Even though the authentication middleware was added via the `authRouter` it will run on the routes defined by the `openRouter` as well since both routers were mounted on `/users`. To avoid this behavior, use different paths for each router.