← Back to Node.js, page 7

nodejs-0137 · Medium mid

How do you handle multipart file uploads in Node.js safely: streaming, size limits, file names and content checks?

Parse multipart/form-data as a stream (busboy, which multer wraps) and write the file to disk or object storage while it arrives, so memory stays flat. Set limits for file size, number of files and fields, never trust the client file name or MIME type, generate your own name, store outside the web root, check the content (magic bytes) and size, and scan if needed.

Full answer

How multipart works

  • The browser sends one request with several parts separated by a boundary. Each part has headers (field name, file name, content type) and a body.
  • Do not buffer it with express.json or read it all into memory. Use a streaming parser: busboy (low level), multer (Express middleware built on busboy), or formidable.

Safe handling checklist

  • Limits: fileSize, files, fields, parts, and headerPairs. When the file limit is hit, busboy marks the stream as truncated and you must discard the data and answer 413 Payload Too Large. Also set a limit at the reverse proxy.
  • File name: treat it as untrusted text. Path traversal (../../etc/passwd) and strange characters are real attacks. Use path.basename at least, and best generate a random name (crypto.randomUUID()) and store the original name as metadata.
  • MIME type and extension: both come from the client and can be faked. Check the first bytes (magic numbers, for example PNG starts with 89 50 4E 47) or use a library like file-type.
  • Storage: write outside the public folder, or to object storage with a private bucket. Serve downloads through a handler that sets Content-Disposition and a safe content type. Never run uploaded files.
  • Clean up: remove partial files on abort, error or limit exceeded.
  • Authentication and rate limits before accepting the body.
  • Images and documents may need re-encoding or virus scanning.
  • For big files, consider direct uploads to object storage with signed URLs so your Node process does not carry the bytes.

Backpressure: pipe the file stream into the destination with pipeline, so a slow disk slows the upload instead of filling memory.

javascript
const http = require('node:http');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const crypto = require('node:crypto');
const busboy = require('busboy');
const { pipeline } = require('node:stream/promises');

const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), 'uploads-'));
const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47]);

const server = http.createServer((req, res) => {
  if (req.method !== 'POST') return res.writeHead(405).end();
  const bb = busboy({ headers: req.headers, limits: { fileSize: 64, files: 1, fields: 5 } });
  const result = { fields: {}, files: [] };
  const writes = [];

  bb.on('field', (name, value) => { result.fields[name] = value; });
  bb.on('file', (name, stream, info) => {
    const saveAs = `file-${result.files.length + 1}.bin`; // our own name, never info.filename
    const target = path.join(uploadDir, saveAs);
    const entry = { field: name, clientName: path.basename(info.filename), saveAs, truncated: false, looksLikePng: false };
    result.files.push(entry);
    let first = Buffer.alloc(0);
    stream.on('data', (chunk) => { if (first.length < 4) first = Buffer.concat([first, chunk]).subarray(0, 4); });
    stream.on('limit', () => { entry.truncated = true; });
    writes.push(pipeline(stream, fs.createWriteStream(target)).then(() => { entry.looksLikePng = first.equals(PNG); entry.bytes = fs.statSync(target).size; }));
  });
  bb.on('close', async () => {
    await Promise.all(writes);
    const tooBig = result.files.some((f) => f.truncated);
    if (tooBig) for (const f of result.files) fs.rmSync(path.join(uploadDir, f.saveAs), { force: true });
    res.writeHead(tooBig ? 413 : 201, { 'content-type': 'application/json' }).end(JSON.stringify(result));
  });
  req.pipe(bb);
});

server.listen(0, '127.0.0.1', async () => {
  const url = 'http://127.0.0.1:' + server.address().port;
  const send = async (label, form) => {
    const res = await fetch(url, { method: 'POST', body: form });
    console.log(label, '->', res.status, JSON.stringify(await res.json()));
  };

  const small = new FormData();
  small.append('title', 'Holiday');
  small.append('photo', new Blob([PNG, Buffer.alloc(20)], { type: 'image/png' }), '../../etc/evil.png');
  await send('small file', small);

  const fake = new FormData();
  fake.append('photo', new Blob(['just text, not an image'], { type: 'image/png' }), 'image.png');
  await send('fake image', fake);

  const big = new FormData();
  big.append('photo', new Blob([Buffer.alloc(500)]), 'big.bin');
  await send('too large', big);
  console.log('files left on disk after the rejected upload:', fs.readdirSync(uploadDir).length);

  server.close();
  fs.rmSync(uploadDir, { recursive: true });
});

Three uploads are sent: a small PNG with a hostile file name, a text file that claims to be an image, and a file above the size limit. Install first with npm install busboy (run here with busboy 1.6.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): small file -> 201 {"fields":{"title":"Holiday"},"files":[{"field":"photo","clientName":"evil.png","saveAs":"file-1.bin","truncated":false,"looksLikePng":true,"bytes":24}]} fake image -> 201 {"fields":{},"files":[{"field":"photo","clientName":"image.png","saveAs":"file-1.bin","truncated":false,"looksLikePng":false,"bytes":23}]} too large -> 413 {"fields":{},"files":[{"field":"photo","clientName":"big.bin","saveAs":"file-1.bin","truncated":true,"looksLikePng":false,"bytes":64}]} files left on disk after the rejected upload: 0

Key points

  • Parse multipart as a stream, never into one big buffer.
  • Set limits and answer 413 when the file is truncated.
  • Ignore the client file name, generate your own.
  • Check magic bytes, not the extension or declared type.
  • Clean up partial files and store outside the web root.

Common mistakes

  • Trusting the file name and writing it into a path.
  • Trusting the declared Content-Type of the file.
  • Buffering whole uploads in memory.
  • Leaving truncated or rejected files on disk.
  • Storing uploads inside the public folder.

Follow-ups

  • How do signed upload URLs to object storage change the design?
  • How does multer differ from busboy?
  • How do you limit total request size at the proxy?

Tips

  • Open with 'stream, limit, rename, verify'.
  • Say that the client controls name and type.
  • Mention 413 for oversized files.