Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

How to Limit Image Upload Size in Multer Before Processing

Use Multer’s finite file-size limit to stop oversized multipart files during parsing, then inspect accepted image metadata with Sharp before costly processing.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To reject oversized multipart images before image processing, set a finite Multer limits.fileSize on the specific upload route. Once the parser accepts the file, use Sharp’s metadata() to check its format and dimensions before decoding or transforming it. The byte limit and metadata check solve different problems: metadata inspection does not stop the upload bytes from first reaching the parser.

What “metadata first” does—and does not—mean

Multer enforces a byte ceiling while parsing a multipart request. Sharp’s metadata() reads image-header information without decoding compressed pixel data, so you can apply format and dimension rules before expensive image work. It is not an early network-level size check: the request still has to reach the application’s parser, and the header must be available to inspect.

As an Amazon Associate I earn from qualifying purchases.

Choose the maximum file size from your product requirements and deployment capacity; the documentation does not establish one universal safe limit. Multer’s documented default for fileSize is Infinity, so omitting it does not impose a per-file ceiling. Multer documentation

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure limits on the upload route

Install upload middleware only on routes that accept uploads. Multer warns against using it globally, where it could process files on routes that were not intended to accept them. Set limits for the multipart request shape as well as the file: files, fields, and parts can bound how many files, text fields, and total parts the parser accepts. Multer says these limits can help protect against denial-of-service attacks. Multer documentation

const upload = multer({
  storage: multer.diskStorage({
    destination: controlledTemporaryDirectory,
    filename: temporaryFilenameGenerator,
  }),
  limits: {
    fileSize: MAX_IMAGE_BYTES,
    files: 1,
    fields: MAX_FIELDS,
    parts: MAX_PARTS,
  },
});

app.post('/images', authenticate, upload.single('image'), async (req, res, next) => {
  try {
    const metadata = await sharp(req.file.path).metadata();

    // Apply accepted-format and dimension rules before pixel processing.
    // Transform or persist only after those checks pass.
    res.sendStatus(202);
  } catch (error) {
    next(error);
  }
});

This is an illustrative route shape, not tested drop-in code. Define MAX_IMAGE_BYTES, the field and part limits, temporary destination, and filename generation for your application. Remove temporary files when a file is rejected or processing fails, and map Multer errors such as LIMIT_FILE_SIZE to an intentional client response. Treat the client-supplied original filename as untrusted.

Inspect image metadata before pixel processing

After Multer has accepted the file, call metadata() on the stored path, buffer, or other supported input. Sharp can report properties including format, dimensions, pages, and available header metadata. Use those values to enforce the application’s image policy before resizing, encoding, or performing other pixel-based work. Sharp describes this operation as fast access to uncached metadata without decoding compressed pixel data. Sharp input metadata documentation

  • Check the reported format against the formats your application accepts; do not rely only on a filename extension or client-supplied content type.
  • Apply width, height, and, where relevant, page-count rules before invoking transformations.
  • Dimensions reported from metadata do not account for EXIF orientation unless orientation is handled separately. Account for that when interpreting width and height. Sharp input metadata documentation

Metadata validation does not replace parser limits. The parser has already received enough of the request to provide the image input, and metadata says nothing by itself about whether the total multipart request is acceptable.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose storage with concurrency in mind

Multer’s memory storage retains each complete uploaded file as a Buffer. That can be convenient for small, controlled workloads, but large files or many simultaneous uploads can exhaust process memory. Disk storage or a custom storage engine changes where bytes are held; it does not remove the need to set file and request limits. Multer documentation

Rank #3
SANDISK 256GB Extreme PRO SD Memory Card, Up to 200MB/s Read Speeds, UHS-I
  • Save time with card offload speeds of up to 200MB/s powered by SanDisk QuickFlow Technology (Up to 200MB/s read speeds, engineered with proprietary technology to reach speeds beyond UHS-I 104MB/s, require compatible devices capable of reaching such speeds. Based on internal testing; performance may be lower depending upon host device, interface, usage conditions and other factors. 1MB=1,000,000 bytes. X = 150KB/sec. SanDisk QuickFlow Technology is only available for 64GB, 128GB, 256GB, 512GB and 1TB capacities. 1GB=1,000,000,000 bytes. 1TB=1,000,000,000,000 bytes. Actual user storage less.)
  • Pair with the SanDisk Professional PRO-READER SD and microSD to achieve maximum speeds (sold separately)
  • Shot speeds up to 140MB/s (Write speed up to 140MB/s. Based on internal testing; performance may be lower depending upon host device, interface, usage conditions and other factors. 1MB=1,000,000 bytes. X = 150KB/sec.)
  • Perfect for shooting 4K UHD video and sequential burst mode photography (Full HD (1920x1080) and 4K UHD (3840 x 2160) video support may vary based upon host device, file attributes and other factors. See HD page on SanDisk site.)
  • UHS Speed Class 3 (U3) and Video Speed Class 30 (V30) (UHS Speed Class 3 designates a performance option designed to support 4K UHD video recording with enabled UHS host devices. UHS Video Speed Class 30 (V30), sustained video capture rate of 30MB/s, designates a performance option designed to support real-time video recording with UHS enabled host devices. See the SD Association’s official website.)

For a disk-backed route, use a controlled temporary location, clean up rejected and completed files according to your persistence workflow, and avoid using the original filename as a filesystem path. If you choose memory storage, account for the number of concurrent accepted files as well as each file’s configured maximum.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why stream thresholds are not upload caps

Node.js streams use backpressure to coordinate a producer with a consumer. A stream’s highWaterMark is a threshold that influences when flow pauses; it is not a strict cap on the total memory an upload operation can use. It cannot substitute for Multer’s explicit byte and part limits or for planning around concurrent requests. Node.js stream documentation

Rank #4
SANDISK 64GB Extreme PRO SDXC UHS-I Memory Card - C10, U3, V30, 4K UHD, SD Card - SDSDXXU-064G-GN4IN
  • Save time with card offload speeds of up to 200MB/s powered by SanDisk QuickFlow Technology (Up to 200MB/s read speeds, engineered with proprietary technology to reach speeds beyond UHS-I 104MB/s, require compatible devices capable of reaching such speeds. Based on internal testing; performance may be lower depending upon host device, interface, usage conditions and other factors. 1MB=1,000,000 bytes. X = 150KB/sec. SanDisk QuickFlow Technology is only available for 64GB, 128GB, 256GB, 512GB and 1TB capacities. 1GB=1,000,000,000 bytes. 1TB=1,000,000,000,000 bytes. Actual user storage less.)
  • Pair with the SanDisk Professional PRO-READER SD and microSD to achieve maximum speeds (sold separately)
  • Shot speeds up to 90MB/s (Write speed up to 90MB/s. Based on internal testing; performance may be lower depending upon host device. 1MB=1,000,000 bytes. X = 150KB/sec.)
  • Perfect for shooting 4K UHD video and sequential burst mode photography (Full HD (1920x1080) and 4K UHD (3840 x 2160) video support may vary based upon host device, file attributes and other factors. See HD page on SanDisk site.)
  • UHS Speed Class 3 (U3) and Video Speed Class 30 (V30) (UHS Speed Class 3 designates a performance option designed to support 4K UHD video recording with enabled UHS host devices. UHS Video Speed Class 30 (V30), sustained video capture rate of 30MB/s, designates a performance option designed to support real-time video recording with UHS enabled host devices. See the SD Association’s official website.)

Plan the rest of the request path

Multer’s route-level limit governs parsing in the application. If requests pass through a reverse proxy or another upstream service, configure its request-size and timeout policies for the same intended behavior; those settings are deployment-specific and are not established by the Multer or Sharp APIs. The incoming HTTP request is a stream, so application limits should be considered alongside how the surrounding infrastructure receives and forwards it. Node.js HTTP documentation

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Confirm that the installed Sharp release supports your Node.js runtime. Sharp’s homepage currently states support for Node.js 20.9.0 and later when the runtime supports Node-API v9; check the compatibility requirements for the release you install because they can change. Sharp

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.