Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'm am passing strict: true thinking that that would add a layer of security against invalid json. Anyone else doing anything similar? Looking for an opinion from someone who was experience with this setup. Thanks

like image 854
Xerri Avatar asked Nov 02 '22 18:11

Xerri


1 Answers

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.

like image 104
Dan Kohn Avatar answered Nov 09 '22 04:11

Dan Kohn