Search code examples
reactjsamazon-s3amazon-cloudfront

Deploying reactjs based application to AWS


I have deployed a ReactJS based application to AWS S3 bucket. Additionally, I had to use CloudFront due to react-router issues, please see S3 Static Website Hosting Route All Paths to Index.html. Now, with CloudFront I have to re-create the distribution when I change endpoints (e.g. API host, callback URL etc), is this the way it works?


Solution

  • No you don't have to re-create Cloudfront distribution.

    A common practice is to append a hash to the static asset, eg:

    <script src="myapp.bundle.js?v=12345678"></script>
    

    The hash is usually the MD5/SHA1 hash of the file. Some may use the timestamp of the time you build the code. So after you update the file content and issue a new deploy, a new hash should be used. Consider the following flow as the client:

    1. A client requests for myapp.bundle.js?v=1
    2. Cache does not exist yet, Cloudfront proxies the request to S3 directly and caches the content.
    3. Cloudfront serves cached content to myapp.bundle.js?v=1 for any subsequent requests.
    4. Now you updated your code and deployed to S3 (with a new hash in your index.html).
    5. Clients now request myapp.bundle.js?v=2 instead
    6. repeat 2-3 and so on

    The hash appending is usually done by build tool such as gulp and webpack with plugins.