Deploying React Applications on AWS
A guide to deploying React applications on AWS using CloudFront and S3, using CDK Nodejs for infrastructure as code.
Prerequisites
Before starting, ensure you have the following prerequisites:
- AWS Account: Sign up for an AWS account if you don't have one.
- AWS CLI: Install and configure the AWS Command Line Interface (CLI) with your credentials. You can follow the guide here.
- Node.js and yarn: Ensure you have Node.js and yarn installed on your machine.
- React Application: Have a React application ready for deployment.
Step 1: Set Up IaC project
- Navigate to your react application directory in the terminal.
- Create a new directory for your IaC project and navigate into it:
-
Initialize a new CDK project using Node.js:
-
Install the necessary AWS CDK packages:
Step 2: Update the IaC code to create an S3 bucket.
- Open the
lib/iac-stack.ts
file in your IaC project directory. - Replace the contents with the following code to create an S3 bucket and a CloudFront distribution
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
import * as s3deploy from 'aws-cdk-lib/aws-s3-deployment';
export class IacStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Create an S3 bucket
const bucket = new s3.Bucket(this, 'MyReactAppBucket', {
websiteIndexDocument: 'index.html',
websiteErrorDocument: 'index.html',
publicReadAccess: true,
});
// Create a CloudFront distribution
const distribution = new cloudfront.CloudFrontWebDistribution(this, 'MyReactAppDistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: bucket,
},
behaviors: [{ isDefaultBehavior: true }],
},
],
});
}
}
Step 3: Build and Deploy the React Application
- Navigate back to your React application directory.
- Build your React application:
- Navigate back to your IaC project directory.
- Deploy the CDK stack to create the S3 bucket and CloudFront distribution:
- After the stack is deployed, note the S3 bucket name and CloudFront distribution domain name from the output.
- Deploy the built React application to the S3 bucket:
- Invalidate the CloudFront cache to ensure the latest version of your application is served:
- Access your React application using the CloudFront distribution domain name.
Step 4: Clean Up
To avoid incurring unnecessary charges, remember to delete the resources created during this process when they are no longer needed. You can do this by destroying the CDK stack: