How do I upload files in an Express API safely?

poze 3 months ago483 gadeen

4

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

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 3 months ago

1 Repons

7
✓
✓ Repons yo aksepte

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();

Konekte pou di lòt moun si li te mache.

answered 3 months ago

Sign in and verify your email to post an answer.