
Creating Your Own ExpressJS from Scratch (Part 6) – Creating a Body-Parser Middleware
Welcome back! In this sixth part of our custom ExpressJS clone series, we'll implement one of the most important middleware components of any modern web server: the body-parser.
This middleware allows your application to parse incoming request bodies — like JSON and form data — and access them as JavaScript objects via req.body
.
🧠 Why You Need a Body-Parser Middleware
By default, Node.js does not parse the body of incoming HTTP requests. That means if a client sends form data or JSON, you’ll only receive it as a stream of bytes.
A body-parser middleware helps:
- Convert the incoming stream into usable text
- Parse that text into a JavaScript object (e.g., from JSON or
application/x-www-form-urlencoded
) - Attach the parsed object to
req.body
so you can access it in your controllers
🛠️ Implementing the Middleware
src/body-parser.js
const BodyParser = async (req, res, next) => {
let body = [];
for await (const chunk of req) {
body.push(chunk);
}
body = Buffer.concat(body).toString();
if (req.headers['content-type'] === 'application/json') {
req.body = JSON.parse(body);
} else if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
const params = new URLSearchParams(body);
req.body = Object.fromEntries(params.entries());
}
next();
};
module.exports = BodyParser;
🔍 What’s Happening Here?
Reading the Stream
- We collect all the chunks of the request body into an array.
Buffer Concatenation
- Convert the chunks into a complete string using
Buffer.concat
.
- Convert the chunks into a complete string using
Content-Type Parsing
- If it's
application/json
, weJSON.parse()
the string. - If it's
application/x-www-form-urlencoded
, we useURLSearchParams
to parse the form data.
- If it's
After parsing, we attach the resulting object to req.body
.
🧪 Using the Middleware
index.js
const App = require('./src/app');
const BodyParser = require('./src/body-parser');
const app = App();
app.useAll(BodyParser);
app.post('/body-parser', (req, res) => {
res.send(`name: ${req.body.name}, age: ${req.body.age}`);
});
const start = async () => {
app.run(3000);
};
start();
🚀 Testing the Middleware
Request
POST /body-parser
Content-Type: application/json
{
"name": "Wesley Miranda",
"age": 28
}
Response
name: Wesley Miranda, age: 28
You can also test with form data using x-www-form-urlencoded
.
📦 What’s Next?
In the upcoming tutorials, we’ll implement:
- ✅ CORS Middleware
- ✅ Multer-style file upload Middleware
We’re getting closer to building a production-grade framework from scratch!
Thanks for following along! 💡