Forem

Saddam Azad
Saddam Azad

Posted on

Deploy React + Vite on AWS S3 and CloudFront: A Complete Guide

Now that Create React App (CRA) is being deprecated, the easiest way to get started with React is with Vite.

Introduction

Vite is a next-generation frontend tooling that offers a fast development experience for modern web projects, including those built with React. When it comes to deploying your application, AWS provides scalable and reliable infrastructure, but setting it up can be complex.

When it comes to deploying your application, Amazon Web Services (AWS) offers scalable and reliable infrastructure solutions. However, setting up the necessary services—like S3 buckets, CloudFront distributions, and CI/CD pipelines—can be complex and time-consuming.

That's where the CDK-SPA library comes into play. CDK-SPA leverages the AWS Cloud Development Kit (CDK) to automate the provisioning of AWS resources required for hosting static site generators (SSG) and single-page applications (SPAs). This simplifies the deployment process, allowing you to focus more on developing your application and less on managing infrastructure.

The library uses AWS S3 for hosting with CloudFront CDN.

Hosting React S3 CloudFront

The library also configures a webhook in your Github to autodeploy using AWS CodeBuild and CodePipeline.

Github CodeBuild CodePipeline

In this guide, we'll walk through deploying a React + Vite application on AWS using CDK-SPA.

Github repo Stackblitz demo

Prerequisites

Before you begin, make sure you have the following:

  • An AWS Account: Sign up for an AWS account if you don't have one.
  • Node.js and npm: Ensure you have Node.js (v18 or later) and npm installed.
  • AWS CLI: Install and configure the AWS Command Line Interface.
  • Before deploying, bootstrap your AWS environment:
cdk bootstrap aws://your-aws-account-id/us-east-1
Enter fullscreen mode Exit fullscreen mode
  • AWS CDK: Install the AWS CDK globally
npm install -g aws-cdk
Enter fullscreen mode Exit fullscreen mode

Staring a New Project

Create a new React project with Vite and TypeScript.

New Project in Stackblitz

Here's the step-by-step process:

Open your terminal and run the following command to create a new project:

pnpm create vite@latest 
Enter fullscreen mode Exit fullscreen mode
  • Enter your project name
  • Select "React" as your framework
  • Choose "TypeScript" as your variant

Create GitHub Personal Access Token

Here's how to create a GitHub Personal Access Token (PAT):

  • Go to your GitHub account settings.
  • Navigate to Developer settings > Personal access tokens.
  • Click on Generate new token.
  • Choose Tokens (classic).
  • Give the token a descriptive name.
  • Set the expiration to No expiration (ignore the warning, for now).
  • Select the scopes (permissions):
    • repo: Full control of private repositories.
    • admin:repo_hook: Full control of repository hooks.
  • Click Generate token.

Important: Copy the token immediately and store it securely. You won't be able to see it again. If you lose it, you'll need to generate a new one.

Store the Token in AWS Secrets Manager

Use the AWS CLI to create a new secret in AWS Secrets Manager:

aws secretsmanager create-secret --name your-secret-name --secret-string your-token
Enter fullscreen mode Exit fullscreen mode
  • Replace your-secret-name with a name for your secret.
  • Replace your-token with your actual GitHub token.
  • The command will return something like this:
{
    "ARN": "arn:aws:secretsmanager:us-east-1:665186350000:secret:your-secret-token-VgnkyF",
    "Name": "your-secret-name",
    "VersionId": "b1a532d2-4434-42a3-9283-41581be07455"
}
Enter fullscreen mode Exit fullscreen mode

Take note of the ARN.

Note: Storing secrets in AWS Secrets Manager may incur a cost (around $0.40 per month).

Setting Up the Project

Navigate to your project directory and install the project dependencies:

pnpm install
Enter fullscreen mode Exit fullscreen mode

Install the CDK-SPA library and AWS CDK as development dependencies:

pnpm install --save-dev @thunderso/cdk-spa aws-cdk-lib@2.150.0 tsx
Enter fullscreen mode Exit fullscreen mode

Run the following command to create the CDK stack entry point:

npx cdk-spa-init
Enter fullscreen mode Exit fullscreen mode

This will generate a stack directory with an index.ts file, which defines how your app will be deployed via CDK.

Configure the Stack

Edit stack/index.ts and replace placeholders with your actual configuration.

import { App } from "aws-cdk-lib";
import { SPAStack, type SPAProps } from "@thunderso/cdk-spa";

const appStackProps: SPAProps = {
  env: {
    account: 'your-aws-account-id', // Replace with your AWS Account ID
    region: 'us-east-1', // Or your preferred region
  },
  application: 'my-app',
  service: 'web',
  environment: 'prod',

  sourceProps: {
    owner: 'cloudbitsio', // GitHub username or organization
    repo: 'vite-react', // Repository name
    branchOrRef: 'main', // Branch to deploy
    rootdir: '', // Root directory if not at the repo root
  },

  buildProps: {
    runtime: 'nodejs',
    runtime_version: '20',
    installcmd: 'npm ci',
    buildcmd: 'npm run build',
    outputdir: 'dist/',
  },

  githubAccessTokenArn: 'arn:aws:secretsmanager:us-east-1:665186350000:secret:your-secret-token-VgnkyF',

};

new SPAStack(
  new App(),
  `${appStackProps.application}-${appStackProps.service}-${appStackProps.environment}-stack`,
  appStackProps
);
Enter fullscreen mode Exit fullscreen mode
  • Set githubAccessTokenArn in your stack/index.ts to the ARN of the secret you just created.

Deploy the Application

Use the CDK CLI to deploy your application:

npx cdk deploy --require-approval never --all --app="npx tsx stack/index.ts"
Enter fullscreen mode Exit fullscreen mode

If you have multiple AWS profiles, select your profile to match your stack configuration.

npx cdk deploy --require-approval never --all --app="npx tsx stack/index.ts" --profile default
Enter fullscreen mode Exit fullscreen mode

Access Your Application

Use the CloudFront URL provided in the deployment outputs to access your app. It will look something like https://d1234567890abcdef.cloudfront.net.

Additional Resources

Troubleshooting

  • Deployment Failures:
    If the deployment fails, check the AWS CloudFormation console for stack events to identify the issue. Common problems include missing permissions, incorrect configuration, or resource conflicts.

  • Access Denied Errors:
    Ensure your AWS credentials have the necessary permissions. You may need to adjust IAM policies or roles to grant appropriate access.

Conclusion

Congratulations! You've successfully deployed a React application on AWS using CDK-SPA. This setup automates the deployment process, allowing you to focus on developing your application rather than managing infrastructure.

In Part 2, we will go in-depth into Custom Domains.

In Part 3, we will do custom Redirects, URL Rewrites and Cache headers.

Top comments (0)