JSON, Forms, and File Uploads
Parsing Request Bodies
Express's built-in parsers cover JSON and form data; multer handles file uploads.
What you'll learn
- Parse JSON requests
- Parse form-encoded data
- Cap body size
Express doesn’t parse request bodies by default — you opt in with middleware.
JSON
app.use(express.json());
app.post("/api/users", (req, res) => {
console.log(req.body); // parsed JSON
res.status(201).json({ id: 42, ...req.body });
}); Send from a client:
curl -X POST http://localhost:3000/api/users \
-H "content-type: application/json" \
-d '{"name":"Ada","email":"ada@example.com"}' Form-Encoded
For traditional HTML form submissions:
app.use(express.urlencoded({ extended: true }));
app.post("/contact", (req, res) => {
console.log(req.body); // { name: 'Ada', message: '...' }
}); extended: true parses nested objects (a[b]=c) using qs.
Body Size Limits
By default Express caps at 100KB. Adjust:
app.use(express.json({ limit: "1mb" })); Why a limit? An attacker sending a 5GB JSON body would OOM your server. Always cap.
File Uploads
For multipart/form-data (file uploads), use multer:
npm install multer import multer from "multer";
const upload = multer({ dest: "./uploads/" });
app.post("/upload", upload.single("file"), (req, res) => {
console.log(req.file); // { path, originalname, size, mimetype }
res.json({ ok: true });
}); Always validate file size and mime type — never trust the client.
Raw Bodies
For webhooks where you need the raw bytes (signature verification):
app.use("/webhooks/stripe", express.raw({ type: "application/json" }), (req, res) => {
const sig = req.headers["stripe-signature"];
// verify(sig, req.body); req.body is a Buffer here
}); express.json() would consume the body — you’d lose the exact
bytes needed to verify the signature.