DEV Community

Cover image for Day 76: Supercharging my React App with AWS CloudFront CDN
Eric Rodríguez
Eric Rodríguez

Posted on

Day 76: Supercharging my React App with AWS CloudFront CDN

Today I tackled one of the most common UI annoyances: slow-loading profile pictures.

My serverless financial app uses AWS S3 to store user avatars. It works perfectly, but S3 object URLs can be slow to resolve depending on where the user is physically located.

(The Upgrade: Amazon CloudFront)
To fix this, I put a CDN in front of my bucket. I created a CloudFront distribution pointing to my S3 origin. This allows AWS to cache the images at edge locations globally. If a user in Spain requests their avatar, it is served from a local cache rather than traveling all the way to my bucket in Sweden.

(The Backend Fix)
I updated my Python Lambda function so that when a user uploads a new photo, the backend returns the new cloudfront.net URL instead of the raw S3 endpoint.

(The Frontend Fix)
To make it even faster, I implemented a local caching strategy in React. I mapped my useState hook for the avatar to localStorage. Now, the browser remembers the CloudFront URL instantly on page load, eliminating the awkward UI flash while React waits for the API response.

Next time you use S3 for public assets, put CloudFront in front of it. Your users (and your bandwidth bill) will thank you!

Top comments (0)