How to Deploy a React.js Web App to AWS
Here in this blog, we are going to learn how to deploy a React.js web App to AWS.
Deploying a React.js web application to AWS (Amazon Web Services) provides a scalable, reliable infrastructure for running your app. This guide will walk you through the steps to deploy your React app to AWS S3 (Simple Storage Service) and configuring it with AWS CloudFront for fast global content delivery.
-
Build Your React App
Before deploying, you need to build your React application into static files using the following command
npm run build
This command will generate a `build/` folder containing optimized HTML, CSS, and JavaScript files. These static assets are ready for deployment.
-
Create an S3 Bucket
To create a new bucket, log into your AWS Management Console and select the S3 service:
- Click Create Bucket.
- Give your bucket a distinctive name, such as {my-react-app}.
- The place closest to your users should be chosen.
- Uncheck the “Block all public access” setting, as the app needs to be publicly accessible.
After the bucket is created, upload the contents of the `build/` folder into the S3 bucket.
-
Set up S3 Bucket Static Hosting Configuration
Once the files are uploaded, configure the bucket for static website hosting:
- Open the bucket and select the Properties tab.
- Under Static website hosting, select Enable.
- Set the index document to `index.html` and the error document to `index.html` (this is necessary for client-side routing in React apps).
Copy the Endpoint URL provided. This URL will be used to access your React app.
-
Set Permissions
To make the bucket publicly accessible:
- Go to the Permissions tab.
- Click Bucket Policy and paste the following JSON policy, replacing `your-bucket-name` with your actual bucket name:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::your-bucket-name/*" } ] }
This policy allows public read access to the files in your bucket.
-
Set Up AWS CloudFront (Optional)
For better performance and security, configure CloudFront, AWS’s content delivery network (CDN):
- Open the AWS Console and navigate to CloudFront.
- Create a new distribution, and set your S3 bucket as the origin.
- Make necessary customizations or use the default settings.
Once configured, CloudFront will provide a global distribution URL for faster content delivery.
-
Test Your Deployment
Visit the S3 or CloudFront URL in your browser to ensure your React.js web app is running correctly.
Conclusion
Deploying a React.js web app to AWS using S3 and CloudFront ensures that your application is fast, reliable, and scalable. AWS S3 provides a cost-effective way to host static web applications, and when combined with CloudFront, delivers a superior user experience across the globe.