Koa2 Formidable Middleware

raw JSON →
1.0.3 verified Thu Apr 23 auth: no javascript abandoned

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.

error WARN deprecated formidable@1.x.x: Please upgrade to latest, formidable@v2 or formidable@v3! Check these notes: https://bit.ly/2ZEqIau
cause This warning appears because `koa2-formidable` depends on a very old and deprecated version of the `formidable` library, which is no longer maintained and has known security vulnerabilities.
fix
This warning cannot be fixed within 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
cause Attempting to `require('koa2-formidable')` in an ECMAScript Module (ESM) context (e.g., in a file with `"type": "module"` in `package.json` or a `.mjs` file). This package is CommonJS-only.
fix
Ensure your file is treated as a CommonJS module (e.g., a .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)
cause The default `maxFieldsSize` (or `maxFileSize`) of the outdated `formidable` version used by `koa2-formidable` is too low for your application's needs, or the options are not being correctly applied.
fix
Ensure you are passing the 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.
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+).
fix Migrate to actively maintained Koa body parsing middleware like `@koa/body` or `koa-body`, which use up-to-date versions of `formidable` or other robust parsers. If direct `formidable` integration is preferred, use the `formidable` library directly with careful implementation, passing `ctx.req` (Node.js Request) to `formidable`'s `parse` method.
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.
fix For new projects or existing ESM projects, prefer middlewares that offer native ESM support. If forced to use, integrate via `import pkg = require('pkg')` in TypeScript or dynamic `import()` in JavaScript, though this is generally discouraged for middleware.
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.
fix Avoid using this package in production. If currently in use, plan for migration to an actively maintained alternative to ensure stability, security, and long-term compatibility.
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).
fix For fine-grained control over `formidable`'s capabilities, consider using the `formidable` library directly within your Koa routes. This allows direct access to `formidable`'s `IncomingForm` instance and its full API.
npm install koa2-formidable
yarn add koa2-formidable
pnpm add koa2-formidable

This quickstart demonstrates how to set up `koa2-formidable` in a Koa application to handle multipart/form-data uploads, including file and field parsing, and how to access the processed data via `ctx.request.body` and `ctx.request.files`.

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');
});