Untitled Lesson
Skill Matrix
UNLOCK NODES BY LEARNING NEW TAGS.
Is Multer's built-in `fileFilter` (checking a file's declared MIME type) sufficient on its own to reliably prevent a malicious file from being uploaded?
💻 Code Challenge | +75 XP
Configure a Multer instance with diskStorage, a custom filename function generating a UUID-based name, a fileFilter restricting to image MIME types, a 5MB size limit, and explicit MulterError handling returning a 413 status.
An upload endpoint throws a generic 500 error when a client uploads a file exceeding the configured size limit, instead of a clear error message. Reorder the steps to fix this using proper Multer error handling.
Task: Reorder the blocks in logical sequence to solve the problem.
A.D.A. Interface
Adaptive Didactic Assistant

Pascual Vila
Frontend Instructor // Code Syllabus
The Error //
Relying solely on Multer's fileFilter (based on declared MIME type) as the complete file type security check
// Insufficient alone: only checks the client-declared type
fileFilter: (req, file, cb) => cb(null, file.mimetype === "image/jpeg")
// Correct: fileFilter as a first pass, PLUS content validation after
const type = await fileTypeFromBuffer(req.file.buffer);
if (type?.mime !== "image/jpeg") throw new Error("Invalid file type");The Solution //
fileFilter checks the client-declared MIME type, which is trivially spoofable, exactly like checking a file extension — it's a useful cheap first-pass filter but must be combined with content-based validation (checking the file's actual binary signature) after upload for genuine security.
The Error //
Not explicitly catching and handling multer.MulterError, letting upload failures propagate as generic unhandled errors
// Wrong: unhandled, becomes a generic 500
upload.single("file")(req, res, next);
// Correct: specific handling for MulterError
upload.single("file")(req, res, (err) => {
if (err instanceof multer.MulterError && err.code === "LIMIT_FILE_SIZE") {
return res.status(413).json({ error: "File too large" });
}
next(err);
});The Solution //
Multer throws a specific, typed error (MulterError) for configured constraint violations like exceeding the file size limit — without explicitly catching this, the error propagates as a generic, unhelpful 500 error instead of a clear, appropriate response like 413 (Payload Too Large).