Multipart Parser With Field Limits

Parse multipart form data with per-field size limits field count cap and content type validation for safe uploads.

JavascriptFile Upload

Code

javascriptsnippet
1 line
export function multipartParser({maxFields=20,maxFieldSize=1024*1024,allowedTypes=['text/plain','application/json']}={}){return async function parse(req){const boundary=req.headers['content-type']?.match(/boundary=(.+)$/)?.[1];if(!boundary)throw new Error('no boundary');const fields={};let count=0;for await(const part of req.multipart(boundary)){if(++count>maxFields)throw new Error('too many fields');if(part.data.length>maxFieldSize)throw new Error('field too large');if(part.filename){fields[part.name]={filename:part.filename,data:part.data,contentType:part.contentType};}else{if(!allowedTypes.includes(part.contentType))throw new Error('unsupported type');fields[part.name]=part.data.toString('utf8');}}return fields;};}

Ordering of the operations

Multipart Parser With Field Limits is built around the functions multipartParser and parse.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Error is the guard’s signal — thrown at the branch, before any partial work happens.

What to watch for

  • The guard !boundary short-circuits the flow with an early throw when its condition holds.

Putting it to use

Signature: export function multipartParser({maxFields=20,maxFieldSize=1024*1024,allowedTypes=['text/plain','applicatio…

multipartParser is what another module would consume; nothing else here is load-bearing for callers.

FAQ

How does the snippet fail?
`Error` is raised at the guard (`!boundary`), so invalid state never reaches the main logic.
What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `multipartParser`, `parse` at load time.