Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route:

import type { NextApiRequest, NextApiResponse } from 'next'
import sanityClient from "@sanity/client"


const config = {
  dataset: process.env.NEXT_PUBLIC_SANITY_DATSET,
  projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
  useCdn: process.env.NODE_ENV === "production",
  token: process.env.SANITY_API_TOKEN
}

const client  = sanityClient(config);


export default async function createComment(
  req: NextApiRequest,
  res: NextApiResponse
) {

  const {_id, name, email, comment} = req.body

  try {

    await client.create({
      _type: 'comment',
      post: {
        _type: "reference",
        _ref: _id
      },
      name,
      email,
      comment
    })
  } catch (error) {
    return res.status(500).json({message: "Couldn't submit comment", error})
  }


  console.log("Comment submitted")
  res.status(200).json({ message: 'Comment Submitted Successfully' })
}

Additionally, here is the frontend code that utilizes Fetch API to send a POST request to the above-mentioned api route:

  const onSubmit: SubmitHandler<IFormInput> = (data) => {
    fetch("/api/createComment", {
      method: "POST",
      body: JSON.stringify(data),
    })
      .then(() => {
        console.log(data);
      })
      .catch((error) => {
        console.log(error);
      });
  };

Despite repeated attempts such as clearing cache and restarting the server, an error persists.

Answer №1

It is highly likely that the issue stems from the `sanityClient`. Consider verifying the .env variables or ensuring that the token received from `sanity` is valid... you never know what might be causing the problem.

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

Ways to conceal the 'Return to Top' button in a script that is only revealed after navigating to the bottom of the page

Can anyone help me hide the 'Back to Top' button in a script that only appears after scrolling to the bottom of the page? I need to take screenshots without it showing up. I've tried using the code below, but the 'Back to Top' but ...

An unexpected problem with text redirection that should not be happening

I am facing an issue with my HTML text field and post button on my website. Whenever I click the post button to make a post, it redirects to a separate PHP file called post.php which handles PHP and MySQL code for posting. However, I want to avoid this red ...

Issue with deactivating attribute through class name element retrieval

There are multiple input tags in this scenario: <input type="checkbox" class="check" disabled id="identifier"> as well as: <input type="checkbox" class="check" disabled> The goal is to remov ...

How can I ensure my function waits for a promise to be resolved using Async / Await?

I'm running into an issue where I want my function to keep executing until the nextPageToken is null. The problem occurs when the function runs for the first time, it waits for the promise to resolve. However, if there is a nextPageToken present in th ...

Utilizing Tailwind's adaptability for dynamic values

I'm currently diving into React with Tailwind CSS and I'm eager to incorporate dynamic values into my styles. I've had experience with MUI where it's as simple as: <Box sx={{ width: dynamicValue }} /> Can someone guide me on h ...

Extracting Querystring Value in C#

When using the code below to set the iframe src with JavaScript, everything works as expected. However, in the C# code behind, I am receiving the query string in a format like this: id=Y&amp%3bcust_id=100&amp%3. Is there a way to simplify this? v ...

A step-by-step guide on transferring data from an HTML file to MongoDB using Python Flask

I am currently developing a web application that involves uploading multiple CSV files and transferring them to MongoDB. To build this application, I have utilized Python Flask. To test out different concepts for the application, I have created a sample f ...

Challenge with maintaining tab view data in Openui5

I am facing an issue with my application's tabs. Each tab renders data retrieved through ajax calls from the database. However, whenever I switch between tabs, the data gets refreshed each time. Is there a way to prevent this refreshing behavior and i ...

"Mastering the art of text animation: A beginner's guide

If you want to see a cool moving text animation, simply head over to this link: . The text will automatically type out and then clear just like the example below: Ever wondered how to create this kind of text animation? Any language can be used - React, A ...

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

Using Javascript to generate a button that randomly chooses links within the webpage

Looking for help with JavaScript to select a link when a button is clicked on the page? Check out my code and let me know what I'm doing wrong. For the full code, visit: here HTML <!doctype html> <html lang="it" xmlns="http:/ ...

VueRouter child route with trailing slash after default

VueRouter automatically includes a trailing slash before the child route's path. Consider this example of a route configuration: const routes = [ path: '/home', components: { default: HomeBase }, children: [ ...

Set up a WhatsApp web bot on the Heroku platform

I am currently in the process of developing a WhatsApp bot using the node library whatsapp-web.js. Once I finish writing the script, it appears something like this (I have provided an overview of the original script) - index.js const {Client, LocalAuth, M ...

Enhance the HTML content using a JavaScript function

Here is the code that I have: <label>Brand</label></br> <select name="brand" id="brand" onChange="changecat(this.value);"> <option value="" selected>Select Brand</option> <option value="A">AMD</option&g ...

The output of the Node.js crypto.pbkdf2 function may not match the result obtained from CryptoJS.PBKDF

Currently, I am utilizing PBKDF2 on both the frontend with CryptoJS and the backend with Node.js. Despite using the identical salt, algorithm, number of iterations, and password, the derived keys are turning out to be different. Below is the code snippet ...

Validation of Date in Angular 5 (with specified minimum and maximum dates)

Struggling to find a simple solution for this issue, I have a date input like the following: <input [(ngModel)]="toolDate" type="text" class="tool_input tool_input__date"> To control the input and restrict it to only accept dates, I am using . In m ...

Iterating through div elements and assigning unique ids to them before enabling click functionality

I'm attempting to create multiple div elements inside my loop that will each display a unique message when clicked. However, I'm encountering issues with the code and can't seem to make it work as intended. Here is what I am trying to achiev ...

Are Node environment variables persistent?

First Example: package.json Scripts "scripts": { "start": "node app.js", "test": "NODE_ENV=test mocha --reporter spec" }, Command to Run Test: if (process.env.NODE_ENV === "test") { cons ...

Trouble arises when selecting shapes in Angular 6 with FabricJS

Currently, I am experimenting with fabricjs and drawing different shapes. Interestingly, when I draw the shapes, they appear accurately on the canvas. However, when I try to switch to selection mode, I encounter an issue where I am unable to select the ind ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...