What is the best way to retrieve form values on the server in nextJs?

I'm facing an issue with passing form data to my API endpoint in nextJS. I have set up the form using Formik and Yup for validation. Oddly, when I check the console on the client side, I can see the user input values just fine, but on the server side, these values appear as undefined. Additionally, upon inspecting the request object in the console, I noticed that the body is empty and bodyUsed is false. Here's a snippet of my client-side component:

"use client";
import React, { useState } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import FormGroup from "../(components)/FormGroup";

const Contact = () => {
  const [loading, setLoading] = useState(false);
  const [processed, setProcessed] = useState(false);

  const formik = useFormik({
    initialValues: {
      firstName: "",
      lastName: "",
      email: "",
      message: "",
    },
    onSubmit: async (values) => {
      try {
        setLoading(true);
        const res = await fetch("http://localhost:3000/api/Contact", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(values, null, 2),
        });
        console.log(res);

        if (res.ok) {
          setProcessed(true);
          setLoading(false);
        }
      } catch (error) {
        console.log("Error processing message: ", error);
        setLoading(false);
      }
    },
    validationSchema: yup.object({
      firstName: yup.string().trim().required("First Name is required"),
      lastName: yup.string().trim().required("Last Name is required"),
      email: yup
        .string()
        .email("Must be a valid email")
        .required("Email is required"),
      message: yup.string().trim().required("Message is required"),
    }),
  });

  return (
    <div className="min-h-screen flex flex-col justify-start  items-center w-full mx-auto mt-24">
      {processed && (
        <p className="text-lg font-semibold justify-self-center">
          Thank you for contacting us! We'll get back to you shortly.
        </p>
      )}
      {!processed && (
        <form
          className="flex flex-col space-y-2"
          onSubmit={formik.handleSubmit}
        >
          <div className="w-full flex space-x-2">
            <div className="flex flex-col">
              <FormGroup
                inputLabel={"First Name:"}
                placeholder={"First Name"}
                name={"firstName"}
                value={formik.values.firstName}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
              {formik.errors.firstName && (
                <p className="text-sm text-pink-600 mt-1">
                  {formik.errors.firstName}
                </p>
              )}
            </div>
            <div className="flex flex-col">
              <FormGroup
                inputLabel={"Last Name:"}
                placeholder={"Last Name"}
                name={"lastName"}
                value={formik.values.lastName}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
              {formik.errors.lastName && (
                <p className="text-pink-600 text-sm mt-1">
                  {formik.errors.lastName}
                </p>
              )}
            </div>
          </div>
          <div className="mt-2">
            <FormGroup
              inputLabel={"Email:"}
              placeholder={"Email"}
              name={"email"}
              value={formik.values.email}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            />
            {formik.errors.email && (
              <p className="text-pink-600 text-sm mt-1">
                {formik.errors.email}
              </p>
            )}
          </div>
          <label htmlFor="message">Message:</label>
          <textarea
            cols={4}
            rows={4}
            placeholder="Message"
            name="message"
            className="rounded-md px-2 py-3 shadow-sm  text-black"
            value={formik.values.message}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />
          {formik.errors.message && (
            <p className="text-pink-600 text-sm mt-1">
              {formik.errors.message}
            </p>
          )}

          <button
            disabled={loading}
            type="submit"
            className="px-3 py-2 bg-green-500 rounded-lg shadow-sm mt-2 hover:bg-green-600"
          >
            {loading ? "Submitting..." : "Submit"}
          </button>
        </form>
      )}
    </div>
  );
};

export default Contact;

And here's a snippet of the server-side component:

import Contact from "@/app/(models)/Contact";
import { NextResponse } from "next/server";

export async function POST(req) {
  const { firstName, lastName, email, message } = await req.body;

  try {
    const newContact = await Contact.create({
      firstName,
      lastName,
      email,
      message,
    });

    if (newContact) {
      return NextResponse.json(
        {
          message:
            "Successfully received your message. We will respond shortly!",
        },
        { status: 201 }
      );
    }
  } catch (error) {
    return NextResponse.json({ message: "Error!", error }, { status: 500 });
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript code to use Angular expressions in an HTML document

I am facing an issue with using Angular expressions inside JavaScript within an ng-repeat loop on my HTML page (note that the app and controller have been declared elsewhere): <div ng-repeat="eleRubrique in scopeComplet"> <script type="text ...

Transferring onFocus in a React component

Is there a way to hide the yellow title when focusing on an input field? I'm having trouble passing it from the component to use it in the index page. You can view my code at this link. ...

Creating a dropdown menu using React库

The API response I received looks like this:- [ { "Product.Name": "Data Migration - Test1", "Product.Id": "8ad0", "Product.Hello__c": { "Value": "First ...

The material-table is utilizing a component as data, but is failing to pass the component context during the onChange

I attempted to include a component as data in a material table, but I'm facing an issue with accessing the 'this' context of the component to update the state within the onChange function. Unfortunately, the editable feature offered by mater ...

The JavaScript audio is not working for the first three clicks, but starts playing smoothly from the fourth click onwards. What could be causing this issue?

$(".btn").click(function(event){ playSound(event.target.id); }); function playSound(name){ $("." + name).click(function() { new Audio("sounds/" + name + ".mp3").play(); ...

Credit for the Position swipejs

After integrating a swipeJS photo slideshow into my jQuery mobile application, I encountered an issue. I am trying to create points for counting the pictures similar to what is seen on this page: Although I have added the necessary HTML and CSS code to my ...

Is there a way to import additional packages into the next.config.js file without replacing the entire export object?

Is there a way to import specific packages into next.config.js without replacing the entire export object? I've noticed a common method of setting up Next.js through next.config.js that doesn't align with the documentation. It typically involves ...

"Implementing Vue mousemove functionality only when the mouse button is pressed

Is it possible to initiate a mouse movement only after the element has been clicked first? I am exploring this functionality for an audio player timeline. .player__time--bar(@mousedown="setNewCurrentPosition($event)") .slider(role="slider" aria-valuem ...

Is there a way to programmatically change the page language in a Next.js App Router?

I'm currently localizing a Next.js 13 website using App Router. Most routes are accessed through [lang], making the process straightforward. However, there are a few routes where language is defined in the database and the existing links appear as /p ...

Vue.js: Issue with dynamically calculating class property

I am attempting to create a computed class in vue.js 2.0 using the following syntax: <li :class="'str1' calcStarClass(1, p.rtg)"> </li> In my methods section, I have the foll ...

Is my jQuery code generating a large number of DOM objects?

I am currently developing a hex dumper in JavaScript to analyze the byte data of files provided by users. To properly display a preview of the file's data, I am utilizing methods to escape HTML characters as outlined in the highest-rated answer on thi ...

Add a click event to elements that match

I must admit that I am not particularly knowledgeable in Javascript/jQuery and my question might come across as trivial. However, I am trying to assign a click event to every element on the page with the following code: $(document).ready(function () { ...

Eliminate Dates from the Past - Jquery Datepicker

Currently, I am developing a booking system for my client. I have successfully disabled Sundays and Mondays (the days she is not open). However, I am now working on enhancing the functionality by blocking out past dates. Although I have written a function ...

Finding a potential data breach in Node.js, MongoDB, and Chrome, exposed passwords are

My web app is built using nodejs with mongodb as the database backend, and I am encountering an issue with Chrome browser flagging my login process via passport.js as an exposed password. How can I prevent this warning? Should I implement something like Bc ...

The concept of nested ng-repeat in AngularJS

My HTML structure is as follows: <div class="fields-plan"data-ng-repeat="roomname in assign.roomname"> <section> <span>Room: {{roomname}}</span> </section> <ul data-ng-repeat="r ...

How to handle event methods with Vue

Currently, I am facing a challenge in passing an event downward with a bound change listener to a child input component. Although I am utilizing wrapped input components, my goal is to define methods within the parent component. //App.js: <currency-inp ...

What do you want to know about Angular JS $http request?

My goal is to send a request using $http with angular js in order to retrieve a json object from google maps. $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city&a ...

Creating a webpage that dynamically loads both content and video using HTML and Javascript

I designed a loading page for my website, but I could use some assistance. The loading page remains visible until the entire HTML content is loaded and then it fades out. However, I am facing an issue because I have a background video that I want to load ...

When making a JQuery - Ajax get request, I did not receive the "extracts" or "exintro" (summary) property in the response

Lately, I've been working on a small web application that displays search results from Wikipedia on the webpage after entering a search term into a text field. This has been a project that I’ve dedicated a lot of time to. I have configured an ajax g ...

Node js server for world's warm greetings

I have been attempting to utilize Node.js for hosting a web server on a dedicated PC, but unfortunately I am unable to access it from anywhere outside of my local network. After researching online, the general consensus is that all I need to do is enter t ...