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.