Next JS encountered an error - Error [ERR_HTTP_HEADERS_SENT]: It is not possible to set headers after they have already been sent to the

Having crafted a serverless application using next.js, Vercel, and Google Sheets to store customer contact data, I encountered an issue post-deployment. While my application works flawlessly locally, after deployment, I started receiving the following error:

error - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_http_outgoing:576:11) at ServerResponse._res.setHeader (F:\javascript\ethiostar\node_modules\next\dist\server\base-server.js:129:24) ...

Below is my feedback component in Next.js:

'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';

export default function Feedback() {
  const { register, handleSubmit, reset } = useForm();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [alertMessage, setAlertMessage] = useState('');
  
  // Rest of the code for the Feedback component goes here...

}

This is the logic implemented in submit.js:

import { google } from 'googleapis';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { Name, Email, Message } = req.body;
    
    // Logic for handling POST request and saving data to Google Sheets

    res.status(201).json({ message: 'Data entered successfully' });
  }

  res.status(200).json({ message: 'Done!' });
}

If anyone can help me troubleshoot this issue, it would be greatly appreciated. I've tried ChatGPT without success.

Answer №1

To avoid sending the response twice, consider using return res.status(...) instead of just res.status(...). If you encounter this error, try adding the second res.status(...) within an else block in your code to resolve it without needing a return statement.

Update: Changed res.send to res.status

Answer №2

The issue has been resolved by making changes to the submit.js file. Here is the modified code:

import { google } from 'googleapis';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { Name, Email, Message } = req.body;
    console.log(Name, Email, Message);

    const auth = new google.auth.GoogleAuth({
      credentials: {
        client_email: process.env.GOOGLE_CLIENT_EMAIL,
        private_key: process.env.GOOGLE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
      },
      scopes: [
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.file',
        'https://www.googleapis.com/auth/spreadsheets',

      ],
    });

    const sheets = google.sheets({
      version: 'v4',
      auth,
    });

    const response = await sheets.spreadsheets.values.append({
      spreadsheetId: process.env.GOOGLE_SHEET_ID,
      range: 'A1:C1',
      valueInputOption: 'USER_ENTERED',
      resource: {
        values: [[Name, Email, Message]],
      },
    });

    res.status(201).json({ message: 'Data entered successfully' });
  } else {
    res.status(200).json({ message: 'Done!' });
  }
}

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 embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

The states of both components are only being updated once the second event call is triggered within React

I am currently working with 2 functions in my project. One function is triggered when I type something into the search input, while the other one is called upon selecting a category. The initial values for the search and selectedCategories variables are an ...

What is the most effective way to handle DOM events in Angular 8?

Looking to listen for the 'storage' event from the window in Angular 8. What is the recommended approach to achieving this in Angular? window.addEventListener('storage', () => { }); One method involves using Renderer2, but are ther ...

How can I use JavaScript api calls to retrieve an image url and insert it into an image tag in an

I have a JSON object that I need to use to retrieve images from a remote URL and display them in the img tag using API calls. The API link can be found at <div class="emoji"> <ul id="emojiz"></ul> <span style= ...

Choose a looping function in React JS that iterates over an array of objects

I have an array of objects let arr = [0: {received: "Return Received", approved: "Approved", rejected: "Rejected"} 1: {authorized: "Authorized", received: "Return Received"}} I am looking to populate a < ...

It appears that the JS function is not being triggered

I am facing an issue with my JavaScript code where a ball is not showing up even though it should. I have an array with only one element, and when that element matches with "F2", the ball is supposed to appear. I suspect there might be a problem with my us ...

Managing JavaScript with Scrapy

Spider for reference: import scrapy from scrapy.spiders import Spider from scrapy.selector import Selector from script.items import ScriptItem class RunSpider(scrapy.Spider): name = "run" allowed_domains = ["stopitrightnow.com"] start_urls = ...

How to properly handle string escaping within a JSON object

When I send this object as JSON response, it includes double backslashes in the URL. {"__type":"http:\/\/example.com\/contracts\/documents\/rendering\/instructions\/1\/0"} My desired response is: {"__type":"http:& ...

Evaluating Vue.js Watchers using Jasmine

I want to write a test for a VueJS watcher method, in order to verify if it's being called. The watcher method in my component is structured like this: watch: { value: (newValue, oldValue) => { if (newValue.Status === 'Completed') ...

Ways to showcase a website within an HTML document using a URL?

Is it possible to show 2 webpages on a single aspx webpage? For instance, When a user opens the link for www.mywebsite.com, I would like to display both www.google.com and www.bing.com on my homepage. Behind the scenes, I will call two separate URLs an ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

Exploring MongoDB through User Interface Requests

As part of a project to develop a minimalist browser-based GUI for MongoDB, an interesting question has arisen. How can we accurately display the current state of the database and ensure it is continuously updated? Specifically, what methods can be utiliz ...

Issue with React-Native Picker - managing item selection

Encountering an issue with the Picker picker component. There is an array of currencies as strings. Using the Picker to select items from this array, and have a function included in the onValueChange prop in Picker. The problem arises when trying to select ...

Avoiding hydration errors when using localStorage with Next.js

Want to save a token and access it using local storage The code snippet I am using is: if (typeof window !== 'undefined') { localStorage.setItem(key, value) } If I remove the window type check, I encounter this error: localStorage is not ...

FingerprintJS is experiencing an issue with the navigator object not being defined, resulting in

I am currently working on extracting browser fingerprint using fingerprintjs2, an npm package in Javascript. However, I encountered the following error: ReferenceError: navigator is not defined Error Logs: Code Snippet: const Fingerprint = require(&apo ...

Update the delivery status of an Uber Eats order using the Uber Eats API

Hey there, I hope everyone is doing well. I need to update the delivery status of orders on Uber Eats through my app. I am in partnership with Uber Eats and using the Update Delivery Status API for this purpose. The API requires the scope eats.store.order ...

Interacting with a button using Python Selenium while validating onFocus with JavaScript

I'm currently working on automating webpage navigation with Selenium in Python. My goal is to click on an HTML button that triggers JavaScript code to validate if the button is focused during the onclick action. Although I can successfully select a v ...

I am hoping to incorporate a "Load More" Pagination button into my Next JS Website

Our blog was created using Next JS and WordPress as our API. As we added more content, the number of posts on our blog exceeded 500, causing it to crash because all the blog posts were being called from the server simultaneously. We plan to implement a ...

Are you experiencing issues with the cipher update when using the crypto library?

When using the crypto module for string encryption and the passed string is not 16 bytes, I expected the cipher.update() function to automatically add padding and create a 16-byte string. However, during debugging, cipher.update returned an empty string. I ...

How can I alter the color of the menu text when scrolling to the top of a webpage?

As I navigate my website, I encounter a menu with a transparent background at the top that changes to black as I scroll down. On a specific page where the background is white, this presents an issue: when the menu reaches the top, the white background clas ...