how to handle a post request in next.js?

To get POST requests working in Next.js API routes, you likely want to do 3 things.

  • Limit the method to POST
  • Use JSON.parse() to parse the JSON on in the route (not needed in NextJS v12+)
  • Send a request to the backend

https://nextjs.org/docs/api-routes/api-middlewares

API Route

API routes in Next.js by default support all types of requests, including GET, POST, DELETE, etc. So while it isn’t required, it’s a good idea to restrict the route to the methods you want to support.

In your case, if you want to only support POST requests on a certain route, you use req.method to filter out non-post requests.

if (req.method !== 'POST') {
  res.status(405).send({ message: 'Only POST requests allowed' })
  return
}

To parse the JSON, all you can use JSON.parse(). This is not needed if you’re using NextJS v12+, as long as you’ve not set bodyParser: false.

const body = JSON.parse(req.body)

Put it all together, and your API route should look something like this:

// pages/route-name.js

export default function handler(req, res) {
  if (req.method !== 'POST') {
    res.status(405).send({ message: 'Only POST requests allowed' })
    return
  }


  // not needed in NextJS v12+
  const body = JSON.parse(req.body)

  // the rest of your code
}

Send the request

Lastly, you need to send a POST request from your front-end code to the backend. You may already know how to do this, but mentioning this for completeness.

fetch('/api/route-name', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(objectWithData),
})

Quick aside, you don’t need to worry about cross-browser compatibility for fetch with Next.js. Next.js automatically adds a polyfill when needed.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)