Back to results for “Security”
Node.js › File Uploads & Media Processing

What is the security risk of trusting a client-supplied filename for an uploaded file, and how do you mitigate it?

Advanced

Answer

A client-supplied original filename could contain path traversal sequences (like '../../etc/passwd') or other malicious characters that, if used directly to construct a file path on the server, could let an attacker write files outside the intended upload directory -- the mitigation is to never use the client-supplied filename directly for the actual storage path, instead generating a new, safe, randomly-generated filename (like a UUID) server-side, optionally preserving only the validated file extension.
const crypto = require('node:crypto');
const path = require('node:path');

const safeExtension = path.extname(req.file.originalname).toLowerCase();
const allowedExtensions = ['.jpg', '.png', '.gif'];
if (!allowedExtensions.includes(safeExtension)) throw new Error('Invalid file extension');

const safeFilename = `${crypto.randomUUID()}${safeExtension}`; // never uses the raw client filename
Real-world example A security review flags that an upload endpoint was using the client-provided filename directly to construct the storage path, a path-traversal vulnerability; the fix generates a random UUID-based filename server-side, only carrying over a validated, allow-listed file extension from the original name.

Common follow-ups: What specific path-traversal payload would exploit an endpoint that uses the raw client filename directly?;Why is validating the extension against an allow-list safer than checking it against a deny-list of dangerous extensions?