The easiest way to deploy a React Application on AWS with Terraform

Vikas Yadav
CodeX
Published in
2 min readJan 29, 2024

--

Introduction

A React application is just a collection of js, css and html files when built.

In this blog I am going to share how you can deploy a simple React application on AWS, leveraging the power of Terraform for automation. This guide is perfect for those who want to understand the basics of deploying a react application and how we can leverage terraform’s automation power to automate the whole process.

Overview

React is a popular JavaScript library for building user interfaces, while AWS S3 and CloudFront offer robust cloud hosting solutions. Terraform enables us to automate the deployment process efficiently.

Setting up React Application

We start by creating a React application using create-react-app. We will create a simple hello-world application.

create-react-app react-demo 
cd react-demo

In our case, we use it to set up AWS S3, a storage service, and CloudFront, a content delivery network, ensuring our application is both stored and delivered efficiently.

Terraform Configuration

Terraform allows us to define and provision infrastructure using a high-level configuration language.

Create a directory

mkdir terraform 
cd terraform

In the directory create the following files

terraform
├── providers.tf
├── s3.tf
├── terraform.tfvars
└── variables.tf

You can get the contents of this file from: https://github.com/vik-y/react-aws-terraform/tree/main/terraform

Our Terraform configuration includes setting up an S3 bucket with default permissions and a CloudFront distribution.

Deploy the infra

Change the bucket name in terraform.tfvars file. Then

terraform apply 

Building and Deploying the Application

Once our React app is ready, we run npm run build to create a production build. Then, we use Terraform to deploy our AWS infrastructure. After the infrastructure is set up, we upload our build to the S3 bucket using the AWS CLI.

aws s3 cp build s3://<bucket-name> --recursive --acl public-read

Verifying the Deployment

To check if our application is live, we simply visit the CloudFront URL. If everything is set up correctly, our React application should be proudly displayed.

Conclusion

Deploying a React application on AWS using Terraform is simple. By deploying on cloudfront+s3 stack — you essentially don’t require any server. Cloudfront can heavily cache your assets and improve the performance of your application drastically.

Additional Resources

For those interested, the complete code and detailed README can be found in my Github Repo. I also recommend checking out AWS and Terraform documentation for more in-depth knowledge.

You can also checkout the full loom video here: https://www.loom.com/share/6d6c154d5b64448ab5739fb85ee3de19

--

--