Secure File Uploads
File uploads are one of the riskiest features: remote code execution, stored XSS (SVG/HTML), path traversal, disk-filling DoS and malware.
Packages
| Package | Use |
|---|---|
multer | Multipart upload handling for Express |
file-type | Detect the real type from the file's magic bytes |
sharp | Re-encode images (removes hidden payloads and EXIF/GPS data) |
clamscan | Virus scanning with ClamAV |
@aws-sdk/client-s3 + @aws-sdk/s3-request-presigner | Private storage + pre-signed URLs |
❌ Vulnerable
const upload = multer({ dest: 'public/uploads' }); // directly served, executable
app.post('/avatar', upload.single('file'), (req, res) => {
fs.renameSync(req.file.path, 'public/uploads/' + req.file.originalname); // ../../ path traversal, overwrite
});✅ Secure
const multer = require('multer');
const { fileTypeFromBuffer } = require('file-type');
const sharp = require('sharp');
const crypto = require('crypto');
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 2 * 1024 * 1024, files: 1 }, // 2 MB, one file
});
const ALLOWED = ['image/jpeg', 'image/png', 'image/webp'];
app.post('/avatar', requireAuth, upload.single('file'), async (req, res) => {
const type = await fileTypeFromBuffer(req.file.buffer); // don't trust the extension or Content-Type
if (!type || !ALLOWED.includes(type.mime)) return res.status(400).json({ error: 'Invalid file' });
const clean = await sharp(req.file.buffer).resize(512, 512).webp().toBuffer(); // re-encode, strip metadata
const key = `avatars/${crypto.randomUUID()}.webp`; // our name, never the user's
await s3.putObject({ Bucket: 'private-bucket', Key: key, Body: clean, ContentType: 'image/webp' });
res.json({ key });
});Serving files
- Serve from a separate domain (e.g.
usercontent.example.com) or S3/CDN, not your app domain - Add
Content-Disposition: attachmentfor downloads - Add
X-Content-Type-Options: nosniff - Use short-lived pre-signed URLs for private files
Checklist
- Size and count limits
- Type check by magic bytes + an extension allowlist
- Rename to a random name; never use user filenames in paths
- Store outside the web root / in private object storage
- Re-encode images; block SVG/HTML unless sanitized
- Malware scan for documents
- Zip uploads: watch for zip bombs and
../entries (zip slip)