Deploying your project on AWS
Tags: aws, beginners, tutorial, webdev
Published: 2023-03-31 05:31:22

Recently, I dove into the world of AWS and wanted to get familiar with the process of deploying a project there. I will be going over deploying a brand new project as well as building and shipping an existing project on to AWS.

You can either follow along with the guide or check out the [github repo](https://github.com/binh-ngo/react-static-cdk).

## Initialize the Project
Before we even start with any coding we need to make sure we have these requirements installed.

- NodeJS with npm or yarn
- Typescript
- AWS CLI 
- CDK CLI (`npm i -g cdk`)
- Configured AWS Account (`aws configure`)

If you already have a project you want to deploy, you can skip the next section. If not, follow along.

## Create the React App

To create a react app use this command:
`npx create-react-app name-of-project --template typescript`

Then enter the directory by typing:
`cd name-of-project`

Finally, type this command to create a build folder:
`npm run build || yarn build`

## Assemble the CDK

Next, you have to create a folder called cdk, then initialize it within that folder while outputting a typescript template:
`mkdir cdk && cd cdk && cdk init app --language typescript`

Make sure that your cdk folder is in your root directory. It is a good practice to separate your folders like this to keep your repo organized.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lw5ydc6tsr9r8gs1e8x7.png)

If we enter our CDK folder, we will find three important additions:

- bin/cdk.ts
  - This is the first part of our stack and where we bootstrap our system.
- lib/cdk-stack.ts
  - Our stacks will live in this lib folder.
-cdk.json
  - This is what AWS uses to create the application. No need tamper with this.

To finish assembling the CDK, add your region to the `bin/cdk.ts` file.

```

#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from '@aws-cdk/core';
import { CdkStack } from '../lib/cdk-stack';

const app = new cdk.App();
new CdkStack(app, 'CdkStack', {
  env: {
    region: 'us-east-1' // add your region
  }
});
```
For those of us in the U.S., I recommend to use 'us-east-1' as your region. The extra latency is minimal and you don't miss out on some features since most are ran there.

## Utilize your Tools

Next, we will be introducing three tools that we will be using.
- S3 Bucket: cloud object storage for your project
- S3 Deployment: takes your project that is in the build folder and puts it into your S3 Bucket.
- CloudFront: compresses your project to speed up the delivery of your content.

First, install your dependencies so that you can use these tools: 
`npm i @aws-cdk/aws-s3 @aws-cdk/aws-s3-deployment @aws-cdk/aws-cloudfront || yarn add @aws-cdk/aws-s3 @aws-cdk/aws-s3-deployment @aws-cdk/aws-cloudfront`
```
import { RemovalPolicy, Stack, StackProps } from 'aws-cdk-lib';
import { Bucket } from 'aws-cdk-lib/aws-s3';
import { BucketDeployment, Source } from 'aws-cdk-lib/aws-s3-deployment';
import { Construct } from 'constructs';
import { CloudFrontWebDistribution } from 'aws-cdk-lib/aws-cloudfront';

export class CdkStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // S3
    const bucket = new Bucket(this, "CreateReactAppBucket", {
      publicReadAccess: true,
      removalPolicy: RemovalPolicy.DESTROY,
      websiteIndexDocument: "index.html"
    });

    // Deployment
    const src = new BucketDeployment(this, "DeployCRA", {
      sources: [Source.asset("../build")],
      destinationBucket: bucket
    });

    // Cloudfront
    const cf = new CloudFrontWebDistribution(this, "CDKCRAStaticDistribution", {
      originConfigs: [
        {
          s3OriginSource: {
            s3BucketSource: bucket
          },
          behaviors: [{isDefaultBehavior:true}]
        }
      ]
    })
  }
}

```
If you receive an error with any of the `this` parameters in your tools, make sure that all the CDK dependencies in your `package.json` file are of the same version number.

To begin describing these three tools, we can start by saying they each have the same three parameters: stack, name, and options. 

- In the first tool, the bucket belongs to `this` stack, its name is "CreateReactAppBucket", and the options are pretty self explanatory.

- The second tool is more interesting. In its options, we can assign the source of what we want to store in the bucket in the first tool either by providing a zip file or path to a directory.

- Finally, we register a subdomain in the last tool. We target the origin and we configure it by passing an S3 Origin Source. Then, we tell AWS that this is the default behavior of the Cloudfront Distribution.

## Deploying to AWS

Pay attention to these three commands that you need to deploy a CDK stack to AWS.

`cdk bootstrap` - will create a CDKToolkit Stack and deploy it to your Cloudformation. Eventually this is used to create later stacks. It also creates a `cdk.out` directory which is the code you want to deploy along with the Cloudformation template.

`cdk synth` - synthesizes your CDK App and attempt to generate any changes in your Cloudformation template.

`cdk deploy` - will attempt to deploy the contents of the `cdk.out` directory. It also makes sure that you want to create all the necessary roles and services in order to run the application.

`cdk diff` - compares the specified stack and its dependencies with the deployed stacks or a local CloudFormation template. It basically checks the differences since the last deployment. 

## This is it!
If you log into your AWS console, you will be able to see all the stacks you created and their respective resources. You can also check out Cloudfront to see if your website is working!

Make sure to use `cdk destroy` to avoid unnecessary costs.