Skip to content

Node.js file upload validation best practices

File upload validation is not one check. It is a stack of checks with different purposes.

For the broader route-design view of where validation fits, see Secure file uploads in Node.js: Beyond Extension and MIME Checks.

LayerPurposeExample
Parser limitsProtect resources before deeper work startsMax file size, file count, request size
Extension allowlistQuick route-level filterpdf, png, jpg only
MIME allowlistReject obviously wrong uploadsapplication/pdf, image/png
Magic-byte / type validationVerify what the bytes claim to beDetect a renamed executable
Structural inspectionLook for risky content patternsPDF actions, SVG scripts, macro containers
Archive controlsHandle ZIP-specific abuseTraversal, depth, total expansion
Storage decisionDecide trust levelStore, quarantine, or reject
  • Trusting req.file.mimetype as the final answer.
  • Using one generic upload route for every file type.
  • Allowing ZIP or SVG through image-only routes.
  • Treating validation as complete once the file extension looks right.

The more powerful the file format, the narrower the route and policy should be.

  • Plain images need a tighter but simpler policy.
  • PDFs and Office documents need structural inspection.
  • ZIPs need explicit archive rules.
  • Direct-to-object-storage flows need quarantine and promotion logic.