How to Fix Express req.body Undefined
In this tutorial, you'll learn about How to Fix Express req.body Undefined. We cover key concepts, practical examples, and best practices.
The Problem
Express req.body is undefined when handling POST, PUT, or PATCH requests because the built-in body parsing middleware is not configured.
Quick Fix
Step 1: Add express.json() middleware
Without JSON body parser, req.body is undefined:
const express = require('express');
const app = express();
app.post('/api/users', (req, res) => {
console.log(req.body); // undefined
res.json({ received: req.body });
});
Add JSON parsing middleware:
app.use(express.json());
app.post('/api/users', (req, res) => {
console.log(req.body);
res.json({ received: req.body });
});
Step 2: Add URL-encoded body parser
For form submissions:
app.use(express.urlencoded({ extended: true }));
extended: true uses the qs library for nested object support. extended: false uses query-string for simpler parsing.
Step 3: Check Content-Type header
The client must send the correct Content-Type:
// For JSON
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice' })
});
// For form data
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'name=Alice'
});
Step 4: Verify middleware order
Body parsers must be registered before routes:
// WRONG: route before parser
app.post('/api/users', handler);
app.use(express.json());
Correct order:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.post('/api/users', handler);
Step 5: Check for body size limits
The default body size limit is 100kb. For larger payloads:
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
Prevention
- Add
<a href="/backend/nodejs/">express</a>.json()and<a href="/backend/nodejs/">express</a>.urlencoded()early in the middleware stack. - Register body parsers before all route handlers.
- Verify the client sends the correct
Content-Typeheader. - Use a linter or template that includes body parsers by default.
- Test with
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' http://localhost:3000/api.
Common Mistakes with body parser
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world NODE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro