javascriptnode.jsjsonexpress

What is the difference between using express.urlencoded() with extended set to true vs set to false + manual JSON stringify/parse calls?


In my NodeJS/Express server I must choose between setting extended to true or to false for the urlencoded middleware:

app.use(express.urlencoded({ extended: true/false }));

I understand that if we use false, it means we will be using the query-string library to parse the request body which cannot parse complex data like objects or arrays. If we use true we would be using the qs library which can parse objects and arrays.

In my application I will have to send requests containing objects and arrays. However, because the tutorials I have watched always used extended: false without me understanding what it did, I ended up learning to use a workaround where I use JSON.stringify() to send my objects and arrays to my server and then use JSON.parse() to reconstruct them after the body is parsed inside my route.

// front end
const myArray = [{ someProperty: "someValue" }, { someProperty: "someValue" }];
const formData = new FormData();
formData.append("myArray", JSON.stringify(myArray));
fetch("/my-route", {
  method: "POST",
  body: formData,
}).then(res => res.json())

// backend
router.post("/my-route", (req, res) => {
  myArray = JSON.parse(req.body.myArray);
  ...
});

This got me wondering what the difference between simply using extended: true is compared to using extended: false with the JSON.stringify() and JSON.parse() workaround. I particularly want to ask what the performance and security differences are? would the qs library be slower than using the JSON methods? And I am not so sure what security risks exist with using the workaround vs using the extended option.


Solution

  • If you're building some kind of API you should consider just using actual JSON instead of JSON wrapped into a urlencoded content type. There's no good reason to have a nested format in the example you described.

    The main drawback of using the form/urlencoded format over JSON is that everything is a string. So you can't send booleans, numbers and nulls.