Every Node.js backend eventually needs a file upload endpoint. And every time, the same questions come back:
- How do I stop someone from uploading a 5 GB file, or 10,000 tiny ones?
- How do I make sure
../../etc/passwdnever ends up as a filename on my disk? - Why does moving from local disk to S3 (or Azure) mean rewriting my routes?
- Why does my "simple upload" pull in a tree of transitive dependencies?
I built @xkid1/multipart to answer those once. It's a multipart/form-data parser written in TypeScript with zero runtime dependencies, Express and NestJS middleware, and storage adapters for the local filesystem, AWS S3 and Azure Blob Storage, all behind one interface.
This post walks through how it works and how to use it.
Install
npm install @xkid1/multipart
You only install the SDKs for the pieces you use:
| You use | Also install |
|---|---|
| Core parser / local | nothing |
| Express | express |
| NestJS |
@nestjs/common reflect-metadata rxjs
|
| AWS S3 | @aws-sdk/client-s3 |
| Azure Blob Storage | @azure/storage-blob |
Express, NestJS and the cloud SDKs are optional peer dependencies. If you only use S3, the Azure SDK never shows up in your node_modules.
Express: typed req.files in a few lines
import express from 'express';
import { multipartExpress } from '@xkid1/multipart/middleware/express';
const app = express();
app.post(
'/avatar',
multipartExpress({
maxFiles: 1,
fileSize: 5 * 1024 * 1024, // 5 MiB
allowedMimeTypes: ['image/*'],
}),
(req, res) => {
if (req.multipartError) {
return res.status(req.multipartError.statusCode).json({ error: req.multipartError });
}
const avatar = req.files?.avatar; // FileData | FileData[] | undefined
const name = req.fields?.name; // string | string[] | undefined
res.json({ name, received: avatar !== undefined });
},
);
A few things are happening here:
-
req.filesandreq.fieldsare typed. Noany, no casting. - Requests that aren't
multipart/form-datapass straight through. - Repeated field names (
tags=a&tags=b) become arrays automatically. - Errors don't throw into the void. They're attached to
req.multipartErrorwith a ready-to-use HTTPstatusCode, so your handler decides how to respond.
If you prefer centralized Express error middleware:
import { multipartErrorHandler, multipartExpress } from '@xkid1/multipart/middleware/express';
app.post('/upload', multipartExpress({ onError: 'next' }), handler);
app.use(multipartErrorHandler); // responds with error.statusCode and { error }
NestJS: apply it like any other middleware
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { createMultipartNestjs, MultipartNestjs } from '@xkid1/multipart/middleware/nestjs';
@Module({ controllers: [UploadController] })
export class UploadModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
// default limits
consumer.apply(MultipartNestjs).forRoutes('upload');
// custom limits for one route
consumer
.apply(createMultipartNestjs({ maxFiles: 1, allowedMimeTypes: ['application/pdf'] }))
.forRoutes('documents');
}
}
In your controller, read req.files and req.fields through @Req(). Failures reach Nest as a regular HttpException (400, 413 or 415) with a body like { statusCode, message, error: 'LIMIT_FILE_SIZE' }, so your existing exception filters keep working.
One gotcha worth knowing:
consumer.apply(new MultipartNestjs())(an instance) is silently ignored by Nest. Pass the class, or usecreateMultipartNestjs().
Safe by default
Upload endpoints are one of the easiest places to get hurt, so limits are on before you configure anything:
| Option | Default | What it limits |
|---|---|---|
maxSize |
100 MiB | the whole request body |
fileSize |
50 MiB | each file |
fieldSize |
10 MiB | each text field |
maxFiles |
100 | number of files |
maxFields |
1000 | number of text fields |
allowedMimeTypes |
all | file types, with wildcards like image/*
|
maxSize is enforced while the body streams in: the request is rejected as soon as it crosses the limit, not after the whole thing has arrived.
Other protections you get without thinking about them:
-
No prototype pollution from field names like
__proto__. - Path-traversal-proof storage: client filenames are reduced to a safe basename before touching the disk.
-
Byte-exact files: parsing is verified against Node's own
FormDataencoder, so what the client sent is exactly what you get. -
UTF-8 filenames sent via
filename*=are decoded correctly.
Every error is a MultiPartError with a stable code, which makes them easy to branch on:
import { MultiPartError, MultiPartErrorCode } from '@xkid1/multipart';
if (error instanceof MultiPartError && error.code === MultiPartErrorCode.LIMIT_FILES) {
// tell the user they sent too many files
}
One storage interface: local, S3, Azure
This is the part I wanted most. Every storage provider implements the same StorageAdapter interface (upload, uploadMany, delete, exists). Your route code talks to the interface; which backend sits behind it is a config decision.
Local disk
import { LocalStorage } from '@xkid1/multipart/storage/local';
const storage = new LocalStorage({ directory: './uploads', prefix: 'avatars' });
const saved = await storage.upload(file);
saved.path; // 'avatars/me.png'
saved.absolutePath; // '/srv/app/uploads/avatars/me.png'
Existing files are never silently overwritten: a second me.png becomes me-1.png. Opt in with overwrite: true, or use preserveFilename: false for generated unique names.
AWS S3
import { S3Client } from '@aws-sdk/client-s3';
import { S3Storage } from '@xkid1/multipart/storage/s3';
const storage = new S3Storage(new S3Client({ region: 'eu-west-1' }), {
bucket: 'my-bucket',
region: 'eu-west-1',
prefix: 'uploads/',
serverSideEncryption: 'AES256',
});
const { key, url, etag } = await storage.upload(file);
const signedUrl = await storage.getUrl(key, 3600); // needs @aws-sdk/s3-request-presigner
ContentType is set on the object, and the original (UTF-8) filename is kept in ContentDisposition, so downloads come back with the right name.
Azure Blob Storage
import { BlobServiceClient } from '@azure/storage-blob';
import { AzureBlobStorage } from '@xkid1/multipart/storage/azure';
const container = BlobServiceClient
.fromConnectionString(process.env.AZURE_STORAGE_CONNECTION_STRING!)
.getContainerClient('uploads');
const storage = new AzureBlobStorage(container, {
accountName: 'myaccount',
container: 'uploads',
prefix: 'files/',
tier: 'Hot',
});
const { name, uri } = await storage.upload(file);
Swapping backends
Because they share an interface, you can pick the backend at startup:
import type { StorageAdapter } from '@xkid1/multipart';
const storage: StorageAdapter =
process.env.NODE_ENV === 'production'
? new S3Storage(s3Client, { bucket: 'prod-uploads', region: 'eu-west-1' })
: new LocalStorage({ directory: './uploads' });
Local disk in development, S3 in production, and the route handlers don't change.
No framework? Also fine
The core parser works on a plain Buffer:
import { extractBoundary, parseMultipartWithDuplicates } from '@xkid1/multipart';
const boundary = extractBoundary(request.headers['content-type']);
const data = parseMultipartWithDuplicates(body, boundary!, { maxFiles: 10 });
// { title: 'Hello', tags: ['a', 'b'], doc: { name, mimeType, size, extension, buffer, ... } }
Tested the way you'll use it
Unit tests are good, but they don't tell you whether the published package works in your setup. So every pull request packs the npm tarball and installs it like an end user would, then runs it against:
- Node.js 18, 20, 22, 24 and 26 (npm and pnpm)
- Express 4 and 5, NestJS 11
- ESM and CommonJS, with TypeScript
node16,bundlerandnode10resolution - S3 and Azure emulators (S3Mock and Azurite)
CodeQL and the OpenSSF Scorecard run on the repo too.
Honest limitations
I'd rather you know these up front:
-
Request bodies are buffered in memory (up to
maxSize) before parsing. The size limit is enforced during upload, but files are not streamed straight to storage. For multi-gigabyte uploads, lowermaxSizeor use a streaming parser. - File buffers are zero-copy views into the request body. If you keep a
FileDataaround long-term, copy it withBuffer.from(file.buffer)so the whole body can be garbage-collected. - The NestJS middleware targets the Express platform (not Fastify).
For typical uploads like avatars, documents and images, these trade-offs keep the library small and predictable.
Try it
npm install @xkid1/multipart
- GitHub: github.com/xkid1/multipart
- npm: @xkid1/multipart
If you try it, I'd love to hear what works and what doesn't. Issues and PRs are welcome, and a ⭐ on GitHub helps other developers find it.
If it saves you time, you can also support development via GitHub Sponsors or Buy Me a Coffee. Thanks for reading!
Top comments (0)