Request Object

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:

app.get('/user/:id', (req, res) => {
res.send(`user ${req.params.id}`);
});

But you could just as well have:

app.get('/user/:id', (request, 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.

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

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:

index.cjs
app.get('/viewdirectory', require('./mymiddleware.cjs'));

And the middleware module itself:

mymiddleware.cjs
module.exports = (req, res) => {
res.send(`The views directory is ${req.app.get('views')}`);
};

req.baseUrl

The URL path on which a router instance was mounted.

The req.baseUrl property is similar to the mountpath property of the app object, except app.mountpath returns the matched path pattern(s).

For example:

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'

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.

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

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() or express.urlencoded().

Warning

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.

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);
});

req.cookies

When using cookie-parser middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to {}.

// Cookie: name=tj
console.dir(req.cookies.name);
// => "tj"

If the cookie has been signed, you have to use req.signedCookies.

For more information, issues, or concerns, see cookie-parser.

req.fresh

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.

console.dir(req.fresh);
// => true

req.host

Contains the host derived from the Host HTTP header.

When the 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.

// Host: "example.com:3000"
console.dir(req.host);
// => 'example.com:3000'
// Host: "[::1]:3000"
console.dir(req.host);
// => '[::1]:3000'

req.hostname

Contains the hostname derived from the Host HTTP header.

When the 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.

// Host: "example.com:3000"
console.dir(req.hostname);
// => 'example.com'

req.ip

Contains the remote IP address of the request.

When the 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.

console.dir(req.ip);
// => "127.0.0.1"

req.ips

When the 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.

// 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

Contains a string corresponding to the HTTP method of the request: GET, POST, PUT, and so on.

app.use((req, res, next) => {
console.dir(req.method);
// => 'GET'
next();
});

req.originalUrl

Caution

req.url is not a native Express property, it is inherited from Node’s http module.

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() will rewrite req.url to strip the mount point.

// 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:

// 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();
});

req.params

This property is an object containing properties mapped to the named 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.

// GET /user/tj
console.dir(req.params.name);
// => "tj"

Properties corresponding to wildcard parameters are arrays containing separate path segments split on /:

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' ]
});

Parameters defined in 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.

app.use(/^\/file\/(.*)$/, (req, res) => {
// GET /file/javascripts/jquery.js
console.dir(req.params[0]);
// => "javascripts/jquery.js"
});