loading...

Body Parser You probably don't need body-parser in your Express apps

taylorbeeston profile image Taylor Beeston ・1 min read

What is body-parser?

Often, when I see a blog post or article describing an Express.js server, it usually starts out with something similar to the following:

npm init -y
npm i express body-parser
Enter fullscreen mode Exit fullscreen mode

Followed by the classic

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());
// more express stuff
Enter fullscreen mode Exit fullscreen mode

I used to have these four lines of code in practically every Express app I've ever made!

However, a few weeks ago I was poring over the Express Docs and noticed that as of version 4.16.0 (which came out three years ago!), Express basically comes with body-parser out of the box!

How do I use the Express version?

Well, you can pretty much just search bodyParser, and replace it with express!

This means our four lines of code above can be refactored into the following three lines of code:

const express = require('express');

const app = express();
app.use(express.json());
Enter fullscreen mode Exit fullscreen mode

If you are using Babel (which I would highly recommend!), you can even use a named import to make the code even more concise:

import express, { json } from 'express';

const app = express();
app.use(json());
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide
Collapse
tobiassn profile image
Tobias SN

Express also has built-in middleware for raw data (express.raw) and text (express.text) since 4.17.0.

Collapse
taylorbeeston profile image
Taylor Beeston Author

That is true! They've also got express.urlencoded,

Collapse
jaterlwj profile image
Jater Loh

Hi, thanks for sharing! I was not aware that express ships with bodyParser now, I have to give this a try. In regards to named imports, it does make the code more concise. But I think it may be a tad confusing to have a function named json.

Collapse
taylorbeeston profile image
Taylor Beeston Author

At first I thought it would be weird too, but I've found that only using it on routes that actually need to parse json actually doesn't look so bad. For example

import { Router, json } from 'express';

const router = Router();

router.route('/').get((_, response) => {
  return response.status(200).send("No parsing needed here");
});

router.route('/').post(json(), (request, response) => {
  return response.status(200).json(request.body);
});

export default router;

It might still be better to just use express.json or to rename it to something like jsonMiddleware though

Collapse
technolaaji profile image
Mohamad Kalaaji

It has been there for quite some time 🙃 body parser became part of express

You can use both, they perform the exact same job but one thing you need to keep in mind that if there is an issue with the express build in body parser then you have to update express as whole, as for the independent body parser package if there is an issue with it then you have to update that package only

Collapse
taylorbeeston profile image
Taylor Beeston Author

That is a good point that I hadn't thought of. Though at least mostly in my limited experience, express upgrades have been pretty painless

Collapse
halasproject profile image
Salah Bentayeb

it proves that the majority prefer to follow the tutorials than to read the documentation ... I am part of the majority 👀, I just learned this technique thanks for sharing 🙏

Collapse
taylorbeeston profile image
Collapse
dayesouza profile image
Day Souza

That's so cool! I just tested it, thanks!

Collapse
taylorbeeston profile image
Taylor Beeston Author

No problem! Glad you found it useful!

Collapse
gabuardi profile image
Josué Gabuardi

Now read the NPM documentation... since now you don't need Babel... you only need the attribute type: module in your package.json and node.js will use ESM imports by default.

Collapse
sumanthyedoti profile image
Sumanth Yedoti

I think, express.json() is to parse header body which is json. Body parser is also to parse form data. Please correct me if im wrong.

Collapse
taylorbeeston profile image
Taylor Beeston Author

As per the Express docs

This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

Returns middleware that only parses JSON and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body), or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.

Collapse
goudekettingrm profile image
Robin Goudeketting

What I understood is that the parser in express is actually the same one, since they always are used together, they just integrated it.

Collapse
jaynwosu profile image
Jerry Nwosu

Thanks. This was helpful.

Collapse
ste profile image
Ste

Amazing! Didn’t know this! Thank you :)

Collapse
icyjoseph profile image
Joseph

It's good to remember that the body parsing was added, removed and then added again stackoverflow.com/a/47232318