Request parsing and validation
Framework lane: Express 5.x (Supertest required for integration test). Exact supported patch, dependency lock, advisory review and execution are NOT RUN. The framework code is a static candidate; do not install dependencies or expose a server automatically. The local companion uses Node.js 22.16.0 and requires no third-party packages.
Framework example — staged
import express from 'express';const app = express();app.use(express.json({ limit: '2kb' }));app.post('/orders', (req, res) => { if (!req.is('application/json')) return res.sendStatus(415); const quantity = req.body?.quantity; if (!Number.isInteger(quantity) || quantity < 1 || quantity > 20) { return res.status(400).json({ code: 'INVALID_QUANTITY' }); } res.status(201).json({ quantity });});export default app;Expected behavior (not observed): A JSON object with quantity 3 returns 201 and {"quantity":3}; quantity "3" returns 400. A non-JSON content type returns 415. This is a response-only example, not durable order creation.
How it works
Express JSON middleware applies to matching content types and can enforce a byte limit. req.body remains untrusted and may be absent. Reject unexpected types and ranges before using data. In this example quantity is an integer from 1 through 20, and only that field is copied into the response. A JSON parser is not an authorization or domain validation mechanism.
Practice the underlying idea without dependencies
function validQuantity(value) { return Number.isInteger(value) && value >= 1 && value <= 20;}console.log(JSON.stringify([1,20,0,21,'3',2.5,null].map(validQuantity)));Run node main.mjs in a disposable directory. Expected output:
[true,true,false,false,false,false,false]This tests the illustrated JavaScript behavior only, not the framework.
Common mistake
Using Number(value) without an explicit coercion policy accepts strings and some surprising values. Validate types first; do not spread the entire untrusted request body into stored objects.
Apply it yourself
Design a validator for an order with quantity and a short product identifier; test missing, fractional, and oversized quantities.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Request parsing and validation — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
Why is quantity "3" rejected?
What does the JSON limit constrain?
Which response fits an unsupported request content type?