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 origins from 'aws-cdk-lib/aws-cloudfront-origins'; export class BetaSupplierSiteStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // 1. Create S3 Bucket for Website hosting const websiteBucket = new s3.Bucket(this, 'BetaSupplierSiteBucket', { bucketName: `betasuppliersite-${this.account}-${this.region}`, removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true, blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, // Secure by default, OAI will be used encryption: s3.BucketEncryption.S3_MANAGED, }); // 2. Create CloudFront Distribution // origins.S3Origin will automatically create an Origin Access Identity (OAI) // and update the S3 bucket policy to allow access only from this CloudFront distribution. const distribution = new cloudfront.Distribution(this, 'BetaSupplierSiteDistribution', { defaultRootObject: 'index.html', defaultBehavior: { origin: new origins.S3Origin(websiteBucket), viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS, allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD, cachedMethods: cloudfront.CachedMethods.CACHE_GET_HEAD, cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED, }, errorResponses: [ { httpStatus: 404, responseHttpStatus: 200, // Return 200 for SPAs responsePagePath: '/index.html', ttl: cdk.Duration.seconds(0), }, { httpStatus: 403, responseHttpStatus: 200, // Return 200 for SPAs responsePagePath: '/index.html', ttl: cdk.Duration.seconds(0), } ] }); // Outputs new cdk.CfnOutput(this, 'BetaSupplierSiteBucketName', { value: websiteBucket.bucketName, description: 'The name of the S3 bucket for the betasupplier site', }); new cdk.CfnOutput(this, 'BetaSupplierSiteCloudFrontDomainName', { value: distribution.distributionDomainName, description: 'The domain name of the CloudFront distribution for betasupplier site', }); } }