Learning objectives
After reading this article you will be able to:
- Receive a multipart upload as a stream in Express, without loading the file into memory
- Validate the file's type, signature and size on the server before storing it
- Send it to storage with the AWS SDK's Upload or straight from the browser with a presigned URL
On this page
- Which path does the file take to storage?
- What do you need before you start?
- How do you receive the file as a stream?
- How do you validate type and size on the server?
- How do you let the browser upload straight to storage?
- How do you test that the upload worked?
- What are the most common errors?
- How to do this on Square Cloud
- FAQs
Accepting a file in a form looks like the easy part of a Node.js app. The trouble comes later: the process runs out of memory on a 2 GB video, someone uploads an executable renamed to .jpg, or the files written to the uploads folder vanish on the next deploy.
This guide builds the full path with Express: the form, streaming the body, validating on the server and sending the file to any S3-compatible storage with the AWS SDK v3. At the end, it shows the alternative where the browser uploads straight to storage. If you still keep uploads on the app's disk, first read why uploaded files disappear after a deploy.
Which path does the file take to storage?#
There are two designs, and the choice changes the code:
| Through the server (streaming) | Straight from the browser (presigned URL) | |
|---|---|---|
| Where the bytes go | Browser, your app, storage | Browser, storage |
| Content validation | Before storing | After the upload |
| App memory and bandwidth | One chunk at a time, but all the traffic | Almost none |
| Best for | Images, PDFs, files up to tens of MB | Videos and large files |
Both work with the same storage and can live in the same app. The code below starts with the first one; the section on direct uploads covers the second.
What do you need before you start?#
- Node.js on an LTS release and a project with
"type": "module"inpackage.json. - A bucket on an S3-compatible storage service and a key pair with write access to it.
- The dependencies:
npm install express busboy @aws-sdk/client-s3 @aws-sdk/lib-storage @aws-sdk/s3-request-presignerCredentials go in a .env file, outside the repository:
S3_ENDPOINT=https://s3.example.com
S3_REGION=us-east-1
S3_BUCKET=my-bucket
S3_ACCESS_KEY=your-access-key
S3_SECRET_KEY=your-secret-keyHow do you receive the file as a stream?#
busboy reads the multipart/form-data body as it arrives and hands you each file as a stream. The Upload class from @aws-sdk/lib-storage consumes that stream and sends it to storage in parts, without knowing the size in advance. Neither of them gathers the whole file in memory.
// server.mjs
import { randomUUID } from "node:crypto";
import { Transform } from "node:stream";
import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";
import busboy from "busboy";
import express from "express";
const s3 = new S3Client({
region: process.env.S3_REGION,
endpoint: process.env.S3_ENDPOINT, // omit on AWS
forcePathStyle: process.env.S3_PATH_STYLE === "true",
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY,
secretAccessKey: process.env.S3_SECRET_KEY,
},
});
const LIMIT = 20 * 1024 * 1024; // 20 MB per file
// accepted type -> stored extension and the format's first bytes
const TYPES = {
"image/jpeg": { ext: "jpg", signature: [0xff, 0xd8, 0xff] },
"image/png": { ext: "png", signature: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] },
"application/pdf": { ext: "pdf", signature: [0x25, 0x50, 0x44, 0x46, 0x2d] },
};
const fail = (status, message) => Object.assign(new Error(message), { status });
// Lets the bytes through and fails if the start isn't the format or the size passes the limit.
function validate(signature) {
let total = 0;
let head = Buffer.alloc(0); // becomes null once checked
return new Transform({
transform(chunk, _encoding, done) {
total += chunk.length;
if (total > LIMIT) return done(fail(413, "file is larger than the limit"));
if (head === null) return done(null, chunk);
head = Buffer.concat([head, chunk]);
if (head.length < signature.length) return done();
if (!signature.every((byte, i) => head[i] === byte)) {
return done(fail(415, "content does not match the type"));
}
const checked = head;
head = null;
done(null, checked);
},
flush(done) {
done(head === null ? null : fail(415, "file is empty or incomplete"));
},
});
}
const app = express();
app.use(express.static("public")); // serves public/index.html with the form
app.post("/upload", (req, res) => {
const reply = (status, json) => {
if (!res.headersSent) res.status(status).json(json);
};
let bb;
try {
bb = busboy({ headers: req.headers, limits: { files: 1 } });
} catch {
return reply(400, { error: "send a multipart form" });
}
let gotFile = false;
bb.on("file", async (_field, file, { mimeType }) => {
gotFile = true;
const type = TYPES[mimeType];
if (!type) {
file.resume(); // discard the content so busboy can move on
return reply(415, { error: "file type not allowed" });
}
let error = null;
const body = validate(type.signature);
body.on("error", (e) => {
error = e;
file.resume(); // discard the rest of the file
});
file.on("error", (e) => body.destroy(e)); // the client gave up halfway
file.pipe(body);
const key = `uploads/${randomUUID()}.${type.ext}`;
try {
await new Upload({
client: s3,
params: { Bucket: process.env.S3_BUCKET, Key: key, Body: body, ContentType: mimeType },
}).done();
reply(201, { key }); // store the key in your database, next to the file's owner
} catch (e) {
if (!error?.status) console.error(e);
reply(error?.status ?? 500, { error: error?.status ? error.message : "upload failed" });
}
});
bb.on("close", () => {
if (!gotFile) reply(400, { error: "no file sent" });
});
bb.on("error", () => reply(400, { error: "invalid or incomplete form" }));
req.pipe(bb);
});
app.listen(process.env.PORT || 3000);And the form, in public/index.html:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="image/jpeg,image/png,application/pdf" required>
<button>Upload</button>
</form>Three details keep the process from hanging or crashing. busboy requires every file stream to be consumed, so a rejected file gets resume(), which discards the bytes. The error listeners on busboy and on the file stream stop a client that cancels the upload from killing Node.js with an unhandled error event. And by default, Upload aborts the multipart upload when it fails (leavePartsOnError: false), so an upload rejected halfway leaves no orphaned parts.
In memory, each upload takes roughly partSize × queueSize: with Upload's defaults (5 MB parts, 4 in parallel), about 20 MB, whatever the file size. Files smaller than one part go in a single PUT.
How do you validate type and size on the server?#
OWASP's file upload cheat sheet sums up the rule: an uploaded file's Content-Type comes from the user and is trivial to spoof. The code uses three layers, and none of them rests only on what the client declares:
- An allowlist of types. The
mimeTypebusboy reads from the form is only the first filter. Anything not inTYPESgets a 415 before a single byte reaches storage. - The file signature. Each format starts with fixed bytes:
FF D8 FFfor JPEG,89 50 4E 47 0D 0A 1A 0Afor PNG and%PDF-for PDF, according to the WHATWG MIME Sniffing standard. TheTransformgathers the start of the file until it has enough bytes and compares them. OWASP notes that signatures can be forged too, so this is one more layer, not the only one. - Size counted on the server. Node.js puts no limit on the request body. The code adds up the bytes going through and fails with 413 on the first byte past the limit, without waiting for the upload to finish.
The object key is a UUID plus the extension you picked from the type. The original filename never becomes a path: it can carry ../, odd characters or collide with someone else's file. If you want to show it later, keep it in your database next to the key. The form's accept attribute only filters the browser's file picker; it isn't validation.
Once the file is stored, decide who can read it. A product photo can have a public URL; a user's document stays private and goes out through a temporary link. The comparison is in public vs private files.
How do you let the browser upload straight to storage?#
For videos and large files, pushing every byte through your app costs bandwidth and process time. The usual pattern is for the API to sign a presigned URL for a PUT and for the browser to send the file straight to storage. Add the imports to the top of server.mjs and these routes:
import { DeleteObjectCommand, HeadObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
app.post("/upload-url", express.json(), async (req, res) => {
const type = TYPES[req.body?.contentType];
if (!type) return res.status(415).json({ error: "file type not allowed" });
const key = `uploads/${randomUUID()}.${type.ext}`;
const url = await getSignedUrl(
s3,
new PutObjectCommand({
Bucket: process.env.S3_BUCKET,
Key: key,
ContentType: req.body.contentType, // the browser must send the same value
}),
// without signableHeaders, SDK v3 leaves content-type out of the signature
{ expiresIn: 300, signableHeaders: new Set(["content-type"]) }, // 5 minutes
);
res.json({ url, key });
});
// the browser calls this route after the PUT; also check that the key belongs to the caller
app.post("/upload-url/confirm", express.json(), async (req, res) => {
const target = { Bucket: process.env.S3_BUCKET, Key: String(req.body?.key) };
try {
const { ContentLength } = await s3.send(new HeadObjectCommand(target));
if (ContentLength > LIMIT) {
await s3.send(new DeleteObjectCommand(target));
return res.status(413).json({ error: "file is larger than the limit" });
}
res.json({ key: target.Key, size: ContentLength });
} catch (e) {
const status = e.name === "NotFound" ? 404 : 500;
res.status(status).json({ error: status === 404 ? "file not found" : "storage error" });
}
});signableHeaders locks the type. By default, SDK v3's getSignedUrl leaves content-type out of the signature, so the browser could store the file under any type; with it, the PUT only goes through with the signed Content-Type.
The security difference is the order. A PUT URL accepts whatever file arrives, of any size up to the storage limit, so validation comes afterwards: the HEAD checks the size and deletes anything over the limit. To check the signature without downloading everything, a GetObject with Range: "bytes=0-15" fetches only the start. The browser code, with a Content-Type that matches the signed one, and the bucket's CORS setup are in CORS errors on direct uploads. For files of several GB, combine the presigned URL with a multipart upload.
How do you test that the upload worked?#
Start the server and send a file with curl, which builds the same form the browser does:
node --env-file=.env server.mjs
curl -i -F "file=@photo.jpg;type=image/jpeg" http://localhost:3000/uploadThe expected answer is HTTP/1.1 201 Created with {"key":"uploads/....jpg"}. Then test the validation by sending a text file labeled as an image, which should come back 415:
curl -i -F "file=@notes.txt;type=image/png" http://localhost:3000/uploadFinally, check the object in storage with the returned key:
aws s3api head-object --bucket my-bucket --key uploads/YOUR-KEY.jpg --endpoint-url "$S3_ENDPOINT"ContentLength must match the local file's size, and ContentType the type you sent.
What are the most common errors?#
Error: Multipart: Boundary not foundThe Content-Type arrived as multipart/form-data without the boundary. The usual cause is setting that header by hand in fetch or axios when sending a FormData. MDN's documentation says not to: without the manual header, the browser fills it in with the right boundary.
Error: Unexpected end of formThe body ended before the form did, usually because the client canceled the upload or the connection dropped. The error listener on busboy turns this into a 400 answer instead of a crashed process.
A large upload fails with 408. The Node.js HTTP server waits up to 300 seconds (server.requestTimeout) for the whole request. For files that take longer, raise the value on the object app.listen() returns, or move those files to direct browser uploads.
AccessDenied or SignatureDoesNotMatch. A key without access to the bucket, the wrong region or a server clock that's off. See AccessDenied and SignatureDoesNotMatch on S3.
The storage rejects uploads after an SDK update. By default, the AWS SDK computes a checksum on every upload, and some compatible services don't accept it. Set AWS_REQUEST_CHECKSUM_CALCULATION=WHEN_REQUIRED, as explained in the best S3 client tool.
Memory grows with every upload. Some middleware reads the whole body before your route, such as multer.memoryStorage() or a parser registered with app.use for every route. Register parsers only on the routes that need them.
The same flow in Python, with FastAPI and Flask, is in file uploads in Python.
How to do this on Square Cloud#
On Square Cloud's Blob Storage, this article's code runs after changing only the .env: S3_ENDPOINT=https://s3-blob.squarecloud.app, S3_REGION=auto, S3_PATH_STYLE=true and the S3 keys you derive from an API key in the "S3 access" tab of the dashboard. S3_BUCKET is public or private, the two fixed buckets you write to: images anyone may see go in public, delivered by a global edge CDN, and users' documents go in private, which only opens through a temporary link or a share link.
Each file can be up to 10 GB, and above 100 MB the upload has to be multipart. The Upload class from @aws-sdk/lib-storage already splits anything larger than one part into 5 MB parts, so the route through the server stays the same. A single PUT through a presigned URL, on the other hand, works for files up to 100 MB; above that, combine the presigned URL with multipart. SigV4 presigned URLs last up to 7 days, although minutes are enough for an upload, and CORS already accepts PUT from any origin; the API key needs write permission and the plan has to be active.
Blob's folder rules set a maximum size and the allowed extensions for everything uploaded to the folder, one more barrier for what arrives through a presigned URL. There is no ingress fee for uploads or egress fee for downloads, and every plan includes a storage quota. Explore Blob Storage.
Blob Storage
S3-compatible object storage with no egress fees
FAQs
Multer or busboy: which one should I use for uploads in Node.js?
Multer is an Express middleware written on top of busboy. With memory storage it keeps the whole file in a Buffer, which is fine for small files. To stream the file on to storage, using busboy directly gives you control over every chunk.
Can I trust the Content-Type the browser sends?
No. The declared type comes from the client and is easy to spoof, as OWASP warns. Use it as a first filter, also check the file's first bytes, and generate the name and extension yourself.
Why does a large upload fail with a 408 error?
By default, the Node.js HTTP server waits at most 300 seconds (requestTimeout) to receive the whole request and answers 408 when that runs out. For files that take longer, raise the timeout or let the browser upload straight to storage.
Should uploads go through my server or straight from the browser?
Through the server, you validate the content before storing it, but you pay for the bandwidth and process time. Straight from the browser with a presigned URL, the file skips your app, and validation happens after the upload.
More in Storage
See all 24 articles- What is a presigned (signed) URL?A presigned URL is a temporary link to a private file that works without login or credentials. See how it works, its limits and when to use it.
- What is object storage?Object storage keeps files as objects with a key and metadata, accessed over an HTTP API. See how it works, what it is for and where its limits are.
- What does 'S3-compatible' storage mean?S3 is Amazon's object storage and its API became the industry standard. Learn what S3-compatible means, what differs between providers, and how to connect.
- Uploading large files: multipart and resumable uploadsMultipart upload splits a large file into parts that are sent in parallel and retried on their own. See the Python walkthrough, how to resume, and common mistakes.