Validating uploads
🏠The everyday picture
A bank teller doesn't accept a cheque just because it's labelled "cheque". They check the paper, the signature and the amount.
📘What it really is
- Limit size (multer's
limits) and number of files. -
Check the type by content, not by name or label. The file name's extension and the browser's stated type (
mimetype) can both be faked. Libraries likefile-typeread the first bytes of the file to identify it. -
Allow a short list of types you need (for example PDF, JPEG, PNG), and refuse everything else. Never accept executable files, HTML or SVG from untrusted people unless you specifically handle them (SVG and HTML can contain scripts).
-
Serve safely:
- send the right
Content-TypeandContent-Disposition: attachmentfor downloads, so browsers don't run anything; - serve user files from a separate domain or storage if possible;
- re-encode images (resize with a library like
sharp), which also removes hidden data such as location in photos. - For sensitive uses, scan uploads for malware.
- Show helpful errors: "Please upload a PDF, JPG or PNG under 5 MB."
🖱️Try it
Add file-type to your upload route. Accept only PDF, JPEG and PNG, checked by content. Test by renaming a .txt file
to .pdf and uploading it: it should be refused with a clear message. Make the download route send
Content-Disposition: attachment.
✅Quick check
A file is named photo.jpg and the browser says image/jpeg. Is it safe to trust that it's a JPEG?
Show the answer
No. Both can be faked; check the file's actual content.
Why can accepting SVG or HTML uploads be dangerous?
Show the answer
They can contain scripts that run in visitors' browsers if served from your site.
