reactjsamazon-web-servicesamazon-s3axiospre-signed-url

I want to read the content of pre-signed s3 urls


When a user requests data from my server, I retrieve three S3 links from the database. These links point to objects with various content types, such as data.json, page.html, and image.jpeg. Since my S3 bucket isn't public, I generate pre-signed URLs for these objects before sending them to the UI.

However, when attempting to load these pre-signed URLs in a browser, instead of displaying the content directly, the objects are downloaded. Strangely, the browser can render image.jpeg on the UI, but it fails to display the content of page.html or data.json.

In my React app, I use Axios to fetch the content of these URLs, and then render it on the page:

export const getS3Data = async (url) => {
  try {
    const response = await axiosInstance.get(url);
    return response;
  } catch (error) {
    console.log(error);
    return null;
  };
};

I generate my pre-signed URLs at server side as below:

params = {
    'Bucket': bucket_name,
    'Key': object_key,
    'ResponseContentDisposition': 'inline'  # Set to inline to display content in browser
}

# Setting expiration time as 7 days
pre_signed_url = s3_client.generate_presigned_url('get_object', Params=params , ExpiresIn=604800)

But unfortunately I can not view the rendered content. And to cross check when i hit the pre-signed s3 link on browser it downloads the file and not showing the content.

At this point, I'm uncertain where the issue lies. It's unclear whether the problem stems from generating the pre-signed URLs incorrectly or if there's an error in how I'm accessing them via Axios or the browser settings. Any guidance you could provide would be greatly appreciated.

I tried the below things

  1. Tried various parameters while generating preassigned URLS. such as 'ResponseContentType':'application/json'
  2. Tried changing metadata (MIME type) of the s3 object by changing its content type to "application/JSON", "text/plain" and other suitable types
  3. Tired of changing my Axios return as a response.data instead of response

Solution

  • Got the solution. After checking the network tab on browser, i saw the required Request Headers were not present so generating CORS error. After adding required Cross-origin resource sharing (CORS) settings in bucket permissions the CORS error got resolved and could view the contnet.

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

    Note: I did not checked the CORS setting at first step because i was already able to load the image from the same bucket but other content was not getting loaded, and also some times browser throw CORS error for many reasons so avoided it.