StackPractices
intermediate By Mathias Paulenko

Node.js File Upload Validation: Type, Size, and Content

Validate file uploads in Node.js with multer — size limits, MIME checks, magic bytes and virus scanning for Express APIs.

Overview

File uploads are one of the easiest ways to get a server compromised. Left unchecked, an attacker can push a webshell, overwrite system files, or run code on your box — and the Content-Type header won’t stop any of it, because the client sets that header and can claim anything. This recipe builds the checks that actually matter in an Express app with multer: size and count limits, extension and MIME filtering, magic-byte verification, image dimension caps, and where virus scanning fits. For a language-agnostic version with Python and Java examples, see File Upload Validation; this one is the Node.js implementation.

When to Use

Reach for this setup whenever any of these apply:

  • You’re exposing an endpoint that accepts files from users — avatars, invoices, CSV imports, attachments.
  • You need to restrict uploads to a short list of types (images only, PDFs only).
  • You want to cap file size and file count before they eat your disk or RAM.
  • You can’t trust the declared Content-Type — which is always — and need to check what the file really is.
  • Skip the full pipeline if uploads only come from trusted internal services on your network. A size limit plus a virus scan is usually enough there; layered content validation mostly adds latency you don’t need.

Solution

Everything below runs on multer 2.x. The 1.x line is deprecated and carries known vulnerabilities, so install with a pinned major:

npm install multer@^2

Basic multer setup with file size limit

const express = require("express");
const multer = require("multer");
const path = require("path");

const app = express();

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "uploads/");
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
        const ext = path.extname(file.originalname);
        cb(null, file.fieldname + "-" + uniqueSuffix + ext);
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 5 * 1024 * 1024, // 5 MB
        files: 1
    }
});

app.post("/api/upload", upload.single("file"), (req, res) => {
    if (!req.file) {
        return res.status(400).json({ error: "No file uploaded" });
    }
    res.json({
        filename: req.file.filename,
        size: req.file.size,
        mimetype: req.file.mimetype
    });
});

app.listen(3000, () => console.log("Server running on port 3000"));

File type validation with file filter

const ALLOWED_MIMETYPES = [
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/webp",
    "application/pdf"
];

const ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".pdf"];

const fileFilter = (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();

    if (!ALLOWED_MIMETYPES.includes(file.mimetype)) {
        return cb(new Error(`MIME type ${file.mimetype} is not allowed`), false);
    }

    if (!ALLOWED_EXTENSIONS.includes(ext)) {
        return cb(new Error(`Extension ${ext} is not allowed`), false);
    }

    cb(null, true);
};

const upload = multer({
    storage: multer.diskStorage({
        destination: "uploads/",
        filename: (req, file, cb) => {
            const safeName = path.basename(file.originalname).replace(/[^a-zA-Z0-9.-]/g, "_");
            const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
            cb(null, uniqueSuffix + "-" + safeName);
        }
    }),
    limits: {
        fileSize: 5 * 1024 * 1024,
        files: 5
    },
    fileFilter: fileFilter
});

app.post("/api/upload", upload.array("files", 5), (req, res) => {
    const files = req.files.map(f => ({
        filename: f.filename,
        size: f.size,
        mimetype: f.mimetype
    }));
    res.json({ uploaded: files });
});

// Multer errors and fileFilter errors land in the same middleware — tell them apart
app.use((err, req, res, next) => {
    if (err instanceof multer.MulterError) {
        if (err.code === "LIMIT_FILE_SIZE") {
            return res.status(413).json({ error: "File too large. Max size: 5MB" });
        }
        if (err.code === "LIMIT_FILE_COUNT") {
            return res.status(400).json({ error: "Too many files. Max: 5" });
        }
        if (err.code === "LIMIT_UNEXPECTED_FILE") {
            return res.status(400).json({ error: "Unexpected field name" });
        }
        return res.status(400).json({ error: err.message });
    }
    if (err) {
        return res.status(400).json({ error: err.message });
    }
    next();
});

Content-based MIME type verification

The manual version below shows what signature checking looks like under the hood. webp needs a slightly different read: it lives inside a RIFF container, so the WEBP tag shows up at bytes 8–11 rather than offset 0 — and checking offset 0 would wave through any RIFF file, including WAV and AVI.

const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");

const app = express();

const MAGIC_BYTES = {
    "image/jpeg": { offset: 0, bytes: [0xff, 0xd8, 0xff] },
    "image/png": { offset: 0, bytes: [0x89, 0x50, 0x4e, 0x47] },
    "image/gif": { offset: 0, bytes: [0x47, 0x49, 0x46, 0x38] },
    "application/pdf": { offset: 0, bytes: [0x25, 0x50, 0x44, 0x46] },
    "image/webp": { offset: 8, bytes: [0x57, 0x45, 0x42, 0x50] } // "WEBP" after RIFF
};

function verifyMagicBytes(filePath, expectedMime) {
    const expected = MAGIC_BYTES[expectedMime];
    if (!expected) {
        return Promise.resolve(true); // nothing to check against
    }

    return new Promise((resolve, reject) => {
        fs.open(filePath, "r", (err, fd) => {
            if (err) return reject(err);

            const length = expected.offset + expected.bytes.length;
            const buffer = Buffer.alloc(length);
            fs.read(fd, buffer, 0, length, 0, (readErr) => {
                fs.close(fd, () => {
                    if (readErr) return reject(readErr);
                    const matches = expected.bytes.every(
                        (byte, i) => buffer[expected.offset + i] === byte
                    );
                    resolve(matches);
                });
            });
        });
    });
}

const upload = multer({
    storage: multer.diskStorage({
        destination: "uploads/",
        filename: (req, file, cb) => {
            cb(null, Date.now() + "-" + file.originalname);
        }
    }),
    limits: { fileSize: 5 * 1024 * 1024 },
    fileFilter: (req, file, cb) => {
        if (MAGIC_BYTES[file.mimetype]) {
            cb(null, true);
        } else {
            cb(new Error("File type not allowed"), false);
        }
    }
});

app.post("/api/upload", upload.single("file"), async (req, res) => {
    try {
        const isValid = await verifyMagicBytes(req.file.path, req.file.mimetype);
        if (!isValid) {
            fs.unlinkSync(req.file.path);
            return res.status(415).json({
                error: "File content does not match declared type",
                declared: req.file.mimetype
            });
        }

        res.json({
            filename: req.file.filename,
            size: req.file.size,
            mimetype: req.file.mimetype,
            verified: true
        });
    } catch (err) {
        res.status(500).json({ error: "File verification failed" });
    }
});

app.listen(3000);

Verifying content with the file-type package

Hand-rolled signatures only cover the formats you remember to add. The file-type package detects hundreds of them — including the tricky container formats — and it’s what most production services reach for. It’s ESM-only, so pull it in with a dynamic import() from CommonJS:

app.post("/api/upload", upload.single("file"), async (req, res) => {
    const { fileTypeFromFile } = await import("file-type");
    const detected = await fileTypeFromFile(req.file.path);

    const allowed = ["image/jpeg", "image/png", "image/webp", "application/pdf"];
    if (!detected || !allowed.includes(detected.mime)) {
        fs.unlinkSync(req.file.path);
        return res.status(415).json({
            error: "File content does not match an allowed type",
            declared: req.file.mimetype,
            detected: detected ? detected.mime : null
        });
    }

    res.json({ filename: req.file.filename, mime: detected.mime, verified: true });
});

One caveat worth knowing: file-type inspects the file signature, not the payload. A structurally valid PNG can still smuggle an exploit in its data — that’s what the virus-scanning layer in the FAQ is for.

Image dimension validation with Sharp

const express = require("express");
const multer = require("multer");
const sharp = require("sharp");

const app = express();

const upload = multer({
    storage: multer.memoryStorage(),
    limits: { fileSize: 5 * 1024 * 1024 },
    fileFilter: (req, file, cb) => {
        if (file.mimetype.startsWith("image/")) {
            cb(null, true);
        } else {
            cb(new Error("Only images allowed"), false);
        }
    }
});

app.post("/api/avatar", upload.single("avatar"), async (req, res) => {
    try {
        const metadata = await sharp(req.file.buffer).metadata();

        if (metadata.width > 2000 || metadata.height > 2000) {
            return res.status(400).json({
                error: "Image too large. Max dimensions: 2000x2000",
                actual: `${metadata.width}x${metadata.height}`
            });
        }

        if (metadata.width < 100 || metadata.height < 100) {
            return res.status(400).json({
                error: "Image too small. Min dimensions: 100x100",
                actual: `${metadata.width}x${metadata.height}`
            });
        }

        const processedImage = await sharp(req.file.buffer)
            .resize(256, 256, { fit: "cover" })
            .jpeg({ quality: 80 })
            .toBuffer();

        // Persist processedImage to disk or S3 here
        res.json({
            message: "Avatar uploaded",
            original: `${metadata.width}x${metadata.height}`,
            processed: "256x256"
        });
    } catch (err) {
        res.status(400).json({ error: "Invalid image file" });
    }
});

app.listen(3000);

Complete upload middleware with all validations

const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");

const app = express();

const CONFIG = {
    maxFileSize: 5 * 1024 * 1024,
    maxFiles: 5,
    allowedMimetypes: ["image/jpeg", "image/png", "image/webp", "application/pdf"],
    allowedExtensions: [".jpg", ".jpeg", ".png", ".webp", ".pdf"],
    uploadDir: "uploads/"
};

// Overrides are merged into CONFIG, so callers can pass only what changes
function createUploadMiddleware(overrides = {}) {
    const config = { ...CONFIG, ...overrides };

    const fileFilter = (req, file, cb) => {
        const ext = path.extname(file.originalname).toLowerCase();

        if (!config.allowedMimetypes.includes(file.mimetype)) {
            return cb(new Error(`MIME type ${file.mimetype} not allowed`), false);
        }

        if (!config.allowedExtensions.includes(ext)) {
            return cb(new Error(`Extension ${ext} not allowed`), false);
        }

        cb(null, true);
    };

    const storage = multer.diskStorage({
        destination: (req, file, cb) => {
            fs.mkdirSync(config.uploadDir, { recursive: true });
            cb(null, config.uploadDir);
        },
        filename: (req, file, cb) => {
            const safeName = path.basename(file.originalname)
                .replace(/[^a-zA-Z0-9.-]/g, "_")
                .substring(0, 100);
            cb(null, `${Date.now()}-${safeName}`);
        }
    });

    return multer({
        storage,
        limits: {
            fileSize: config.maxFileSize,
            files: config.maxFiles
        },
        fileFilter
    });
}

const uploadMiddleware = createUploadMiddleware();

app.post("/api/documents", uploadMiddleware.array("files", 5), async (req, res) => {
    const { fileTypeFromFile } = await import("file-type");

    for (const f of req.files) {
        const detected = await fileTypeFromFile(f.path);
        if (!detected || !CONFIG.allowedMimetypes.includes(detected.mime)) {
            fs.unlinkSync(f.path);
            return res.status(415).json({ error: `${f.originalname}: content not allowed` });
        }
    }

    const results = req.files.map(f => ({
        filename: f.filename,
        size: f.size,
        path: f.path
    }));
    res.json({ uploaded: results });
});

Explanation

Upload validation works in five layers, cheapest first. You want the cheap rejections to happen before the expensive ones — there’s no point parsing a file that was never going to be allowed.

  • Size limits — the fileSize and files options tell multer to reject oversized files and oversized batches before they hit disk.
  • Extension check — the extension is your first filter, but it’s trivial to fake, so treat it as a convenience check, not a security boundary.
  • MIME type check — multer reads the client-sent Content-Type. Spoofable too, but it still catches honest mistakes and lazy attacks.
  • Magic bytes — the first bytes of the file say what it actually is. A JPEG always opens with FF D8 FF; a PDF with %PDF. This is where disguised uploads get caught.
  • Content inspection — image dimensions via Sharp, or a full parse/virus scan for anything riskier. Most expensive layer, so it runs last.

Filename sanitization isn’t a layer so much as a rule that applies everywhere: anything in originalname — including ../ — is attacker input until you clean it.

When a layer rejects a file, the client deserves a precise answer. Multer surfaces its own rejections as MulterError codes; map them to status codes that tell the caller what went wrong:

MulterError codeMeaningStatus
LIMIT_FILE_SIZEFile over fileSize413
LIMIT_FILE_COUNTToo many files400
LIMIT_UNEXPECTED_FILEWrong field name400
LIMIT_PART_COUNTToo many multipart parts400
flowchart diagram: Client upload

In production, a few extra rules apply. Uploads belong outside the web root — or straight to S3/GCS — so a .js or .php file can’t be executed by the web server. Proxy limits matter too: nginx rejects anything over client_max_body_size (1 MB by default) before Express ever sees it. And uploads are just one input surface — pair this recipe with input validation and input sanitization for the rest of the request body.

Variants

Validation LayerMethodReliabilityOverhead
ExtensionString checkLow (spoofable)Negligible
MIME typeContent-Type headerMedium (spoofable)Negligible
Magic bytesManual header read or file-typeHighLow (first N bytes)
Content scanFull file parse (Sharp, pdf-lib)Very highMedium
Virus scanClamAV / external serviceVery highHigh (async)

Best Practices

  • Pin multer to 2.x (npm install multer@^2). The 1.x line stopped getting patches and still carries open vulnerabilities.
  • Use diskStorage for anything over ~1 MB. Buffers live in RAM, so keep memoryStorage for small files you process immediately — the avatar resize above is the right shape for it.
  • Sanitize every filename before it touches disk. Strip path separators and cap the length; ../ in originalname is the oldest trick in the book.
  • Set a fileSize cap and a files cap. Limiting size alone won’t stop a request carrying thousands of tiny files.
  • Check the actual bytes, not just the declared type — file-type or a manual signature read both work.
  • Store uploads outside the web root, or stream them straight to object storage. Serving user files from your app directory is how webshells get executed.
  • Run images through Sharp even when dimensions look fine — processing strips EXIF GPS data that users rarely mean to share.
  • Put a rate limit on upload endpoints. Validation costs CPU per request, so an unthrottled upload route is an easy DoS target — the endpoint security checklist covers this and the rest of the endpoint surface.

Common Mistakes

  • Trusting the Content-Type header — the client writes it, so it’s a claim, not a fact.
  • Saving files under originalname without sanitizing. ../../etc/passwd in that field can overwrite system files.
  • Running memoryStorage on big uploads. Ten concurrent 50 MB files and the process is out of RAM.
  • Skipping the files limit, so one request can carry thousands of files.
  • Serving uploads from the same directory as application code — the classic path to code execution.
  • Checking only RIFF for webp. WAV and AVI share that container header; verify the WEBP tag at bytes 8–11 or let file-type handle it.
  • Staying on multer 1.x because it still works. It’s got known vulnerabilities — upgrade.

Further Reading

Companion code: the companion repo has the complete middleware and the avatar example as runnable apps.

Frequently Asked Questions

How do I upload files directly to S3 instead of local disk?

Swap multer.diskStorage for multer-s3:

const multerS3 = require("multer-s3");
const { S3Client } = require("@aws-sdk/client-s3");

const s3 = new S3Client({ region: "us-east-1" });

const upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: "my-bucket",
        key: (req, file, cb) => {
            cb(null, `uploads/${Date.now()}-${file.originalname}`);
        }
    }),
    limits: { fileSize: 5 * 1024 * 1024 }
});

Content verification gets trickier here — the file never lands on your disk — so run file-type on the buffered stream or validate the object in S3 after upload.

How do I scan uploaded files for viruses?

Hook the clamscan package into a local ClamAV daemon and run it after multer saves the file:

const NodeClam = require("clamscan");

const clamscan = new NodeClam().init({
    clamscan: { path: "/usr/bin/clamscan" }
});

async function scanFile(filePath) {
    const { isInfected } = await clamscan.scanFile(filePath);
    if (isInfected) {
        fs.unlinkSync(filePath);
        throw new Error("File infected");
    }
}

Scan asynchronously when you can — holding the request open for a full AV scan adds seconds of latency to every upload.

Should I use memoryStorage or diskStorage?

memoryStorage fits small files (under ~1 MB) you process right away, like resizing an avatar. Everything else belongs on diskStorage — every buffered file sits in RAM, so a handful of concurrent large uploads will exhaust it fast.

How do I handle multiple file types with different limits?

Build one middleware per type. The factory merges your overrides into the defaults, so you only declare what changes:

const imageUpload = createUploadMiddleware({
    allowedMimetypes: ["image/jpeg", "image/png"],
    allowedExtensions: [".jpg", ".png"],
    maxFileSize: 2 * 1024 * 1024
});

const docUpload = createUploadMiddleware({
    allowedMimetypes: ["application/pdf"],
    allowedExtensions: [".pdf"],
    maxFileSize: 10 * 1024 * 1024
});

app.post("/api/images", imageUpload.single("image"), imageHandler);
app.post("/api/docs", docUpload.single("doc"), docHandler);