KeoooDev
KeoooDev

Reputation: 576

NEXT JS req.body undefined

not sure what I'm doing wrong?

I'm getting undefined when trying to upload my form data to my supabase the data is coming to the API undefined but when I pass it to the function it prints what I want to send to the API in my submit handler.

export const Quote = () => {
  const [formIsValid, setFormIsValid] = useState(false);
  //----------------------------_FORM VALIDATION------------------------------------
  const {
    value: firstName,
    inputBlurChangeHandler: firstNameBlur,
    isValid: firstNameValid,
    hasError: firstNameInputHasError,
    valueChangeHandler: firstNameChangeHandler,
    reset: resetFirstName,
  } = useInput((value) => value.trim() !== "");



**hooks & useEffect removed to shorten question they are same as above but different names**

  console.log(formIsValid, "FORM IS VALID");


  const formSubmitHandler = async (event) => {
    event.preventDefault();

    //UNDEFINEDS
    await fetch("api/dbhandler", {
      method: "POST",
      body: {
        firstname: firstName,
        secondname: secondName,
        street: streetAddress,
        phone: phoneNumber,
        email: emailAddress,
        postal: postalCode,
        about: quoteDescription,
      },
      headers: {
        "Content-Type": `text/plain`,
      },
    });
  };

API is coming as undefined in req. body but if I console log in the submit handler values are being passed to the function not sure what I am doing wrong

import { supabase } from "../../utils/supabaseClient";

const supabaseApiHandler = async (req, res) => {
  console.log(req.body.firstname);
  if (req.method === "POST") {
    const firstname = req.body.firstname;
    const secondname = req.body.secondname;
    const email = req.body.email;
    const street = req.body.street;
    const postal = req.body.postal;
    const phone = req.body.phone;
    const about = req.body.about;

    const { data, error } = await supabase.from("quotes").insert([
      {
        firstname,
        secondname,
        email,
        street,
        postal,
        phone,
        about,
      },
    ]);
  }

  res.status(200).json({ name: "test" });
};

export default supabaseApiHandler;

Upvotes: 6

Views: 10799

Answers (1)

user3152459
user3152459

Reputation: 403

If you have the body parser disabled in the API route, req.body will be empty.

I accidentally left this code in without using another body parser.

export const config = {
  api: {
    bodyParser: false,
  },
};

Upvotes: 19

Related Questions