Body Parser You probably don’t need body-parser in your Express apps
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