Body-parser Middleware in Node.js
Last Updated :
07 Jan, 2025
Body-parser is the Node.js body-parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it. It's commonly used in web applications built with Express.js to handle form submissions, JSON payloads, and other types of request bodies.
What is Body-parser?
body-parser is essential for handling incoming data in a variety of formats, such as JSON, URL-encoded form data, and raw or text data. It transforms this data into a readable format under req.body for easier processing in your application.
Features
- Handles different types of request payloads, including JSON, URL-encoded, raw, and text data.
- Simplifies the process of accessing request data, making it readily available under req.body.
- Works seamlessly with Express.js and other Node.js frameworks.
Body-parser is middleware used to parse incoming request bodies in a middleware before handlers.
Steps to Setup a body-parser Module
Step 1: First init the node app using the below command.
npm init -y
Step 2: You can visit the link to Install the body-parser module. You can install this package by using this command.
npm install body-parser express ejs
Step 2: After installing body-parser you can check your body-parser version in the command prompt using the command.
npm version body-parser
Project Structure:
Project Structure
The updated dependencies in your package.json file will look like this:
"dependencies":{
"body-parser": "^1.20.2",
"express": "^4.18.2",
"ejs": "^3.1.9"
}
Example: This code uses body-parser middleware in an Express.js application to parse URL-encoded and JSON request bodies, allowing access to form data via req.body.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Body-Parser Module Demo</title>
</head>
<body>
<h1>Demo Form</h1>
<form action="saveData" method="POST">
<pre>
Enter your Email : <input type="text"
name="email"> <br>
<input type="submit" value="Submit Form">
</pre>
</form>
</body>
</html>
JavaScript
// Filename - index.js
const bodyparser = require('body-parser')
const express = require("express")
const path = require('path')
const app = express()
let PORT = process.env.port || 3000
// View Engine Setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
// Body-parser middleware
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
app.get("/", function (req, res) {
res.render("SampleForm")
});
app.post('/saveData', (req, res) => {
console.log("Using Body-parser: ", req.body.email)
})
app.listen(PORT, function (error) {
if (error) throw error
console.log("Server created Successfully on PORT", PORT)
})
Run the index.js file using the below command:
node index.js
Now Open the browser and type the below URL and you will see the Demo Form as shown below:
http://localhost:3000/

Now submit the form and then you will see the following output:

But if we do not use this body-parser middle, then while parsing, an error will occur as shown below:

So this is how you can use the body-parser module for parsing incoming request bodies in middleware before you handle it.
Summary
body-parser is a powerful middleware in Node.js used for parsing incoming request bodies. Whether you're working with JSON, form data, or other content types, body-parser simplifies the process of accessing and handling this data. It is often used with express and is a core part of express which makes it easier to implement.
Similar Reads
Middlewares in Next.js
Middlewares in Next.js provide a powerful mechanism to execute custom code before a request is completed. They enable you to perform tasks such as authentication, logging, and request manipulation, enhancing the functionality and security of your application.Table of ContentMiddleware in Next.jsConv
7 min read
Purpose of middleware in Express
Middleware in Express is like a set of tools or helpers that helps in managing the process when your web server gets a request and sends a response. Mainly it's work is to make the Express framework more powerful and flexible. It allows users to insert additional steps or actions in the process of h
2 min read
Understanding Mongoose Middleware in Node.js
Mongoose is a powerful tool for Node.js developers working with MongoDB databases. It simplifies database interactions and allows developers to model data with schemas, perform CRUD operations, and more. One of Mongoose's most powerful features is its middleware system. In this article, we'll explai
7 min read
Explain the concept of middleware in NodeJS
Middleware in NodeJS refers to a software design pattern where functions are invoked sequentially in a pipeline to handle requests and responses in web applications. It acts as an intermediary layer between the client and the server, allowing for modularization of request processing logic and enabli
2 min read
How to use third-party middleware in Express JS?
Express JS is a robust web application framework of Node JS which has the capabilities to build web and mobile applications. Middleware is the integral part of the framework. By using the third party middleware we can add additional features in our application.PrerequisitesNode JSExpress JSPostmanTa
2 min read
Implementing Csurf Middleware in Node.js
Csurf middleware in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSR
4 min read
What is Middleware in Express.js ?
Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middlewa
2 min read
API Response Caching using apicache Middleware in Node.js
APIs are a crucial part of modern web applications, providing the means for different software systems to communicate and exchange data. However, frequent API calls, especially to the same endpoints, can lead to increased server load, slower response times, and higher bandwidth usage. Caching is a s
4 min read
Edge Functions and Middleware in Next JS
Next JS is a React-based full-stack framework developed by Vercel that enables functionalities like pre-rendering of web pages. Unlike traditional react apps where the entire app is loaded on the client. Next.js allows the web page to be rendered on the server, which is great for performance and SEO
3 min read
How to Build Middleware for Node JS: A Complete Guide
NodeJS is a powerful tool that is used for building high-performance web applications. It is used as a JavaScript on runtime environment at the server side. One of Its key features is middleware, which allows you to enhance the request and response object in your application.Building middleware for
5 min read