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

Notification pop-up for accepting cookies on a website

I am curious about how to insert a .js code into a button within a bootstrap alert so that when the user clicks 'accept', the alert box does not reappear. Thank you very much. Here is the code I have, but it is not working. Javascript: $(".bt ...

Material UI Grid List rows are displaying with an unusually large gap between them, creating a

Currently, I am utilizing Material UI in combination with Reactjs. One particular issue that I am encountering involves the Grid List Component. In my attempt to establish a grid of 1000x1000px, I have specified the height and width within the custom gridL ...

How can I inform a parent component in React JS when an event occurs in the child component?

I created a React JS app that consists of a simple hierarchy: ContainingBox wraps two InfoBox components. In this scenario, my goal is to inform the ContainingBox component when something is clicked and which specific InfoBox (identified by label name) has ...

What is the best way to halt a jQuery function when hovering over it?

Currently, I have a jQuery function set up to run on setInterval(). However, I am looking for a way to pause the interval when hovering over the displayed div and then resume once no longer hovering (i.e., continue cycling through the divs). Does anyone ...

When making a Get Request from Angular, the header fails to appear for servicing

I am currently working on an angular JS application where I need to call a GET API that is OAuth 2.0 enabled, requiring a Bearer Token in the header for authentication. The method I am using to make the HTTP request is as follows: var config = { heade ...

Typescript on the client-side: what is the best way to eliminate circular dependencies when using the factory method design pattern?

In my code, I have implemented the factory method pattern. However, some instances using this pattern end up with circular dependencies. Removing these dependencies has proven to be a challenge for me. To illustrate, consider the following example: // fact ...

Display a hidden div on hover using JQUERY

How can I make a hover popup appear when submitting a form, and have it disappear only when the mouse is out of both the popup div and the submit button? Currently, the hover popup shows up but disappears when entering the popup. Can someone assist me in r ...

Show information retrieved from fetch api

Hi there! I've been trying to fetch data from the Avascan API and display it on my HTML page, but so far, I haven't had any luck. I've experimented with using the Fetch API, JSON, and AJAX methods, but none of them seem to work for me. Do yo ...

Conceal any errors and warnings from appearing in the console

Many programming languages, such as PHP, provide methods to suppress error and warning messages. Is there a similar approach in JavaScript or jQuery to stop errors and warnings from appearing in the console log? ...

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

Maintaining Aspect Ratio and Adding Letterboxes with Next.js Image

In my Next.js app, there is a section dedicated to displaying selected photos from a gallery. It's crucial for this area to maintain a fixed size of 566px*425px as users navigate through images or when a photo is loading. While the layout is responsiv ...

JavaScript scroll event not firing

I have searched multiple questions on SO to avoid duplication, but none of the solutions worked for me. My goal is to toggle the visibility of a button based on scroll position. I tried creating a scroll event listener to trigger a function that checks th ...

Encountered a 'SyntaxError: await is only valid in async function' error while trying to utilize the top-level await feature in Node v14.14.0

I'm excited to use the new top-level await feature that was introduced in Node version 14.8. For more information, you can check out this link and here. I did a thorough search but couldn't find any questions related to issues with the new featur ...

Displaying a loading spinner image as PHP script runs

Hey there! I've been experimenting with using a script to show a loading bar while my PHP code is running. I followed the instructions on this website, but even after following the exact steps, my loading bar still isn't showing up. Any suggestio ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

Problem with Jsdom retrieving document

I am struggling to utilize jsdom for loading a local HTML file. Here is the code snippet: var config = { file: "filename", scripts: ["node_modules/jquery/dist/jquery.min.js"], done: function(err, window){ con ...

Strategies for addressing the issue of assigning "xx" to intrinsic attributes and props in React with TypeScript

I'm facing an issue where I am unable to locate 'count' and assign {count: number; title:string} type to IntrinsicAttributes in a React and TypeScript environment. There are two components involved, ParentComponent and ChildComponent. In t ...

Instructions for overlaying a text onto the select input field in DataTables

I am currently utilizing the DataTables select input feature to capture only the first three columns of data. However, I would like to enhance this by adding a text element above the select inputs within the DataTables interface. Is there a way to achieve ...

A simple guide on accessing a local PDF file and returning it as the response for an ExpressJS application

In my ExpressJS application, I have a method for generating a PDF file and sending it to the client. However, there are cases where I need to retrieve an existing local PDF file and return it as the response. I'm unsure how to handle this scenario. ...

I encounter difficulties in executing a request through ReactJS, as the header cannot be properly composed

const fetchData = async () => { try { const response = await axios.get('http://localhost:8080/omp/patients', { headers: {authorization: 'Bearer ' + token}}); this.state = response.data; } catch (ex) { ...