AceDevHub
Intermediate Node.js Interview QuestionsIntermediatePractical

Node.js · Question 66

How do you prevent path traversal attacks in Node.js?

Direct answer

Never pass user input directly to fs paths — resolve with path.resolve, ensure result starts with allowed base directory, reject .. segments, use path.basename for filenames, and serve static files from a fixed root.

Path traversal exploits ../ in filenames to read /etc/passwd or .env — any endpoint that reads or writes files from user-supplied names must validate paths.

  1. Fixed base — const base = path.resolve('./uploads').
  2. Resolve + check — target = path.resolve(base, userInput); if (!target.startsWith(base)) reject.
  3. basename only — path.basename(userInput) strips directory components.
  4. Allowlist extensions — .json, .png only for public asset endpoints.
path-security.mjs
import path from "node:path";
import fsp from "node:fs/promises";

const CONTENT_ROOT = path.resolve("data/interviews");

function safeInterviewPath(topicSlug) {
  const normalized = path.basename(topicSlug);
  const target = path.resolve(CONTENT_ROOT, normalized, "questions.json");

  if (!target.startsWith(CONTENT_ROOT + path.sep)) {
    throw new Error("Invalid path");
  }

  return target;
}

// Attacker input: "../../apps/api/.env" → basename strips or resolve check fails