@fastify/multipart
Streaming multipart/form-data parsing plugin for Fastify with async iterators and disk or memory upload modes
Repository Health
Technical Analysis
@fastify/multipart is the official Fastify plugin for parsing multipart/form-data request bodies, built on top of @fastify/busboy. It registers as a standard Fastify plugin and decorates the request object with file(), files(), parts(), and saveRequestFiles() methods, giving you async-iterator access to uploaded files and form fields as they stream off the wire rather than forcing you to buffer the entire request in memory first.
The plugin supports three distinct consumption models — pure streaming (pipe each file straight to disk or S3 as it arrives), disk mode (saveRequestFiles() writes uploads to the OS temp directory and auto-cleans them after the response ends), and in-memory accumulation (toBuffer() for small files). It also offers an attachFieldsToBody mode that maps parsed fields directly onto request.body, so upload routes can look and validate like ordinary JSON routes, including JSON Schema validation and shared-schema support for multipart fields.
What You Get
- Request decorators
req.file(),req.files(), andreq.parts()for async-iterator-based streaming access to multipart parts - Disk mode via
req.saveRequestFiles()that writes uploads to a temp directory and automatically removes them once the response finishes - In-memory mode via
part.toBuffer()for accumulating small files or fields without touching the filesystem attachFieldsToBodyoption (boolean or'keyValues') to map multipart fields ontorequest.bodyfor JSON Schema-style validation- Configurable limits (
parts,fields,files,fileSize,fieldSize) with typed errors exposed onfastify.multipartErrors(FilesLimitError,RequestFileTooLargeError, etc.) - Automatic JSON parsing of fields sent with an
application/jsoncontent-type viasecure-json-parse, guarding against prototype-pollution field names - First-class TypeScript typings and an HTTP/2 compatible parsing path
Common Use Cases
- Accepting file uploads (avatars, documents, CSVs) in a Fastify API and streaming them straight to disk, S3, or another store without buffering the whole payload in memory
- Building upload endpoints that mix file parts with regular form fields and need both validated together via JSON Schema (
attachFieldsToBody) - Enforcing upload size and count limits at the framework layer and returning typed 413/406 errors instead of ad hoc checks in route handlers
- Rebuilding a browser
FormDataobject server-side (viarequest.formData()) to forward to a downstream service or SDK that expectsFormData
Under The Hood
Architecture: The plugin is a single fastify-plugin-wrapped function (index.js) that hooks into Fastify’s content-type parser pipeline: fastify.addContentTypeParser('multipart/form-data', setMultipart) marks the incoming request as multipart without consuming the body, then a set of decorateRequest calls (file, files, parts, saveRequestFiles, isMultipart, formData) lazily construct a @fastify/busboy instance per-request inside handleMultipart(). That function bridges busboy’s event-emitter API (field, file, partsLimit, filesLimit, error) into a pull-based async generator using a small hand-rolled queue (values/pendingHandler), so for await (const part of req.parts()) backpressures correctly against the underlying stream. Disk mode (saveRequestFiles) additionally tracks written temp paths on the request and registers an onResponse hook that unlinks them, so callers never have to remember cleanup themselves.
Tech Stack: Runtime dependencies are deliberately narrow — @fastify/busboy (the actual multipart tokenizer, a fork of the original busboy), fastify-plugin (for correct encapsulation-skipping registration), @fastify/deepmerge (to merge global plugin options with per-route multipartOptions), @fastify/error (typed, serializable error classes), and secure-json-parse (safe JSON.parse for multipart JSON fields, guarding against prototype pollution). It targets Fastify 5.x and is pure CommonJS with a hand-written types/index.d.ts rather than being generated from source.
Code Quality: The test/ directory has 22 files and roughly 90 test cases covering disk mode, stream mode, HTTP/2, file/field limits, malformed uploads, premature connection close, and prototype-pollution field names (multipart-security.test.js), and package.json wires c8 --100 node --test, meaning CI enforces 100% statement/branch coverage on every change. Error paths are modeled as dedicated typed error classes (PartsLimitError, RequestFileTooLargeError, PrototypeViolationError, etc.) built with @fastify/error rather than generic thrown strings, and the type definitions carry a separate tstyche type-test suite (types/*.tst.ts) checked in CI alongside the runtime tests.
API Design: Getting started is a single fastify.register(require('@fastify/multipart')) call, after which every route on the instance gains req.file()/req.files()/req.parts(). The API deliberately mirrors familiar Node stream idioms (data.file is a readable stream you can pipeline() straight into fs.createWriteStream), while saveRequestFiles() and attachFieldsToBody give progressively higher-level escape hatches for callers who don’t want to manage streams themselves. The one sharp edge, called out prominently in the README, is that an unconsumed file stream leaves the returned promise unresolved — a busboy-inherited constraint rather than a design choice, but one every new user hits at least once.
Used by 8 apps in this directory
Activepieces
Automation · AI Assistants
Open-source AI automation platform that converts 280+ workflow integrations into MCP servers for LLMs, with no-code builders and TypeScript extensibility.
Dittofeed
Marketing · Automation
Open-source omni-channel customer engagement platform for automating transactional and marketing messages via email, SMS, WhatsApp, Slack, and mobile push.
Docmost
Productivity · Note Taking · Collaboration
Self-hosted collaborative wiki and knowledge base with real-time editing, diagrams, AI assistance, and enterprise access controls — a modern alternative to Confluence and Notion.
Infisical
Security · Devops
The open-source platform for secrets, certificates, privileged access, and AI agent security — all in one self-hostable system.
Kimi Code CLI
AI Code Assistants · AI Agents · Developer Tools
A single-binary, terminal-native coding agent that reads, edits, and runs code end to end, built by Moonshot AI for Kimi models but pluggable with Anthropic, OpenAI, and Google providers too.
nao
AI Development · Analytics
Build and deploy an open-source analytics agent that understands your data warehouse and answers business questions in plain English.
Palmr.
File Storage · Security
Self-hosted, privacy-focused file sharing without limits
superglue
AI Agents · Data Engineering · Developer Tools
superglue is an AI-agent-driven integration engine that turns plain-English descriptions of enterprise systems into production-grade API tools, ERP/CRM connectors, and data pipelines — self-hosted or cloud, Y Combinator-backed (W25).