Angular Deployment on AWS: The Ultimate S3 + CloudFront Guide with CDK

Angular Deployment on AWS: The Ultimate S3 + CloudFront Guide with CDK

Deploying an Angular Single Page Application (SPA) on AWS doesn’t have to be complicated. Forget manual console configuration; we are going to build a Serverless infrastructure, secured by OAC and optimized by CloudFront, all without depending on Route 53.

Prerequisites

Before starting, you will need:

BASH
aws configure
Click to expand and view more
BASH
npm install -g aws-cdk
Click to expand and view more

1. Project Structure

For clean management, we will group the application and the infrastructure into a single root folder. This “Monorepo” approach is a best practice.

SQL
/host-anglar-app
├── /frontend          --------------> Application Angular
└── /infrastructure    --------------> Code AWS CDK
Click to expand and view more

Create the folders and the Frontend

SH
mkdir host-anglar-app && cd host-anglar-app
# creation de l'application angular
ng new frontend
Click to expand and view more

Initialize the Infrastructure

SH
mkdir infrastructure && cd infrastructure
# Initialisation du CDK
cdk init app --language typescript
Click to expand and view more

2. Le code de l’Infrastructure (CDK)

Open infrastructure/lib/infrastructure-stack.ts. This script creates the S3 bucket and the CloudFront distribution. It also automatically handles security so that only CloudFront can access your S3 files.

TS
import * as cdk from 'aws-cdk-lib/core';
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';
import * as origins from 'aws-cdk-lib/aws-cloudfront-origins';


export class InfrastructureStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    // S3 bucket to host the Angular app
    const bucket = new s3.Bucket(this, "AngularAppBucket", {
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      autoDeleteObjects: true,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      bucketName: 'angular-app-bucket-example-123456' // Change to a globally unique name
    });

    // CloudFront distribution to serve the Angular app
    const distribution = new cloudfront.Distribution(this, "AngularAppDistribution", {
      defaultBehavior: {
        origin: origins.S3BucketOrigin.withOriginAccessControl(bucket),
        viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
      },
      defaultRootObject: "index.html",
      // Ajoutez ceci pour gérer le rafraîchissement des pages Angular
      errorResponses: [
        {
          httpStatus: 403,
          responseHttpStatus: 200,
          responsePagePath: '/index.html',
        },
      ],
    });

    // Deploy the Angular app to the S3 bucket
    new s3deploy.BucketDeployment(this, "DeployAngularApp", {
      sources: [s3deploy.Source.asset("../frontend/dist/frontend/browser")],
      destinationBucket: bucket,
      distribution,
      distributionPaths: ["/*"],
    });

    // Output the CloudFront distribution domain name
    new cdk.CfnOutput(this, "DistributionDomainName", {
      value: distribution.domainName,
    });

  }
}
Click to expand and view more

3. One-Click Deployment

To automate the build and deployment, we will create a custom command. In the infrastructure folder, we add a script to package.json:

JSON

  "deploy:all": "cd frontend && ng build && cd ../infrastructure && cdk deploy"
Click to expand and view more

Now, a single command is enough:

BASH
npm run deploy:all
Click to expand and view more

The output will provide the CloudFront URL to access your application: https://xxxxxxxxxxx.cloudfront.net/

4. Pointing your domain (Without Route 53) - Bonus

If you already have a domain with OVH, GoDaddy, or another provider, simply create a CNAME record:

5.Nettoyer

To stop incurring costs once your tests are finished:

SH
cdk destroy
Click to expand and view more

Comments

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut