expressjs/express · error · TypeError

path argument is required to res.sendFile

Error message

path argument is required to res.sendFile

What it means

Thrown at the top of `res.sendFile` when the `path` argument is falsy (undefined, null, or empty string). Express fails fast here because the underlying `send` module needs a real path, and a missing one usually indicates a caller bug rather than a runtime file condition.

Source

Thrown at lib/response.js:381

 *           res.sendFile('/uploads/' + uid + '/' + file);
 *         } else {
 *           res.send(403, 'Sorry! you cant see that.');
 *         }
 *       });
 *     });
 *
 * @public
 */

res.sendFile = function sendFile(path, options, callback) {
  var done = callback;
  var req = this.req;
  var res = this;
  var next = req.next;
  var opts = options || {};

  if (!path) {
    throw new TypeError('path argument is required to res.sendFile');
  }

  if (typeof path !== 'string') {
    throw new TypeError('path must be a string to res.sendFile')
  }

  // support function as second arg
  if (typeof options === 'function') {
    done = options;
    opts = {};
  }

  if (!opts.root && !pathIsAbsolute(path)) {
    throw new TypeError('path must be absolute or specify root to res.sendFile');
  }

  // create file stream
  var pathname = encodeURI(path);

View on GitHub ↗ (pinned to a3714473fe)

Solutions

  1. Ensure the first argument is a non-empty path string: guard the request input and return 400 if missing.
  2. Check argument order — the signature is `res.sendFile(path, options, callback)`; the path must come first.
  3. Log the computed path before the call to confirm it isn't undefined at runtime.

Example fix

// before
res.sendFile(req.query.file);
// after
if (!req.query.file) return res.status(400).send('file parameter required');
res.sendFile(req.query.file, { root: path.join(__dirname, 'public') });
Defensive patterns

Strategy: validation

Validate before calling

if (!filePath) {
  return res.status(404).end();
}
res.sendFile(filePath, { root: PUBLIC_DIR });

Type guard

function hasPath(p) {
  return p !== undefined && p !== null && p !== '';
}

Prevention

When it happens

Trigger: Calling `res.sendFile()` with no arguments, or with a variable that resolved to undefined/null/'' — e.g. `res.sendFile(req.query.file)` when the query param is absent, or a bad destructure of an options object.

Common situations: Route handlers that build the path from request input without checking it; refactors that renamed a variable so the argument is undefined; passing the options object as the first argument by mistake.

Related errors


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