Secure File Uploads & Downloads
How to validate uploaded files by content, enforce size limits, store outside the web root with randomized names, scan for malware, and serve safely with Content-Disposition.
TL;DR
Never trust a client's filename or Content-Type header. Enforce byte-size limits, verify file type by content/magic bytes (or re-encode images), save under a randomized key outside the web root, scan asynchronously before publishing, and serve downloads from a separate origin with Content-Disposition: attachment and X-Content-Type-Options: nosniff.
Why it exists
File upload endpoints combine multiple high-severity risks in one place: remote code execution if a file lands inside a web root, stored XSS if HTML/SVG is served inline on your app origin, path traversal via ../ filenames, and denial of service via zip bombs or multi-gigabyte uploads.
Defense-in-depth upload pipeline (ASVS V5)
- Size limits first: Enforce max
Content-Lengthand streaming byte caps at the reverse proxy and app before buffering into memory. - Validate by content, not extension: Check magic bytes (e.g. PNG/JPEG/PDF signatures) and, for images, decode and re-encode with a library like
sharpto strip embedded payloads and EXIF metadata. - Randomize storage keys: Ignore the user's filename when writing to disk or object storage (
crypto.randomUUID() + '.png'). Keep original display names only as metadata in your DB. - Store outside the web root: Write uploads to private object storage (S3/R2) or a non-executable directory outside
public/. - Quarantine & malware scan: Place new uploads in a quarantine bucket/prefix, run AV scanning (e.g. ClamAV) asynchronously, and promote only clean files.
- Serve safely: Serve user files from a dedicated sandboxed domain (e.g.
usercontent.example) with:Content-Disposition: attachment; filename="safe-name.pdf"X-Content-Type-Options: nosniff
// UNSAFE: trusts client filename and Content-Type, writes into public/ web root
await fs.writeFile(path.join('public/uploads', file.originalname), file.buffer);
// SAFE: validates size + magic bytes, writes UUID key outside web root (ASVS V5)
import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
const MAX_BYTES = 5 * 1024 * 1024;
const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
export async function saveSafePng(bytes: Buffer, uploadDir: string) {
if (bytes.length === 0 || bytes.length > MAX_BYTES) throw new Error('Invalid file size');
if (!bytes.subarray(0, 8).equals(PNG_MAGIC)) throw new Error('Not a valid PNG');
const key = `${randomUUID()}.png`;
const target = path.join(uploadDir, key); // uploadDir is outside public/ web root
await fs.writeFile(target, bytes, { flag: 'wx' });
return key;
}Gotchas
- SVG uploads: Allowing
.svguploads and serving them inline gives attackers instant Stored XSS on your origin; convert to PNG/WebP or serve only from an isolatedusercontentdomain withContent-Disposition: attachment. - Archive/zip bombs: A 50 KB
.zipor.xlsxcan decompress to gigabytes in memory; enforce uncompressed output limits and entry-count caps. - Double extensions & null bytes: Filenames like
shell.php.jpgor../../etc/cron.d/jobbreak naive regex checks—using a generatedUUIDkey avoids filename parsing entirely.
Production checklist
- Maximum file size is enforced at both the edge/proxy and application stream reader.
- File type is verified by magic bytes (and re-encoded for images), using an explicit allowlist.
- Stored paths use server-generated UUIDs outside the web root (never user filenames).
- Malware scanning runs in quarantine before files become downloadable.
- Downloads send
Content-Disposition: attachmentandX-Content-Type-Options: nosnifffrom a separate origin.
Check yourself
Check Yourself
1. An upload handler checks file.mimetype === 'image/png' and saves file.originalname into /var/www/html/uploads/. What are the two main flaws?
2. Why should user-uploaded SVGs never be served inline from your primary application domain?
Sources
Related Notes
HTTP Security Headers Cheatsheet
Practical reference for CSP, HSTS (and preload caveats), X-Content-Type-Options, Referrer-Policy, Permissions-Policy, frame-ancestors, and COOP/COEP using Cloudflare Pages _headers.
Rate Limiting & Brute-Force Protection
Token bucket vs fixed/sliding window algorithms, edge vs application enforcement, choosing rate-limit keys, and returning 429 Too Many Requests with Retry-After.