Search code examples
amazon-web-servicesamazon-s3corsaws-sdkcache-control

Aws-sdk s3 upload CORS error cause by CacheControl Option


My code is looks like this and when

import { FileUpload } from "../types/scalars/Upload.scalar";

 new S3.ManagedUpload({
        params: {
            ACL: "public-read",
            Bucket: process.env.AWS_BUCKETNAME || "",
            Body: upload.createReadStream(),
            Key: filename || upload.filename,
            CacheControl: "max-age=604800,public,immutable",
        },
        // tags,
    }).promise();

If I upload this with the CacheControl option, upload works fine.

But when I load it on the client side I get a CORS error.

If I remove CachControl, obviously the CORS error doesn't come up.

My Bucket has CORS-Policy like this

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "POST"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]

Headers with CacheControl Param

enter image description here

Headers without CachControl Param

enter image description here

With CacheControl param, My Allow headers are gone. Why is that?

I found some documents in here https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9


Solution

  • I had same problem.
    Did you set bucket policy in Amazon S3 actions?
    https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-with-s3-actions.html
    It worked by setting policy in my project.

    And you can check if settings works by using curl.
    The below command is check if POST request can access to a bucket.

    curl -i https://your-bucket-name.s3.your-bucket-region.amazonaws.com/index.html -H "Access-Control-Request-Method: POST" -X OPTIONS -H "Origin: http://localhost:3000"
    

    Check this link out.
    https://aws.amazon.com/jp/premiumsupport/knowledge-center/s3-configure-cors/