Streaming file uploads in Fastify with fastify-multipart — no buffering everything into memory.
Prerequisites
- Node.js >=16
- Fastify project setup
Step 1: Install the Plugin
npm install fastify-multipart
Step 2: Register Plugin
In src/server.ts:
import Fastify from "fastify";
import multipart from "fastify-multipart";
const app = Fastify({ logger: true });
app.register(multipart);
app.post("/upload", async (req, reply) => {
const parts = req.parts();
for await (const part of parts) {
if (part.file) {
await pump(part.file, fs.createWriteStream(`uploads/${part.filename}`));
}
}
reply.send({ status: "ok" });
});
app.listen({ port: 3000 });
Step 3: Handle Streams and Save Files
Install utility:
npm install pump
Use pump to pipe the file stream:
import { pump } from "pump";
import fs from "fs";
Step 4: Test Uploads
curl -F "file=@./path/to/file.png" http://localhost:3000/upload
Streaming multipart means large files won’t eat your RAM. Register the plugin, iterate req.parts(), pipe each file stream to disk or S3.