Express XML Body Parser
`body-parser-xml` is an Express.js middleware that extends the widely used `body-parser` library, enabling applications to seamlessly parse incoming XML-formatted request bodies into JavaScript objects. Currently at stable version 2.0.5, this package integrates an `xml` method directly onto the `body-parser` object, allowing developers to handle XML APIs while working with familiar JSON-like structures. Its release cadence reflects active maintenance, with recent updates addressing Node.js version compatibility (supporting Node 10 and above) and critical security vulnerabilities, including prototype pollution and `xml2js` dependency issues. A key differentiator is its straightforward integration model, piggybacking on `body-parser`'s established middleware pattern and providing extensive options for XML parsing via the underlying `xml2js` library, such as `normalize` and `explicitArray`. This approach simplifies the handling of diverse XML content types in Express applications.
Common errors
-
TypeError: bodyParser.xml is not a function
cause The `body-parser` object was not correctly extended by `body-parser-xml`.fixEnsure you have called `require('body-parser-xml')(bodyParser);` (or `bodyParserXml(bodyParser);` in ESM) after requiring `body-parser`. -
Error: request entity too large
cause The incoming XML request body exceeded the configured `limit` option.fixIncrease the `limit` option in `bodyParser.xml({ limit: '5MB' })` or adjust the client payload size. Default limit is '100kb'. -
XML parse error: Non-whitespace characters not allowed in prolog
cause The incoming request body is not valid XML, or the `Content-Type` header is incorrect, causing the parser to attempt to parse non-XML data as XML.fixVerify that the client is sending well-formed XML and that the `Content-Type` header (e.g., `application/xml`, `text/xml`) is set correctly. If using a custom type, configure the `type` option in `bodyParser.xml({ type: 'application/x-my-xml' })`.
Warnings
- breaking Version 2.0.0 removed official support for Node.js versions older than 10. Users on older Node.js environments must upgrade their runtime or remain on `body-parser-xml` v1.x.
- breaking A prototype pollution vulnerability (CVE-2022-25927) was present in versions prior to 2.0.3, allowing attackers to inject arbitrary properties into JavaScript object prototypes. This could lead to various security risks, including remote code execution or denial of service.
- breaking A reported vulnerability in the `xml2js` dependency (issue #663) affected `body-parser-xml` versions prior to 2.0.4. While specific details might vary, it indicates potential risks related to XML parsing.
- gotcha Unlike typical middleware that are directly imported and used, `body-parser-xml` functions as an enhancer. You must pass an initialized `body-parser` object to the `body-parser-xml` module to add the `.xml()` method, rather than directly using `body-parser-xml` as middleware.
Install
-
npm install body-parser-xml -
yarn add body-parser-xml -
pnpm add body-parser-xml
Imports
- body-parser-xml initialization (CommonJS)
const bodyParserXml = require('body-parser-xml');const bodyParser = require('body-parser'); require('body-parser-xml')(bodyParser); - body-parser-xml initialization (ESM)
import { xml } from 'body-parser-xml';import bodyParser from 'body-parser'; import bodyParserXml from 'body-parser-xml'; bodyParserXml(bodyParser);
- bodyParser.xml middleware
app.use(require('body-parser-xml'));app.use(bodyParser.xml({ limit: '1MB' }));
Quickstart
const express = require('express');
const bodyParser = require('body-parser');
// Initialize body-parser-xml to extend body-parser
require('body-parser-xml')(bodyParser);
const app = express();
// Use the XML middleware
// It parses application/xml, text/xml, and +xml content types by default
app.use(
bodyParser.xml({
limit: '1MB', // Reject payload bigger than 1 MB
xmlParseOptions: {
normalize: true, // Trim whitespace inside text nodes
explicitArray: false, // Prevents elements with a single child from being an array
},
})
);
// Define a route to handle XML POST requests
app.post('/xml-data', (req, res) => {
if (!req.body) {
return res.status(400).send('No XML body received.');
}
console.log('Received XML data:', JSON.stringify(req.body, null, 2));
res.json({ message: 'XML data received and parsed', data: req.body });
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
console.log('Send a POST request with Content-Type: application/xml to http://localhost:3000/xml-data');
console.log('Example cURL:');
console.log(`curl -X POST -H "Content-Type: application/xml" -d '<root><item>Hello</item><value>123</value></root>' http://localhost:3000/xml-data`);
});