{"id":17767,"library":"koa-xml-body","title":"Koa XML Body Parser Middleware","description":"koa-xml-body is a Koa middleware designed to parse XML request bodies, making the parsed data available on `ctx.request.body`. The current stable version is 3.0.0, published approximately 3 years ago, which is compatible with Koa 2.x and 3.x, while Koa 1.x users should opt for `koa-xml-body@1.x`. It internally uses `xml2js` for the actual XML parsing, exposing its configuration options via the `xmlOptions` property. Key differentiators include its explicit focus on XML content types (e.g., `application/xml`, `text/xml`), robust error handling customization through an `onerror` callback, and seamless integration with other body parsers by carefully managing `ctx.request.body`. Its release cadence is generally tied to bug fixes or Koa compatibility updates rather than rapid feature additions, suggesting a maintenance-oriented status.","status":"maintenance","version":"3.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/creeperyang/koa-xml-body","tags":["javascript","xml","body","bodyParser","koa","middleware","xml2js","xml parser"],"install":[{"cmd":"npm install koa-xml-body","lang":"bash","label":"npm"},{"cmd":"yarn add koa-xml-body","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-xml-body","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency, required for the middleware to function within a Koa application.","package":"koa","optional":false},{"reason":"Internal dependency for core XML parsing functionality. Its options are exposed via `xmlOptions`.","package":"xml2js","optional":false}],"imports":[{"note":"The primary export is a default function, not a named one. Used for modern ESM Koa applications.","wrong":"import { koaXmlBody } from 'koa-xml-body'; // Not a named export for the default function","symbol":"koaXmlBody","correct":"import koaXmlBody from 'koa-xml-body';"},{"note":"CommonJS `require` syntax as demonstrated in the package's documentation, suitable for Node.js environments without ESM.","wrong":"import xmlParser from 'koa-xml-body'; // Incorrect for CommonJS environments, use require()","symbol":"xmlParser","correct":"const xmlParser = require('koa-xml-body');"},{"note":"The middleware is configured by calling the imported function with an options object. This applies to both CommonJS and ESM usage.","wrong":"app.use(require('koa-xml-body', { limit: '5mb' })); // Options are passed as an argument to the function, not as a second argument to require","symbol":"koaXmlBodyWithOptions","correct":"import koaXmlBody from 'koa-xml-body';\napp.use(koaXmlBody({ limit: '5mb', xmlOptions: { explicitArray: false } }));"}],"quickstart":{"code":"import Koa from 'koa';\nimport koaXmlBody from 'koa-xml-body';\n\nconst app = new Koa();\n\n// Apply the XML body parser middleware with custom options\napp.use(koaXmlBody({\n  limit: '2mb', // Set a higher limit if expecting larger XML payloads\n  encoding: 'utf8', // Ensure correct encoding is used\n  xmlOptions: {\n    explicitArray: false, // Prevents single child elements from being wrapped in arrays\n    ignoreAttrs: true, // Ignores XML attributes and only parses element values\n  },\n  key: 'parsedXml', // Store parsed XML in ctx.request.parsedXml instead of ctx.request.body\n  onerror: (err, ctx) => {\n    console.error('XML parsing error:', err.message);\n    ctx.status = 400;\n    ctx.body = 'Invalid XML format.';\n  },\n}));\n\napp.use(async (ctx) => {\n  if (ctx.method === 'POST' && ctx.is('application/xml')) {\n    // Access the parsed XML body based on the 'key' option\n    const xmlData = ctx.request.parsedXml;\n    if (xmlData) {\n      console.log('Received XML:', JSON.stringify(xmlData, null, 2));\n      ctx.body = { status: 'success', received: xmlData };\n    } else {\n      ctx.status = 400;\n      ctx.body = { status: 'error', message: 'No XML body received or parsed.' };\n    }\n  } else {\n    ctx.body = 'Send an XML POST request to this endpoint.';\n  }\n});\n\nconst port = 3000;\napp.listen(port, () => {\n  console.log(`Koa server listening on http://localhost:${port}`);\n});\n\n// Example usage with curl:\n// curl -X POST -H \"Content-Type: application/xml\" -d '<root><item id=\"1\">Value1</item><item id=\"2\">Value2</item></root>' http://localhost:3000\n","lang":"typescript","description":"This quickstart demonstrates setting up a Koa server with `koa-xml-body` to parse incoming XML requests. It includes custom options for body size limit, XML parsing behavior (e.g., `explicitArray`, `ignoreAttrs`), a custom request key, and an error handler for invalid XML, making it robust for production use."},"warnings":[{"fix":"Upgrade Koa to version 2.x or 3.x, or explicitly install `koa-xml-body@1.x` if tied to Koa 1.x.","message":"Version 3.x of `koa-xml-body` is designed for Koa 2.x and newer. Users on Koa 1.x must use `koa-xml-body@1.x` to maintain compatibility and avoid runtime errors.","severity":"breaking","affected_versions":"<2.0"},{"fix":"Always provide a custom `onerror` function in the middleware options to gracefully handle parsing errors, e.g., `onerror: (err, ctx) => { ctx.status = 400; ctx.body = 'Bad Request: Invalid XML'; }`.","message":"By default, `koa-xml-body` will throw an error if XML parsing fails and no `onerror` option is provided. This can lead to unhandled exceptions and server crashes in production environments.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Configure the `limit` option in the middleware to a higher value if needed, e.g., `app.use(xmlParser({ limit: '5mb' }))`. Ensure your server resources can handle the increased payload size.","message":"The default `limit` for the XML body size is 1MB. Requests exceeding this limit will result in a `413 Payload Too Large` error, which might be insufficient for applications handling large XML documents.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Place `koa-xml-body` before other generic body parsers if it's meant to be the primary handler for XML. The library is designed to co-exist, so ensure the content-type allows `koa-xml-body` to process first.","message":"When integrating `koa-xml-body` with other generic body parsers (like `koa-bodyparser` or `koa-body`), the order of middleware matters. `koa-xml-body` should generally be placed before other body parsers if you specifically want it to handle XML, but it is designed to integrate well, carefully checking `ctx.request.body`.","severity":"gotcha","affected_versions":">=1.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Increase the `limit` option when initializing the middleware: `app.use(xmlParser({ limit: '5mb' }))` to accommodate larger XML payloads.","cause":"The incoming XML request body size exceeds the configured `limit` option in `koa-xml-body` (defaulting to 1MB).","error":"HTTP Status 413: Payload Too Large"},{"fix":"Ensure the client sends well-formed XML without any leading non-whitespace characters. If the issue persists, review the `content-type` header to confirm it is `application/xml` or `text/xml`.","cause":"The request body is not valid XML or contains characters before the XML declaration/root element. This error originates from the underlying `xml2js` parser.","error":"Error: Non-whitespace before first tag."},{"fix":"Verify that the request's `Content-Type` header is set to `application/xml` or `text/xml`. Check for preceding body parsing middleware that might have already consumed or processed the request stream. Add a `console.log(ctx.request.body)` to debug when it becomes `undefined`.","cause":"This error typically occurs if `ctx.request.body` is accessed, but `koa-xml-body` either didn't parse a body (e.g., wrong `Content-Type`), or another middleware overwrote it, or parsing failed without a custom `onerror`.","error":"TypeError: Cannot read properties of undefined (reading 'body')"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}