11/09/2019

Deploy React app to AWS S3 in 5 mins

This post is just to show how to deploy React app to AWS S3, it does not include setting up CloudFront(CDN) and Route 53(Domain name). After going through the below steps, you should be able to deploy your react app to s3 quickly and easily. At the end of the post, there is a handy command that you can redeploy your static website next time. Here, I try to use as many screenshots as possible to show you how it works.

Step 1: Build and bundle your app

In your React app which is built with FB's create-react-app, it has a command to bundle the app out of the box:
npm run build

After running this command, it will generate a "build/" folder. Then, our goal is to upload this to S3.


Step2: Set up S3 bucket

Before doing this, please make sure you have an AWS account. If you already had an AWS account, then visit AWS S3 after entering the console: https://console.aws.amazon.com.

Click "Create bucket" button
Specify the bucket name whatever you want. Here I specified "myreactdemo" to the bucket name

Set up Block public access setting which can be changed afterward if you want. You can keep clicking next button.

Then, you will see the bucket is created
Go inside the newly created bucket, upload all contents under the "build" folder to this S3 bucket

Click Properties tab and enable static website hosting(Properties/Static website hosting). Also, specify index.html to index document and Error document fields. At the same time, copy the endpoint which will be the URL of your website.


However, after setting up this, it still demands permissions setting. Otherwise, you will see 403 error if you open the URL.


Let's fix this 403 error by changing the policy. Copy the below snippet of code to Bucket policy editor, but remember to change to your bucket name instead of mime(myreactdemo)


{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AddPerm",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::[YOUR S3 BUCKET NAME]/*"
        }
    ]
}

After done with the permissions, you should be able to see PUBLIC access for your S3 bucket, then you can try to access the URL again. It should work fine.




Step 3: Redeploy

The above steps require uploading manually, you can consider using aws cli or s3cmd to make it be automatic. For instance, I use aws cli to deploy this to S3 without visiting aws console:

npm run build && aws s3 ls && aws s3 sync build/ s3://[BucketName]

Besides, you can consider hooking this up to your CI/CD like AWS CodePipeline