Guide to deploying a React application on AWS Amplify

Introduction

AWS Amplify is a complete development framework provided by Amazon Web Services (AWS) that helps developers build, deploy, and manage Full-stack web and mobile applications quickly.

Instead of having to manually configure each individual AWS service, Amplify acts as an intelligent "manager," integrating tools and libraries to connect your application to cloud infrastructure in just minutes.

Key Advantages

  • Ultra-fast development speed (Speed): Amplify provides a Command Line Interface (CLI) and ready-to-use UI components for common features such as Authentication, Storage, and APIs.
  • You don’t need to be a cloud infrastructure expert to set up a complex Backend.
  • Seamless Full-stack integration: This platform allows you to build both Frontend (React, Vue, NextJS) and Backend synchronously. Data management between the client and the cloud becomes seamless thanks to automatic Code Generation capabilities.
  • Automated CI/CD workflow: Amplify Hosting supports Git-based workflows. When you push code to GitHub or GitLab, the system automatically builds and deploys your application to Amazon's global CDN network, ensuring fast access speeds for users.
  • Powerful scalability: Because it is built on AWS foundations (such as Lambda, AppSync, S3, Cognito), your application can easily scale from a few users to millions of users without changing the core architecture.
  • Offline support (Offline sync): With Amplify DataStore, applications can function normally even when network connection is lost and automatically synchronize data when the connection returns.


Prerequisites

The React project I created previously using Vite; you can review this article to get the code or use any React project of your choice, as long as it can be successfully built into static files.


Detail

First, create the file lib/amplify-stack.ts

import * as cdk from "aws-cdk-lib"
import { Construct } from "constructs"
import * as amplify from "@aws-cdk/aws-amplify-alpha"
import * as amplifyLib from "aws-cdk-lib/aws-amplify"
import { Asset } from "aws-cdk-lib/aws-s3-assets"
import * as path from "path"

export class AmplifyDeployReactStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props)

    const asset = new Asset(this, "ViteAsset", {
      path: path.join(__dirname, "../path-to-dist/dist"),
    })

    const amplifyApp = new amplify.App(this, "MyViteApp", {
      appName: "React Vite Deployed via CDK",
      customRules: [
        {
          source:
            "</^[^.]+$|\\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|woff2|ttf|map|json)$)([^.]+$)/>",
          target: "/index.html",
          status: amplify.RedirectStatus.REWRITE,
        },
      ],
    })

    // 2a. Thêm custom headers qua CfnApp
    const cfnApp = amplifyApp.node.defaultChild as amplifyLib.CfnApp
    cfnApp.customHeaders = `
      customHeaders:
        - pattern: '**/*.{js,css,png,jpg,jpeg,gif,svg,ico,woff,woff2,ttf}'
          headers:
            - key: 'Cache-Control'
              value: 'public, max-age=31536000, immutable'
        - pattern: 'index.html'
          headers:
            - key: 'Cache-Control'
              value: 'public, max-age=0, must-revalidate'
    `

    const mainBranch = amplifyApp.addBranch("main", {asset})

    new cdk.CfnOutput(this, "AppUrl", {
      value: `https://${mainBranch.branchName}.${amplifyApp.defaultDomain}`,
      description: "The URL of the deployed React Vite app",
    })
  }
}

  • asset: specify the path to the dist folder after a successful build
  • customRules: used to resolve errors when using React Router upon reloading the page
  • customHeaders: cache config; I set the time to 31536000ms=1 year. Amplify supports CDN and automatic caching by default, but you can configure it specifically like this


Then update the file bin/aws-cdk.ts as follows:

#!/usr/bin/env node
import * as cdk from "aws-cdk-lib/core"
import { AmplifyDeployReactStack } from "../lib/amplify-stack"

const app = new cdk.App()
new AmplifyDeployReactStack(app, "AmplifyDeployReactStack")


Results after successful deployment

 AmplifyDeployReactStack
 Deployment time: 187.13s

Outputs:
AmplifyDeployReactStack.AppUrl = https://main.dka3atdag2mlz.amplifyapp.com
 Total time: 250.95s


Resources created on the AWS console


Please access the web URL to see the results


Cache is also working as configured


Happy coding!

See more articles here.

Comments

Popular posts from this blog

All practice series

Deploying a NodeJS Server on Google Kubernetes Engine

Setting up Kubernetes Dashboard with Kind

Using Kafka with Docker and NodeJS

Monitoring with cAdvisor, Prometheus and Grafana on Docker

Kubernetes Practice Series

Kubernetes Deployment for Zero Downtime

Practicing with Google Cloud Platform - Google Kubernetes Engine to deploy nginx

NodeJS Practice Series

Helm for beginer - Deploy nginx to Google Kubernetes Engine