5

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.

Chenmunka
  • 685
  • 4
  • 21
  • 25
Xerri
  • 4,916
  • 6
  • 45
  • 54
  • 2
    it's `strict` by default. you don't need to set it as true. – Jonathan Ong Jul 23 '13 at 09:38
  • In post request if u want to get the post value means.you should add this middleware -app.use(express.bodyParser());. – sachin Jul 23 '13 at 09:56
  • 1
    I don't think that is true @sachin. Mine is working. Body parser is a collection of `app.use(connect.json()); app.use(connect.urlencoded()); app.use(connect.multipart());` – Xerri Jul 23 '13 at 10:54

1 Answers1

2

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.

Dan Kohn
  • 33,811
  • 9
  • 84
  • 100
  • 5
    Hey....just as an addition to this. Have a look at http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html – Xerri Sep 16 '13 at 13:57