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

When you click, apply the hidden class to all the div elements

Is there a way to apply the .hide class to all .slide divs whenever the .option button is clicked? If so, how can I modify my JavaScript code so that all .slide divs receive the .hide class (if they don't already have it) upon clicking the .option bu ...

Trouble Displaying DHtmlX Scheduler Events on Safari and Internet Explorer

I have recently embarked on the journey of building a nodejs application and decided to incorporate DHtmlX Scheduler as my calendar. To my dismay, I encountered an issue where the events are not displaying on Safari or IE, despite working perfectly fine on ...

Is it possible to simultaneously run two Node.js projects on Windows?

Is it possible to run two Node.js projects on a Windows operating system? If so, what is the process for doing that? If not, can I run two Node.js projects on a dedicated host instead? ...

"Implementing a click event on a dynamically generated element is triggering the event for all of its parent elements

I have a task to generate a dynamic table with data retrieved from the server. Each row in the table contains a tag that I am trying to link to a click event. The code snippet below demonstrates how the dynamic table is created: function ProcessResponse ...

What could be causing my Material UI Divider to appear invisible within a Material UI Container or Paper component?

Hey there! I am absolutely smitten with Material UI - it's incredibly versatile. However, I'm facing a bit of trouble with the Material UI Divider not displaying when nested within either a Container or Paper component. I've looked into it ...

Troubleshooting problem with sorting in Angular 4 material header

Using Angular 4 material for a table has presented me with two issues: 1. When sorting a table, it displays the description of the sorting order in the header. I would like to remove this. It displays "Sorted by ascending order" here. The ngx modal theme ...

Issue with integrating Razorpay into a Node.js Express application

I am currently working on setting up a checkout page using nodejs and express with Razorpay as the payment gateway. The issue arises when trying to run the checkout() function by clicking the "Checkout" button within my shopping-cart.hbs file. Despite havi ...

Issue with October CMS: Radio button selection triggers an Ajax call, but clicking twice in quick succession causes the content

I am currently utilizing October CMS and materializecss to develop a form with options on one of my pages. The form functions correctly as it dynamically loads content when different options are clicked. However, I have identified a problem where clicking ...

Adjust the horizontal position of a text element using CSS

I am faced with a specific challenge where I need to center the text "test" within a text tag using only CSS, without being able to directly change the HTML. <text width="13.89" height="13.89" x="291.46999999999997" y="156.55" transform= ...

Tips for effortlessly moving content by dragging and dropping it into a text box

Before attempting to create something, I want to verify its feasibility. Begin with a text area that can be pre-filled with text and allow users to add or delete text. Alongside the text area, there are small elements that can be images or HTML components ...

Modifying the Redux state using an array with prototypes

In my React application, I am utilizing Redux along with the ChartJS library to create charts. Occasionally, when I extract an array from the global Redux state, it appears in this format: ejeY: Array(7) 0: 43783 1: 85001 2: 100960 3: 752 ...

Fetching information from the server in response to the data transmitted from the client

In need of help with sending a string id from the client to server side and retrieving related information using Node.js for the back-end. I have searched online but haven't found a solution yet. Hoping this isn't a redundant question. ...

The application monitored by nodemon has halted - awaiting modifications in files before restarting the process

1. My ProductController Implementation: const Product = require('../models/product') //Creating a new product => /ap1/v1/product/new exports.newProduct = async(req, res, next) => { const product = await Product.create(req.body); re ...

I am facing an issue with uploading files to my designated directory through Node.js Multer

After creating a web service using node js and implementing a form with React interface that includes user information and file upload, I encountered an issue while attempting to save the file to the specified directory on the node js server using multer. ...

In need of guidance to troubleshoot the error "Encountering problem while reading properties of undefined (jwt)"

I'm currently facing an authentication flow issue and I am looking for assistance from someone with a keen eye to help me troubleshoot and resolve the problem. The specific error message I am encountering is [next-auth][error][JWT_SESSION_ERROR] http ...

JavaScript decimal validation not functioning as intended

Hey everyone! I've created a script that restricts textboxes to allow only decimal numbers. Take a look at the code snippet below: function onlyDecimal(evt) { if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57))) ...

Strategies for avoiding asynchronous behavior in AJAX with JQuery

My questions are best explained through code rather than words. Take a look at the snippet below and try to understand it: $('#all').on('change', function(){ //ONCHANGE RADIOBUTTON, THERE ARE #bdo, #cash also. $.ajax({ type:"GET", ...

Step-by-step guide on displaying SVG text on a DOM element using Angular 8

I have a FusionChart graph that I need to extract the image from and display it on the same HTML page when the user clicks on the "Get SVG String" button. I am able to retrieve the SVG text using this.chart.getSVGString() method, but I'm unsure of ho ...

Ensure that the second y-axis in charts.js consistently shows the 100% tick

I have implemented a scatter chart using recharts and it currently looks like this: The right-y-axis in my chart represents the percentage and is showing the correct values as desired. However, I am looking to make a modification so that the 100% mark is ...

Receiving a response from an XMLHttpRequest() within a function

I've come across a situation where I have a function called isOnline(), and here's how it looks: function isOnline() { var request=new XMLHttpRequest(); request.onreadystatechange=function() { if(request.readyState==4) { ...