How do I upload files in an Express API safely?

asked 3 months ago486 viewsen

4

Users need to upload profile pictures. I'm using multer and saving to ./uploads. What should I watch out for?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 3 months ago

1 Answer

7
✓
✓ Accepted answer

Key safeguards:

1. Limit size: multer({ limits: { fileSize: 2 * 1024 * 1024 } }). 2. Validate the real type, not the client-provided MIME or extension. Check magic bytes with file-type, and only allow image/jpeg|png|webp. 3. Re-encode images with sharp. This strips EXIF (including GPS location!) and neutralizes polyglot files. 4. Never use the original filename on disk. Generate one with crypto.randomUUID(). 5. Don't serve uploads from your app's origin with executable types. Better: store them in object storage (S3, R2, Supabase Storage) and serve them from a separate domain or CDN. 6. Rate-limit the upload endpoint.

const buf = await sharp(req.file.buffer)
  .rotate()
  .resize(512, 512, { fit: 'cover' })
  .webp({ quality: 80 })
  .toBuffer();

Sign in to tell others whether this worked.

answered 3 months ago

Sign in and verify your email to post an answer.