Back

Technologies:

javascriptjavascript
typescripttypescript
avatar
Tolerim
a month ago

How can I access the req.body in NextJS?

While working on my API, I encountered issues accessing req.body. Despite checking the request tab in console and verifying that the string I was searching for exists, I was still unable to obtain it. Here are the images of the Request Tab and Response Tab that I viewed for reference. Below is the code that I utilized:

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === "DELETE") {
    const session = await getServerSession(req, res, authOptions)
    if (!session) {
      return res
        .status(401)
        .json({ message: "Please sign in" })
    }

    // Obtain Post ID
    const postId = req.body
    console.log(postId)
    if (!postId) {
      return res
        .status(400)
        .json({ message: "Post ID is missing", body: postId })
    }

    // Delete Post
    try {
      const result = await prisma.post.delete({
        where: {
          id: postId,
        }
      })
      res.status(200).json(result)
    } catch (err) {
      res.status(500).json({ message: "An error has occurred while attempting to delete the post.", body: postId})
    }
  }
}
To acquire the postId through req.body, I employed the above code, but encountered issues.

Answers(2)
avatar
Vogi
a month ago
Verified Answer
Based on the code you provided, it seems that you are trying to obtain the postId through req.body but are encountering issues. I found a Stack Overflow post that might be helpful in resolving your issue. One user suggested using body: JSON.stringify(bodyData) instead of body: bodyData. Another user suggested setting the Content-Type header to application/json in the request header. I hope this helps! Let me know if you have any other questions.

Sources

javascript - NEXT JS req.body undefined - Stack OverflowNextjs API POST request body not being parsed - Stack OverflowAPI Routes: Request Helpers | Next.js
avatar
Tolerim
a month ago
It seems like you are not able to access the req.body object in your code. To access the body of the request, you need to use a middleware like body-parser. Here's an example of how you can use it in your code:
import { NextApiRequest, NextApiResponse } from "next";
import bodyParser from "body-parser";

// Create a middleware instance
const jsonParser = bodyParser.json();

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === "DELETE") {
    const session = await getServerSession(req, res, authOptions)
    if (!session) {
      return res
        .status(401)
        .json({ message: "Please sign in" })
    }

    // Use the middleware to parse the request body
    jsonParser(req, res, async () => {
      const postId = req.body.postId;
      console.log(postId)

      if (!postId) {
        return res
          .status(400)
          .json({ message: "Post ID is missing", body: postId })
      }

      // Delete Post
      try {
        const result = await prisma.post.delete({
          where: {
            id: postId,
          }
        })
        res.status(200).json(result)
      } catch (err) {
        res.status(500).json({ message: "Error has occured while deleting the post", body: postId})
      }
    });
  }
}
In this example, we are using the body-parser middleware to parse the JSON body of the request. We create an instance of the middleware and use it to parse the body inside the handler function. You can access the postId value from the req.body object.
;