AWS S3 PresignedPost works locally but fails in production with ERR_CONNECTION_RESET
Asked Answered
A

2

0

I have a backend lambda function that creates the presigned post url using the code below and this works just fine returning the url as planned in both production and locally.

router.post("/file_upload", async (req, res) => {
try {
var name = `${uuidv4()}`;
var params = {
    Bucket: process.env.S3_BUCKET,
    Fields: {
        key: name, // File name you want to save as in S3,
        //acl: "public-read"
    },
    Expires: 3600,
    Conditions:[
        ["content-length-range", 0, 52428800]
    ]
};

s3.createPresignedPost(params, (err, data) => {
    if(err) {
      throw err;
    }
    Object.assign(data, { name });
    console.log(data);
    res.send(data);
});
} catch (error) {
res.status(500);
res.end(`Error: ${error}`);
console.log(error);
}
});

However when the code below executes the post request to this url I receive an error ERR_CONNECTION_RESET, this happens everytime:

let results = await triggerAWSS3("file_upload", name);
if (results && results.url && results.fields) {
  name = results.name;
  let form = new FormData();
  let keys = Object.keys(results.fields);
  await Promise.all(keys.map((key) => {
    form.append(key, results.fields[key]);
    return true;
  }));
  form.append('file', file);
  let response = '';
  try {
    //This line generates the error
    response = await Axios.post(results.url, form, { headers: { 'content-type': 'multipart/form-data' } });
    console.log(response);
  } catch (error) {
    console.log(error);
  }

And I have a public bucket policy like the one below:

{
"Version": "2012-10-17",
"Id": "http referer policy example",
"Statement": [
    {
        "Sid": "Allow get requests originating from www.example.com and example.com.",
        "Effect": "Allow",
        "Principal": "*",
        "Action": [
            "s3:GetObject",
            "s3:PutObject",
            "s3:PutObjectAcl"
        ],
        "Resource": "arn:aws:s3:::example-s3-bucket/*",
        "Condition": {
            "StringLike": {
                "aws:Referer": [
                    "https://www.example.com/*",
                    "https://example.com/*",
                    "https://localhost:3000/*"
                ]
            }
        }
    }
]
}

If anyone could help me figure out why this isn't working that would be fantastic as I have tried many different fixes to this and nothing has worked.

Ayacucho answered 24/3, 2022 at 3:27 Comment(0)
A
1

So after a few days of troubleshooting I figured out that the S3 bucket was being configured to the wrong region.

const AWS = require('aws-sdk');
const { v4: uuidv4 } = require('uuid');
const s3 = new AWS.S3();
AWS.config.update({ signatureVersion: 'v4',
                    accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY,   
                    secretAccessKey: process.env.REACT_APP_AWS_SECRET_KEY, 
                    region: process.env.REACT_APP_AWS_REGION });

I fixed it by moving the config update statement above the definition of the S3 variable. A stupid mistake, but maybe I could save someone else the time in the future.

const AWS = require('aws-sdk');
const { v4: uuidv4 } = require('uuid');
AWS.config.update({ signatureVersion: 'v4',
                    accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY,   
                    secretAccessKey: process.env.REACT_APP_AWS_SECRET_KEY, 
                    region: process.env.REACT_APP_AWS_REGION });
const s3 = new AWS.S3();
Ayacucho answered 29/3, 2022 at 3:50 Comment(0)
I
0

In my case I forgot to add my AWS environment variables to Vercel.

Impatient answered 30/3, 2023 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.