Koa2 Formidable Middleware
raw JSON →koa2-formidable is a Koa 2 middleware designed to parse multipart/form-data requests, primarily for file uploads and complex form submissions. It acts as a wrapper around the popular `formidable` library, simplifying its integration into Koa applications. The package is currently at version 1.0.3 and has not seen any updates or releases in over five years, indicating it is no longer actively maintained. This contrasts sharply with the underlying `formidable` library, which is actively developed and has moved to major versions 3 and 4, introducing ESM support, modern Node.js stream compatibility, and crucial security updates. As such, `koa2-formidable` relies on an outdated version of `formidable`, making it unsuitable for modern Koa projects due to potential security vulnerabilities, lack of current features, and compatibility issues with newer Node.js runtimes.
Common errors
error WARN deprecated formidable@1.x.x: Please upgrade to latest, formidable@v2 or formidable@v3! Check these notes: https://bit.ly/2ZEqIau ↓
koa2-formidable itself. The only resolution is to replace koa2-formidable with an actively maintained Koa body parsing middleware that uses a current version of formidable (v3+) or an alternative parser. Consider koa-body or @koa/body. error TypeError: require is not a function ↓
.js file without "type": "module" in package.json). Alternatively, if your project is ESM, you must use dynamic import(): const formidable = await import('koa2-formidable');, though this is generally not recommended for middleware due to its asynchronous nature. error Error: Max fields size exceeded. (or similar errors related to request size limits) ↓
maxFieldsSize and maxFileSize options correctly to the formidable middleware. For example: app.use(formidable({ maxFieldsSize: 20 * 1024 * 1024, maxFileSize: 200 * 1024 * 1024 })); (for 20MB fields and 200MB files). If problems persist, this may indicate a limitation of the old formidable version, requiring migration to a modern alternative. Warnings
breaking The package `koa2-formidable` has not been updated in over five years and relies on a significantly outdated version of `formidable`. This older `formidable` version is deprecated and known to contain security vulnerabilities if not implemented with extreme care, and it lacks features present in modern `formidable` (v3+). ↓
gotcha `koa2-formidable` is a CommonJS-only package. It cannot be directly `import`ed in an ESM-first Node.js project without specific configuration or a build step, which adds unnecessary complexity to modern applications. ↓
gotcha Given its abandoned status, `koa2-formidable` will not receive bug fixes, performance improvements, or compatibility updates for newer Node.js versions or Koa releases. This can lead to runtime errors or unexpected behavior as the ecosystem evolves. ↓
gotcha The `formidable` options passed to `koa2-formidable` might not fully expose or correctly configure all modern `formidable` features, especially those introduced in `formidable` v2 or v3, leading to limitations in how file uploads and fields can be handled (e.g., streaming to cloud storage, advanced progress tracking). ↓
Install
npm install koa2-formidable yarn add koa2-formidable pnpm add koa2-formidable Imports
- formidable
const formidable = require('koa2-formidable');
Quickstart
const Koa = require('koa');
const Router = require('@koa/router');
const formidable = require('koa2-formidable');
const path = require('path');
const fs = require('fs');
const app = new Koa();
const router = new Router();
// Apply koa2-formidable middleware with custom options for formidable
// Ensure the upload directory exists
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
app.use(formidable({
uploadDir: uploadDir,
keepExtensions: true,
multiples: true
}));
router.post('/upload', async (ctx, next) => {
// Access parsed fields and files from ctx.request
const { body, files } = ctx.request;
console.log('Received fields:', body);
console.log('Received files:', files);
let fileInfo = {};
if (files) {
if (Array.isArray(files.uploadFile)) {
fileInfo = files.uploadFile.map(f => ({ name: f.name, path: f.path, size: f.size }));
} else if (files.uploadFile) {
fileInfo = { name: files.uploadFile.name, path: files.uploadFile.path, size: files.uploadFile.size };
}
}
ctx.body = {
message: 'File upload successful!',
fields: body,
files: fileInfo
};
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
console.log('Koa server listening on http://localhost:3000');
console.log('Use a tool like Postman or curl to POST multipart/form-data to /upload.');
console.log('Example: curl -X POST -F "username=test" -F "uploadFile=@./some-file.txt" http://localhost:3000/upload');
});