Xerri
Xerri

Reputation: 5046

Using express.json instead of express.bodyparser

I'm building a simple REST API and I only want to accept JSON input.

I am opting to use app.use(express.json({strict: true})); instead of app.use(express.bodyParser());.

I am passing strict: true thinking that that would add a layer of security against invalid json. Anyone else doing anything similar? Looking for suggestions from someone who was experience with this setup.

Upvotes: 5

Views: 6995

Answers (1)

Dan Kohn
Dan Kohn

Reputation: 34337

Your approach is fine, since you are potentially reducing the attack area on your app. But, I'm not sure there's any evidence that using bodyParser (which would allow some malformed JSON, as well as url-encoded and multipart-form encoded data as well) would be any meaningful risk.

You can see exactly what strict: true means here:

http://www.senchalabs.org/connect/json.html

if (strict && '{' != buf[0] && '[' != buf[0]) return next(utils.error(400, 'invalid json'));

It just ensures that the JSON starts with a { or a [. You're still relying on Google not to have screwed up their JSON.parse implementation in V8 the way Rails did with YAML, which I think is a relatively safe bet.

Upvotes: 2

Related Questions