expressjs/express · error · TypeError

name must be a string to req.get

Error message

name must be a string to req.get

What it means

Immediately after the presence check, req.get() at lib/request.js:69-71 validates that the header name is a string, because it calls name.toLowerCase() and indexes this.headers with it. A non-string argument (number, object, array, Symbol) indicates the caller passed the wrong value entirely.

Source

Thrown at lib/request.js:70

 *
 *     req.get('Something');
 *     // => undefined
 *
 * Aliased as `req.header()`.
 *
 * @param {String} name
 * @return {String}
 * @public
 */

req.get =
req.header = function header(name) {
  if (!name) {
    throw new TypeError('name argument is required to req.get');
  }

  if (typeof name !== 'string') {
    throw new TypeError('name must be a string to req.get');
  }

  var lc = name.toLowerCase();

  switch (lc) {
    case 'referer':
    case 'referrer':
      return this.headers.referrer
        || this.headers.referer;
    default:
      return this.headers[lc];
  }
};

/**
 * Check if the given `type(s)` is acceptable, returning
 * the best match when true, otherwise `false`, in which
 * case you should respond with 406 "Not Acceptable".

View on GitHub ↗ (pinned to a3714473fe)

Solutions

  1. Pass the header name as a string literal or coerce explicitly: req.get(String(name)).
  2. Fix the call site that passes an object/array — usually you meant a property of that object.
  3. Add a type annotation (string) at the source of the value so the compiler catches it.

Example fix

// before
headerList.forEach(req.get, req); // forEach passes (value, index, array)
// after
headerList.forEach(function (name) { values.push(req.get(name)); });
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof headerName !== 'string') {
  throw new TypeError(`header name must be a string, got ${typeof headerName}`);
}
const value = req.get(headerName);

Type guard

function isValidHeaderName(name) {
  return typeof name === 'string' && name.length > 0;
}

Try / catch

try {
  const value = req.get(headerName);
} catch (err) {
  if (err instanceof TypeError && /must be a string/.test(err.message)) {
    // non-string (array, number, object) was passed — normalize at the call site
  }
  throw err;
}

Prevention

When it happens

Trigger: Calling req.get(42), req.get(['accept']), req.get({name: 'accept'}), or req.get(Symbol(...)) — any truthy non-string value. Truthy is required, otherwise error [0] fires first.

Common situations: Iterating over a headers config that mixes objects and strings; passing the whole req.headers object instead of a key; TypeScript projects with an any-typed value crossing into the call; accidentally passing an index from a map/forEach callback signature.

Related errors


AI-assisted analysis of expressjs/express@a3714473fe (2026-07-31). Data as JSON: /data/errors/82b2c741cb58cd8c.json. Report an issue: GitHub ↗.