Search code examples
amazon-s3axiosnext.js13pre-signed-url

Access to file in S3 with Next.JS application via pre-signed URL does not work - blocked by CORS


I have created a pre-signed URL to a file in an S3 bucket to use it in my application. When I enter the pre-signed URL in the browser or call it in Powershell with curl I get the file back directly, which works as expected. But if I do the same in my application with an axios.get (code below) I get an error and no access to the file, blocked by the CORS.

I'm very new to AWS, but the S3 documentation says, as I understand it, that you can also get files via a program and without restriction by policies. "use presigned URLs to grant time-limited access to objects in Amazon S3 without updating your bucket policy. A presigned URL can be entered in a browser or used by a program to download an object."

What have I misunderstood/implemented incorrectly?

export async function handleS3(url: string) {
  axios
    .get(url)
    .then((response) => {
      // Hier verarbeiten wir die Antwort vom Server
      console.log('Daten erfolgreich geladen:', response.data);
    })
    .catch((error) => {
      // Fehlerbehandlung, falls die Anfrage fehlschlägt
      console.error('Fehler beim Laden der Daten:', error);
    });
}

This is the error I get in the console: Access to XMLHttpRequest at 'pre-signed URL' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


Solution

    1. Go to S3 console
    2. Click the S3 bucket where you've hosted you html page
    3. Click Permissions and Scroll and Goto the Cross-origin resource sharing (CORS) section

    There you can see the CORS policy for that selected bucket.

    If the localhost is not allowed there then click edit and update there.

    The CORS policy looks something like this, you have to update the AllowedOrigins

    [
        {
            "AllowedHeaders": [
                "*"
            ],
            "AllowedMethods": [
                "PUT",
                "POST",
                "DELETE"
            ],
            "AllowedOrigins": [
                "http://www.example.com"
            ],
            "MaxAgeSeconds": 3000
        }
    ]