Conditionally apply middleware by request property
knowing helpers and the type option exist.
use express.text({ type: 'application/xml' }) or a guard wrapper that checks req.is() then calls the parser or next().
WHAT THIS TESTS This checks whether you know Express middleware can be applied conditionally in a declarative way, keeping the conditional logic out of the parser itself.
A GOOD ANSWER COVERS Two clean approaches. First, the built-in body parsers accept a type option that controls which Content-Type they activate for; express.text({ type: 'application/xml' }) only parses requests whose Content-Type is application/xml and is a no-op otherwise, so the matching logic lives in configuration, not your code. You then hand the captured body to an XML parsing library. Second, write a tiny dispatcher middleware that uses req.is('application/xml') to decide whether to invoke the XML parser or simply call next(); this keeps the condition outside the parser. A third option is a helper library such as express-conditional-middleware that wraps any middleware with a predicate. The theme is composition over baking the check into the parser.
COMMON WRONG ANSWERS Putting an if (req.headers['content-type'] === ...) check inside the parser body, which the question explicitly rules out. Applying the XML parser globally so it runs on JSON and form requests too. Forgetting req.is() exists and doing brittle manual string matching that ignores charset parameters.
LIKELY FOLLOW-UPS What does req.is() return and how does it handle parameters like charset? How would you route to different parsers for JSON, XML, and form data? Why is configuration-driven matching more maintainable?
ONE CONCRETE EXAMPLE app.use(express.text({ type: 'application/xml' })); app.use((req, res, next) => { if (req.is('application/xml')) req.parsedXml = parseXml(req.body); next(); }); Or a dispatcher: const xmlOnly = (mw) => (req, res, next) => req.is('application/xml') ? mw(req, res, next) : next(); app.use(xmlOnly(myXmlParser)); Both keep the Content-Type decision outside the parser, so the parser stays focused and other content types pass through untouched.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.