Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 43 ยท Request and Response

The Request Object

Tour the Express request object: req.method, path, query, headers, req.get, ip, hostname, protocol, content negotiation with req.accepts and the trust proxy setting.

Every handler receives a request object, conventionally named req. In Express it is Node's http.IncomingMessage with extra properties and methods added on top. Everything the client sent is on it: the method, the URL, the headers, the parsed query string, the route parameters and, once a parser has run, the body.

This lesson walks through the properties you will use every day, shows how Express decides things like the client's IP address, and explains content negotiation. Real Express code is read-only on this site; the runnable examples use our stand-in framework, extended in the examples with the same helper names so you can watch the behavior. Where the stand-in only imitates something, the text says so.

What lives on req

Where method, path, query, params
What headers, body, cookies
Who ip, hostname, protocol
How accepts, is, get

Most of it is read-only information about the incoming request.

1 / 2

The URL properties

Given a request to GET /shop/books?sort=price&page=2 inside a router mounted at /shop:

JavaScript
app.use('/shop', router);

router.get('/books', (req, res) => {
  req.method;       // 'GET'
  req.originalUrl;  // '/shop/books?sort=price&page=2'  (never changes)
  req.baseUrl;      // '/shop'                          (the mount point)
  req.path;         // '/books'                         (relative to the mount)
  req.query;        // { sort: 'price', page: '2' }
  req.params;       // {}  (no :params in this route)
});

req.url also exists (it is Node's property) but Express rewrites it while it passes through mounted routers, so prefer req.originalUrl, req.path and req.query. Query values are always strings (or arrays when a key repeats), so convert numbers yourself: Number(req.query.page ?? 1). Express 5 uses a simple query parser by default, so ?a[b]=1 stays a flat key rather than becoming a nested object as it did in Express 4. Route Parameters and Query Strings covers this in depth.

Node.js Reading the URL properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second request has no page, so the default of 1 applies. Notice req.query.page itself is the string "2"; the number appears only after Number(...).

Headers

req.headers is an object with lower-case names, because HTTP header names are case-insensitive and Node normalizes them. Express adds req.get(name) (alias req.header), which looks a header up case-insensitively:

JavaScript
req.headers['user-agent'];     // 'curl/8.5.0'
req.get('User-Agent');         // same value
req.get('Content-Type');       // 'application/json'
req.get('Referrer');           // handles the Referer / Referrer spelling

Treat every header as an untrusted claim. User-Agent, Origin, Referer and X-Forwarded-* are written by the client (or by whoever sits in between), so they are fine for logging and content decisions, but never for security on their own.

Useful helpers that read headers for you:

  • req.is('json') checks the request's Content-Type ('json', 'html', 'application/*'); it returns false if there is no body.
  • req.xhr is true when X-Requested-With: XMLHttpRequest was sent (old-school AJAX).
  • req.cookies exists only after cookie-parser.

Who is calling: ip, hostname, protocol

Three properties describe the connection:

JavaScript
req.ip;        // '203.0.113.9'
req.hostname;  // 'api.example.com' (from the Host header, without the port)
req.protocol;  // 'http' or 'https'
req.secure;    // req.protocol === 'https'

Here is the catch. Most production apps run behind a proxy (nginx, a load balancer, a CDN). The TCP connection then comes from the proxy, so Node sees the proxy's address and plain http, even when the real visitor used https. Proxies pass the original information in headers: X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host.

By default Express ignores those headers, because any client could forge them and pretend to be someone else. You opt in with the trust proxy setting:

JavaScript
app.set('trust proxy', 1);            // trust exactly one proxy hop (common)
app.set('trust proxy', 'loopback');   // trust proxies on 127.0.0.1
app.set('trust proxy', ['10.0.0.0/8']); // trust a network range

With a number, Express counts that many proxies from the server side of the chain and takes the address just beyond them. Setting it to plain true trusts every hop and uses the leftmost X-Forwarded-For entry, which a client can fake; use the narrowest setting that matches your hosting. This matters for rate limiting and logging by IP, and for cookies marked secure. Security Best Practices and Deployment come back to it.

Node.js trust proxy: ignoring or believing X-Forwarded headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With trust off, the stand-in reports the loopback address and http, ignoring the forwarded headers. With trust on, it believes them. Real Express does the same, with finer control over which hops to trust.

Content negotiation

A client says what formats it can read in the Accept header, for example Accept: text/html, application/json;q=0.5. The q value (from 0 to 1) is a preference weight. req.accepts() compares that header with the types you can produce and returns the best match, or false when there is none:

JavaScript
app.get('/report', (req, res) => {
  switch (req.accepts(['json', 'html'])) {
    case 'json': return res.json({ total: 3 });
    case 'html': return res.send('<p>Total: 3</p>');
    default:     return res.status(406).send('Not Acceptable');
  }
});

Real Express also has res.format({...}), which wraps this switch, plus req.acceptsCharsets, req.acceptsEncodings and req.acceptsLanguages for the other Accept-* headers. The status 406 Not Acceptable says "I cannot produce anything you accept".

Node.js req.accepts: picking a response format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The third request prefers JSON because of the higher q; */* means "anything", so your first listed type wins; image/png matches nothing and gets 406. This is a simplified version of the real matcher, which also handles wildcards in more positions and parameters such as charset.

More request properties: fresh, stale, ips, route and the accepts family

Five more members of req are less famous but solve real problems.

req.fresh and req.stale: is the client's cached copy still good?

Browsers keep copies of responses and later ask "has this changed?" with a conditional request: If-None-Match (carrying the ETag they saw) or If-Modified-Since (carrying the Last-Modified date). If the copy is still current, the server can answer 304 Not Modified with no body, which saves bandwidth (Performance and Caching).

req.fresh is true when the conditional headers say the client's copy matches what your response is about to be. req.stale is its opposite. The rules:

  • Only GET and HEAD requests can be fresh.
  • Fresh only makes sense when the response status is 2xx or 304 (in your own code, set the ETag / Last-Modified response headers before you check).
  • A request header Cache-Control: no-cache always makes it stale (the browser demands revalidation).
  • An If-None-Match that lists your current ETag (a weak W/ prefix is ignored in the comparison) makes it fresh; If-Modified-Since makes it fresh when your Last-Modified is not newer.

In real Express you rarely test req.fresh yourself, because res.send and res.json do it for you: they add a weak ETag and turn the response into a bodiless 304 when req.fresh is true. You use it directly when you build a response in a custom way (a stream, a computed file) and want the same behavior.

req.ips and the chain of proxies

req.ip is the client address. When several proxies sit in front of your app, each one appends an address to the X-Forwarded-For header, so you end up with a chain such as 203.0.113.9, 198.51.100.2. req.ips is that chain as an array (farthest client first), but only the part you are willing to believe, which depends on the trust proxy setting (Application Settings). With trust proxy off, req.ips is empty and req.ip is the socket address. With trust proxy set to 1, one hop is trusted: the socket peer (your proxy). Never trust addresses further left than the proxies you control, because a client can write anything into the start of that header.

req.route: the matched route

Inside a route handler, req.route is the route object that matched: its path (the pattern, such as /users/:id, not the actual URL), the HTTP methods registered on it and its handler stack. It is undefined in ordinary middleware that runs before a route matches. It is most useful in logging and metrics: grouping by req.route.path gives one counter per route instead of one per distinct user id. In an error handler or res.on('finish') callback you can combine req.baseUrl + req.route.path to name the endpoint.

req.acceptsCharsets, req.acceptsEncodings, req.acceptsLanguages

req.accepts handles the Accept header. Its three siblings read the other negotiation headers, and each returns the best match from the list you pass in (or false):

  • req.acceptsLanguages(['en', 'fr', 'de']) reads Accept-Language; en also matches en-GB, so a regional variant picks the base language.
  • req.acceptsEncodings(['br', 'gzip']) reads Accept-Encoding. Compression middleware uses this; identity (no compression) is always acceptable unless the client forbids it.
  • req.acceptsCharsets(['utf-8']) reads Accept-Charset, which modern browsers no longer send; you will rarely need it.

Without arguments they return an array of everything the client accepts, in preference order. The next program rebuilds the rules in a few lines so you can watch them work. It uses a real HTTP server, so the 304 and the headers are real; the negotiation, fresh and ips helpers are simplified stand-ins for what Express builds from the accepts, fresh and proxy-addr packages.

Node.js fresh, stale, ips, route and accepts*

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the results. The first visit returns the body. A matching If-None-Match (weak or strong form) yields 304 with no body: req.fresh was true. A different version, or no-cache, yields a full response. For req.ips, with trust proxy off nothing in X-Forwarded-For is believed and req.ip is the proxy socket; with 1 the first forwarded address is believed; each extra hop reveals one more client address, farthest first in req.ips. For the accepts calls, the client's weights pick the winner (fr;q=0.9 beats en-GB;q=0.8); on a tie the header order decides, and a regional tag like en-GB matches your plain en.

The negotiation here is simplified (real accepts follows the full specification, including type/* ranges and parameters). The point is the decision process: weights first, then order, with false when nothing matches so you can answer 406 Not Acceptable or fall back to a default language.

Other things worth knowing

  • req.body is covered in Built-in Middleware; it is undefined until a parser runs.
  • req.params holds route parameters; in a router you may need mergeParams (Modular Routing).
  • req.res and req.app point back to the response and the app.
  • req.host (new meaning in Express 5) includes the port, while req.hostname does not; req.subdomains lists the parts left of the registered domain.
  • Custom data: attach your own values (req.user, req.id) from middleware, as in Writing Your Own Middleware. With TypeScript, extend the Request type to describe them.

The runnable examples reimplement req.accepts, ip, protocol and hostname in a few lines each. The real Express uses the accepts and proxy-addr packages and handles many more cases (IPv6, subnets, multiple proxies, quality ties).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client requests /shop/books?page=2 and your handler reads req.query.page. What do you get?

    Query string values are always strings (or arrays of strings for repeated keys). Convert with Number() and validate.
  2. 2. Your app runs behind nginx and req.ip always shows the proxy's address. What should you configure?

    By default Express ignores X-Forwarded-For. trust proxy tells it how many proxies to believe.
  3. 3. What does req.accepts(['json', 'html']) return for the header Accept text/html?

    It returns whichever of your listed types the client accepts best. Only html matches text/html.
  4. 4. Why is app.set('trust proxy', true) risky on a server directly exposed to the internet?

    With full trust Express believes the leftmost X-Forwarded-For value, which any client can send. Trust only the proxies you actually run.
  5. 5. Which request property is NOT changed as the request passes into a mounted router?

    req.originalUrl always keeps the full URL as received, while url, path and baseUrl change while inside mounted routers.

Summary

  • req.method, req.originalUrl, req.path, req.query and req.params describe where the request went; query values are strings.
  • Header names are lower-case in req.headers; use req.get(name) for case-insensitive lookups, and never trust headers for security.
  • req.ip, req.protocol and req.hostname ignore X-Forwarded-* unless you set trust proxy narrowly and correctly.
  • req.accepts([...]) negotiates a response format from the Accept header, returning false when nothing fits (send 406).
  • Attach your own per-request data from middleware, but do not overwrite built-in properties.

Next: The Response Object.