File paths built from user input (path traversal)

Last updated November 9, 2026
Steps
- Search your code for fs.readFile, fs.createReadStream, res.sendFile, path.join and path.resolve where any part of the path comes from req.query, req.params, request bodies, form data or an AI tool call.
- Best fix: don't accept file paths at all. Store files under random IDs, look the ID up in your database, and read the stored path from there after checking that the user owns the file.
- If you must accept a name, allowlist it: only letters, numbers, dashes and one known extension, and reject anything containing /, \ or ..
- Then resolve the full path with path.resolve(baseDir, name) and confirm it still starts with your base folder plus a path separator before opening it. Reject it if not.
- Don't try to strip ../ with a find-and-replace. Encoded and nested variants (%2e%2e%2f, ....//) get past simple filters.
- Test it: request ../package.json, %2e%2e%2fpackage.json and an absolute path like /etc/passwd. Each should return 400 or 404, never file contents.
- Keep secrets out of files the app can read where possible, and run the app with the least file access it needs.
Why it matters
OWASP describes path traversal as accessing files and directories stored outside the intended folder by manipulating variables that reference files with dot-dot-slash sequences and their variations, and notes that encoded forms can bypass naive filters. MITRE tracks it as CWE-22, Improper Limitation of a Pathname to a Restricted Directory, and recommends allowlist input validation and canonicalizing paths before checking them. The Node.js path docs explain that path.join and path.resolve normalize .. segments, so joining untrusted input to a base folder doesn't keep the result inside that folder. A single vulnerable route can expose .env files, source code and other users' uploads.
Sources
OWASP: Path Traversal — https://owasp.org/www-community/attacks/Path_Traversal
MITRE CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') — https://cwe.mitre.org/data/definitions/22.html
Node.js documentation: Path (path.join, path.resolve) — https://nodejs.org/api/path.html
OWASP Cheat Sheet Series: Input Validation Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
Related patterns
Found a problem you'd rather not fix yourself?
Tell us what's wrong. A StorenTech engineer reviews your app and replies with a fixed quote, so you know the cost before any work starts.
Get it fixed by StorenTechVibe Security Weekly
One email a week with new failure patterns and how to fix them.
By joining you agree we may email you this newsletter. See our privacy policy. Free. Unsubscribe anytime. We'll never sell your email.