skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Yeah, there are differences in using either, and this can be reflected in its parsing capability, security, and performance as well

    The extended true can parse nested objects and arrays because of the qs library but the false value can only parse key-value pairs as it uses query-string

    You can already guess that extended true might performance time will be high because of the QS library which is more complex.

    Even the extended false + Json methods as extra steps might also increase performance time

    When it comes to security, the extended true is safe but attacks like prototype pollution can get to it, while the extended false + JSON method can be more secure since it kind of provides you more control over the data being parsed

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search