Search code examples
javascriptreactjsnext.jsbackend

how to handle a post request in next.js?


I want to setup a POST route in my api folder using next.js, And I'm sending the data to the route but I can't parse the data to actually save it in the database. what is the best way to handle POST routes in next.js. particularly parsing the data in JSON format?


Solution

  • As with everything, it depends. In Next.js v12, you do not need JSON.parse(req.body) in the API route as long as you have NOT explicitly set bodyParser: false in the exported configuration for the API route (see https://nextjs.org/docs/api-routes/api-middlewares). The req.body will be parsed automatically to an object for example if the content-type of the request is application/json. In this case since the content is pre-parsed into a object, trying to run JSON.parse(req.body) in the API will likely throw an error.