Difference between app.use(express.json()) and app.use(bodyParser.json())
When you working with Express.js you might see Both app.use(express.json()); and app.use(bodyParser.json()); in deferent sources.
app.use(express.json()); and app.use(bodyParser.json()); are used to parse incoming request bodies as JSON in Express.js, but there are a few differences between them.
express.json()
This is a build-in-method in Express.js after 4.16.0 version to parse JSON bodies. Prior to this version, Express used body-parser as a middleware to parse JSON. Since this is a built-in middleware, don’t need to install body-parser separately.
bodyParser.json()
This is a separate package that need to install. It’s a middleware used by older versions of Express before express.json() was added.
Main Differences
Functionality:
- Both
express.json()andbodyParser.json()provide the same functionality for parsing JSON bodies. express.json()is essentially a wrapper aroundbody-parser’sjson()function since Express started usingbody-parserinternally in version 4.16.0.
Built-in vs. External:
express.json()is built into Express 4.16.0 and later, so you don't need any additional package.bodyParser.json()requires you to install thebody-parserpackage separately.
Performance:
- Since
express.json()is built into Express, there is no overhead of an external package likebody-parser. It can be slightly more efficient if you're only using Express's JSON parsing.
Usage
bodyParser.json()
const bodyParser = require('body-parser');
app.use(bodyParser.json());express.json()
app.use(express.json());Conclusion:
- If you’re using Express 4.16.0 or later, it is recommended to use
express.json()since it is built-in and eliminates the need for an external dependency. - If you’re working with an older version of Express or if you’re already using
body-parserfor other purposes, you can continue usingbodyParser.json().
