How to Deploy a React App on AWS S3 and CloudFront

In this tutorial, you will learn how to deploy a React application on AWS using S3 for static file storage and CloudFront for content distribution. This process includes three basic steps.

Deployment Commands

1. Build the application

First, make sure your application is production-ready by generating the static files:

yarn build

This command creates a dist/ folder (or build/ depending on your setup) with all the files optimized for production.

2. Upload files to S3

Sync the generated files with your S3 bucket using the following command:

aws s3 sync dist/ s3://mi-bucket-s3 --delete --region us-east-1

This command:

  • dist/: Specifies the folder where the generated files are located.
  • s3://mi-bucket-s3: Specifies the S3 bucket where the files will be uploaded.
  • --delete: Deletes files in the S3 bucket that are no longer in your local folder.
  • --region us-east-1: Defines the region where your bucket is located.

3. Invalidate CloudFront cache

Once the files are uploaded to S3, invalidate the CloudFront cache to ensure users get the latest version:

aws cloudfront create-invalidation --distribution-id ABCD1234EXAMPLE --paths "/*"

This command:

  • --distribution-id ABCD1234EXAMPLE: Specifies your CloudFront distribution ID (replace with your own ID).
  • --paths "/*": Indicates that the entire cache should be invalidated.

Summary of commands

These are the commands needed to deploy your React application on S3 and CloudFront:

# 1. Generate static files
yarn build

# 2. Sync with S3
aws s3 sync dist/ s3://mi-bucket-s3 --delete --region us-east-1

# 3. Invalidate CloudFront cache
aws cloudfront create-invalidation --distribution-id ABCD1234EXAMPLE --paths "/*"

Additional notes

  • Make sure your AWS credentials are properly configured before running these commands.
  • The yarn build command requires Yarn to be installed and configured in your environment.
  • Replace the values mi-bucket-s3 and ABCD1234EXAMPLE with the specific names and IDs for your project.

I hope this tutorial helps you with your deployments! If you have any questions or suggestions, feel free to comment.