Troubleshooting AWS S3 SDK upload error when sending data from Next.js API endpoint hosted on Vercel - ERR_HTTP_HEADERS_SENT

I'm currently working on uploading a file from my Next.js API endpoint running on Vercel using the @aws-sdk/client-s3 package. Here's a snippet of my code:

import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import type { NextApiRequest, NextApiResponse } from "next";

export default async function handleUpload(req: NextApiRequest, res: NextApiResponse) {
  const s3Client = new S3Client({});

  const uploadCommand = new PutObjectCommand({
    Bucket: process.env.MY_S3_BUCKET,
    Key: "test/testUpload.json",
    Body: JSON.stringify({ message: "Hello World" }),
  });

  const response = await s3Client.send(uploadCommand);

  res.status(200).json(response);
}

This code works perfectly fine on my local machine and uploads the file to S3 without any issues. However, when deployed to Vercel, I encounter an error within the @aws-sdk package.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:399:5)
    at ClientRequest.setHeader (node:_http_outgoing:663:11)
    at mod.request (/var/task/___vc/__launcher.js:90:17)
    at /var/task/node_modules/@aws-sdk/node-http-handler/dist-cjs/node-http-handler.js:70:25
    at new Promise (<anonymous>)
    at NodeHttpHandler.handle (/var/task/node_modules/@aws-sdk/node-http-handler/dist-cjs/node-http-handler.js:49:16)
    at async /var/task/node_modules/@aws-sdk/middleware-serde/dist-cjs/deserializerMiddleware.js:5:26 {
  code: 'ERR_HTTP_HEADERS_SENT',
  '$metadata': { attempts: 1, totalRetryDelay: 0 }
}

The package version being used is:

"@aws-sdk/client-s3": "3.278.0",

I have double-checked my environment variables for the S3 connection, experimented with different ways of passing the body/key of the object, attempted promise chaining instead of await, removed await altogether, and tried returning the response directly from the endpoint. Despite this, the behavior remains inconsistent as it was working previously and files were successfully uploaded to the bucket.

If you have any insights or suggestions, they would be greatly appreciated.

Answer №1

Greetings from the Vercel team member Swarnava! A solution has been implemented to address this issue.

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

What are some ways to maintain code efficiency when working with AJAX requests?

Looking at the code below, I am making two identical Ajax requests with only one line of difference. Is there a way to consolidate this into a function to maintain DRY (Don't Repeat Yourself) code? $('.searchable').multiSelect({ selecta ...

Obtaining the correct information from an array using Ionic's Angular framework

I am currently working with an array of data that contains arrays within each item. I have been able to display the data as needed, except for the IDs. Approach Show arrays within the array Retrieve the IDs of the arrays (excluding the IDs inside the ar ...

Optimizing rest service calls with $resource

I am currently learning about the $resource to utilize RESTful Web Services. For my first attempt, I created a factory like this : 'use strict'; angular.module('BalrogApp').factory('Req', ['$resource', function($r ...

Insufficient module names remaining in NPM

Starting to release modules on NPM has been on my mind, but I can't help but worry about the limited availability of sensible module names in the public domain. Is there a way to create a public NPM module that organizes all my module names within a ...

What is the method for including preset text within a search bar?

My current issue is as follows: When the searchbox is focused, it appears like this: -------------------- -------------------- Upon exiting the searchbox, a string will automatically be added to it: -------------------- Search -------------------- I a ...

The process of loading the Facebook like script using $.getScript is causing an issue where the

How can I make the Facebook like button display properly on my HTML page? I have successfully loaded scripts and divs for Twitter, Google +1 buttons, but the Facebook like button script is not displaying the button. The alert shows that the script is exec ...

Add a span tag with the class "javascript" around the index of a character within a string

Within an element, I have a string as such: <p>I like trains and planes</p> Using jQuery's .text(), I extract the text and store it in a variable. var str = $('p').text(); I aim to identify a specific character, let's sa ...

AngularJs triggers a function once two distinct https requests have been completed

If I have two HTTP requests that I need to be called asynchronously, but both must be completed before rendering my view, how can I ensure that these two separate calls are done in order to trigger a specific function? Calls 3 and 4 can continue running in ...

Excessive CPU usage caused by a patch in jQuery dealing with regular expressions

Working on a project developed by an unknown individual has presented some challenges. Without any means of contact with this person, I noticed that the browser's CPU consumption spikes significantly upon loading the page. Upon further investigation, ...

Only carry out a redirect to the specified page if the successRedirect is present in the passport.authenticate function

Encountering some difficulties with a Node Express app. After removing the successRedirect property in the auth method by passport, it fails to redirect. The below code does not redirect to the desired page when the successRedirect is removed and replaced ...

I'm encountering an issue with my React 18 application using TypeScript: the module './App' cannot be found

Encountering an issue while attempting to update to react 18. I'm curious if this problem is related to my file types. I am using Typescript, so do both the app and index files need to have a .tsx extension? Both the app and index files are located ...

React textarea trigger function on blur event

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx When working with a textarea in React, I have two main objectives: To remove focus and reset certain states when the user presses "Escape" To trigger a callback function (sa ...

Having trouble accessing the Ajax "data" parameter in Twisted

An ajax request is made using the "POST" method with these parameters: function sendDataToServer(portNumber){ console.log(portNumber) $.ajax({url: "action", dataType : 'html', type: "POST", data: portN ...

"Facing rendering issues with handlebars.js when trying to display an

I have been diligently working on trying to display an array from my running express app, but despite the lack of errors, nothing is being rendered. Take a look at my handlebars template: <h3>Registered Users:</h3> <h5>{{users}}</h5& ...

"Utilizing the power of ng-click to target specific child

I am facing an issue with my owl carousel where events are not firing on cloned items. In search of a solution, I came across a suggestion from Stack Overflow to move the event handler from the direct target to its parent element: Original code snippet: ...

Error: Validation issues detected in field functionality

My goal is to loop through a set of text fields and check if the user has input any values. However, I'm facing an issue where even though I have provided values in the text fields, it seems like they are empty. To better illustrate my problem, I have ...

Infusing JavaScript with vibrant images

I am currently facing an issue where I am trying to insert images with JavaScript attached to them. Oddly enough, it seems to work fine on Firefox but the images or icons do not display on Internet Explorer. This is how I have written the code: <a hre ...

Transmitting various pieces of information using AJAX

Is it possible to send both "credit_uri" and "address" strings in one AJAX request? Currently, only the second string is being sent. How can I include both in the data of the request? $.ajax({ url: '#{add_cards_path}', type: 'POST&apo ...

What are some solutions for troubleshooting setInterval issues?

I have a h1 element with a v-for loop that displays items from my array in the following format: <h1 v-for="(record, index) of filteredRecords" :key="index" :record="record" :class="get ...

Storing resource-intensive tasks throughout pages undergoing construction in a static build using Next.js

When utilizing the generateStaticParams function to designate which pages should be constructed statically, and these pages depend on a resource-intensive operation, how can I cache the result of that operation across all page builds? The cache and unstabl ...