1

I have a Cloudfront distribution with a S3 origin bucket (using Cloudformation/SAM to delegate resources) that's acting strangely. The S3 bucket only stores images.

Whenever I request an image through the src attribute, the network tab in dev-tools shows that the Cloudfront resource was a cache-miss (remains even after repeated refreshing). However, when sending a GET request through Postman or a browser, after one refresh I start seeing Cache-hits from the respective request sender.

Client-side, I'm using React with styled-components for the image tag. No query strings are being appended and Cloudfront has been told to disregard them as well.

Not sure if this is an issue with my Cloudformation setup or an issue with cached responses from the server, but any guidance would be much appreciated!

My template.yaml file:

UserAssetsDistributionIdentity:
    Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
    Properties:
      CloudFrontOriginAccessIdentityConfig: 
        Comment: 'Origin identity.'
  UserAssetsDistribution: 
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Origins: 
          - DomainName: // Domain name removed
            Id: user-assets-bucket
            S3OriginConfig: 
              OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${UserAssetsDistributionIdentity}'
        Enabled: 'true'
        Comment: Projects microservice to distribute user uploaded assets
        DefaultCacheBehavior: 
          AllowedMethods:
            - GET
            - HEAD
          CachedMethods: 
            - GET
            - HEAD
          CachePolicyId: b2884449-e4de-46a7-ac36-70bc7f1ddd6d
          TargetOriginId: user-assets-bucket
          ViewerProtocolPolicy: allow-all
        ViewerCertificate:
          AcmCertificateArn: // arn removed
          SslSupportMethod: sni-only
          MinimumProtocolVersion: TLSv1
        Aliases: 
          - uploads.phazia.com
  UserAssetsBucket:
    Type: AWS::S3::Bucket
    Properties: 
      AccessControl: PublicRead
Charan
  • 21
  • 7
  • 1
    Show the code used for requesting in react-side? POST request are never cached. Any differences in the query strings of the images is also not gonna result to a cache hit. – Allan Chua Jan 25 '22 at 01:44
  • The code for a client side req is just the src tag in an image element— not a fetch request. It’s sending a GET request (known from the network tag displaying that), and the query strings aren’t being changed or sent in the first place. – Charan Jan 25 '22 at 02:04

1 Answers1

0

The issue was Chrome caching response headers for repeat-requests to resources.

Devtools shows a status code of 200 for the requested resource along with a (from disk cache) message- led me to believe that the status code AND the response headers were being cached. Tried clearing the browser cache and got the expected Cloudfront header.

Charan
  • 21
  • 7