Express Cheatsheet

The Request Object

Use this Express reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Overview

The req object is a Node.js IncomingMessage extended with Express helpers. It is available in every route handler and middleware as the first argument.

URL and Path Properties

PropertyTypeDescriptionExample
req.urlstringRaw URL (relative to mount point)'/users?sort=asc'
req.originalUrlstringFull URL, never rewritten by router'/api/users?sort=asc'
req.baseUrlstringMount path of the matched router'/api'
req.pathstringPath portion of URL'/users'
req.hostnamestringHost without port (trust proxy aware)'example.com'
req.protocolstring'http' or 'https' (trust proxy aware)'https'
req.securebooleanreq.protocol === 'https'true
req.subdomainsstring[]Subdomain array, reversed order['api', 'v2']
// For request: GET https://api.example.com/v1/users?sort=asc
app.use('/v1', (req, res) => {
  req.url;          // '/users?sort=asc'
  req.originalUrl;  // '/v1/users?sort=asc'
  req.baseUrl;      // '/v1'
  req.path;         // '/users'
  req.hostname;     // 'api.example.com'
  req.protocol;     // 'https'
});

Method and Route

req.method;      // 'GET', 'POST', 'PUT', 'DELETE', etc.  (always uppercase)
req.route;       // matched Route object: { path, stack, methods }

Query String — req.query

Parsed from the URL search string. Type is object | string | string[] | ParsedQs.

// GET /search?q=node&tags=js&tags=ts&page=2
req.query.q;        // 'node'
req.query.tags;     // ['js', 'ts']
req.query.page;     // '2'  (always string — coerce manually)
req.query.missing;  // undefined

By default Express uses qs (extended: true). Change with app.set('query parser', 'simple') or a custom function.

Route Parameters — req.params

Key/value pairs from named URL segments.

// Route: /users/:userId/posts/:postId
// URL:   /users/42/posts/7
req.params.userId;  // '42'
req.params.postId;  // '7'

Request Body — req.body

Populated by body-parsing middleware (express.json(), express.urlencoded(), etc.). undefined if no parser applied.

app.use(express.json());

// POST /users  body: { "name": "Alice", "age": 30 }
req.body.name;  // 'Alice'
req.body.age;   // 30

Headers — req.headers / req.get()

req.headers;                        // plain object, all headers (lowercase keys)
req.get('Content-Type');            // case-insensitive header lookup
req.get('Authorization');           // 'Bearer eyJ...'
req.header('x-request-id');        // alias for req.get()

// Common headers
req.get('content-type');    // 'application/json'
req.get('accept');          // 'text/html,application/json'
req.get('user-agent');      // 'Mozilla/5.0 ...'
req.get('authorization');   // 'Bearer token'
req.get('host');            // 'localhost:3000'

IP Address

req.ip;      // Client IP (respects trust proxy)
req.ips;     // Array of IPs from X-Forwarded-For when trust proxy enabled

Content Negotiation — req.is() / req.accepts()

// req.is() — checks Content-Type of incoming body
req.is('application/json');   // 'application/json' | false
req.is('json');               // shorthand — true for application/json
req.is('text/*');             // wildcard match
req.is(['json', 'text']);     // returns first match or false

// req.accepts() — checks client's Accept header for response format
req.accepts('html');                    // 'html' or false
req.accepts(['json', 'text']);          // best match based on q-values
req.acceptsCharsets('utf-8');           // charset negotiation
req.acceptsEncodings('gzip', 'deflate');
req.acceptsLanguages('en', 'fr');
// Pattern: respond in the client's preferred format
app.get('/data', (req, res) => {
  const type = req.accepts(['json', 'html', 'text']);
  if (type === 'json')      return res.json({ value: 42 });
  if (type === 'html')      return res.send('<p>42</p>');
  if (type === 'text')      return res.send('42');
  res.status(406).send('Not Acceptable');
});

Cookies — req.cookies / req.signedCookies

Requires cookie-parser middleware.

const cookieParser = require('cookie-parser');
app.use(cookieParser('secret'));

req.cookies.name;          // plain cookie value
req.signedCookies.session; // signed (and verified) cookie value

Fresh / Stale Caching

req.fresh;  // true if response is still cached (ETag / Last-Modified match)
req.stale;  // !req.fresh

xhr (AJAX Detection)

req.xhr; // true if X-Requested-With: XMLHttpRequest header is set

Full Request Property Quick-Reference

Property / MethodDescription
req.appReference to the Express application
req.baseUrlMount path of the current router
req.bodyParsed request body (needs middleware)
req.cookiesParsed cookies (needs cookie-parser)
req.signedCookiesSigned cookies (needs cookie-parser)
req.freshCache freshness check
req.hostnameRequest hostname
req.ipClient IP address
req.ipsProxy-forwarded IPs
req.methodHTTP method, uppercase
req.originalUrlFull original URL
req.paramsRoute parameter key/values
req.pathURL path portion
req.protocol'http' or 'https'
req.queryParsed query string
req.routeMatched route object
req.secureHTTPS boolean
req.staleNegation of fresh
req.subdomainsArray of subdomains
req.urlURL relative to mount point
req.xhrAJAX request detection
req.get(header)Get request header
req.is(type)Check Content-Type
req.accepts(types)Content negotiation
req.acceptsCharsets()Charset negotiation
req.acceptsEncodings()Encoding negotiation
req.acceptsLanguages()Language negotiation
req.range(size)Parse Range header