Skip to content

geoicons/serverless-webhosting

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Serverless Web Hosting with AWS CDK

A serverless web hosting infrastructure solution built with AWS CDK (Cloud Development Kit) that deploys static websites to S3 and distributes them globally via CloudFront CDN. This project supports both React and Vue.js frontends with automated deployment pipelines.

🎯 Overview

This project provides a complete Infrastructure as Code (IaC) solution for hosting static websites on AWS. It automatically provisions and configures:

  • S3 Buckets for storing frontend assets and public files
  • CloudFront Distribution for global content delivery with HTTPS
  • Origin Access Identity (OAI) for secure S3 access
  • Environment-specific configurations (development, production)
  • Automated asset deployment from your built frontend applications

✨ Features

  • πŸš€ Serverless Architecture - No servers to manage, pay only for what you use
  • 🌍 Global CDN - CloudFront distribution for low-latency content delivery worldwide
  • πŸ”’ Secure by Default - HTTPS redirection and private S3 buckets with OAI
  • 🎨 Multi-Framework Support - Choose between React or Vue.js frontends
  • πŸ”„ SPA Routing Support - Proper error handling for client-side routing (404/403 β†’ index.html)
  • πŸ—οΈ Infrastructure as Code - Version-controlled infrastructure with AWS CDK
  • πŸ”§ Environment Management - Separate configurations for dev/test/prod environments
  • ⚑ Optimized Caching - CloudFront caching policies for improved performance

πŸ“‹ Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v20 or later) and Yarn package manager
  • AWS CLI configured with appropriate credentials
  • AWS CDK CLI - Install globally with npm install -g aws-cdk
  • An AWS Account with appropriate permissions to create:
    • S3 Buckets

    • CloudFront Distributions

    • IAM Roles and Policies

AWS Credentials Setup

Configure your AWS credentials using one of these methods:

# Method 1: Using AWS CLI
aws configure

# Method 2: Environment variables
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export AWS_DEFAULT_REGION="ap-southeast-2"

πŸš€ Quick Start

1. Install Dependencies

# Install root dependencies and both frontend dependencies
yarn installall

# Or install individually
yarn install              # CDK dependencies
yarn installreact         # React frontend dependencies
yarn installvue           # Vue frontend dependencies

2. Build Your Frontend

# Build all frontends
yarn buildall

# Or build individually
yarn buildreact           # Build React frontend
yarn buildvue             # Build Vue frontend

3. Configure Your Deployment

Set environment variables to customize your deployment:

# Optional: Set stack name (defaults to "RequestRocket-website-test")
export STACK_NAME="my-website-stack"

# Optional: Set stage (defaults to "dev")
export STAGE="prod"

# Optional: Set AWS region (defaults to "ap-southeast-2")
export RESOURCE_REGION="us-east-1"

4. Deploy to AWS

# Compile TypeScript and deploy
yarn build
yarn deploy

# Or use CDK commands directly
cdk synth                 # Preview CloudFormation template
cdk diff                  # Preview changes
cdk deploy                # Deploy to AWS

After deployment, the CloudFront URL will be displayed in the output. Your website will be accessible at:

https://[distribution-id].cloudfront.net

πŸ“ Project Structure

serverless-webhosting/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app.ts                    # Main CDK application entry point
β”‚   β”œβ”€β”€ jsonrest_service.ts       # Main service construct
β”‚   β”œβ”€β”€ stack/
β”‚   β”‚   β”œβ”€β”€ buckets.ts            # S3 bucket configurations
β”‚   β”‚   β”œβ”€β”€ cloudfront.ts         # CloudFront distribution setup
β”‚   β”‚   └── utilities.ts          # Helper functions
β”‚   β”œβ”€β”€ reactfrontend/            # React application
β”‚   β”‚   β”œβ”€β”€ src/                  # React source files
β”‚   β”‚   β”œβ”€β”€ dist/                 # Build output (generated)
β”‚   β”‚   └── package.json
β”‚   β”œβ”€β”€ vuefrontend/              # Vue application
β”‚   β”‚   β”œβ”€β”€ src/                  # Vue source files
β”‚   β”‚   β”œβ”€β”€ dist/                 # Build output (generated)
β”‚   β”‚   └── package.json
β”‚   └── public/                   # Static assets (logos, images, etc.)
β”œβ”€β”€ package.json                  # Root package configuration
β”œβ”€β”€ cdk.json                      # CDK configuration
β”œβ”€β”€ tsconfig.json                 # TypeScript configuration
└── README.md                     # This file

🎨 Frontend Development

React Frontend

# Navigate to React frontend
cd src/reactfrontend

# Development server
yarn dev                  # Starts on http://localhost:5173

# Build for production
yarn build

# Preview production build
yarn preview

Vue Frontend

# Navigate to Vue frontend
cd src/vuefrontend

# Development server
yarn dev                  # Starts on http://localhost:5173

# Build for production
yarn build

# Preview production build
yarn preview

βš™οΈ Configuration

Choosing Between React and Vue

In src/jsonrest_service.ts, line 32, specify which frontend to deploy:

const { frontendBucket, publicBucket, ... } = createBuckets(
    this,
    stack_name,
    stage,
    prefix,
    "vue"  // Change to "react" for React frontend
);

Environment Stages

The project supports different stages with automatic resource management:

  • Development/Test (dev): Resources are automatically deleted when stack is destroyed
  • Production (prod): Resources are retained for safety

Stack Naming Convention

Resources are named using the pattern:

{STACK_NAME}-{RESOURCE_REGION}-{STAGE}-{RESOURCE_TYPE}

Example: my-website-ap-southeast-2-prod-frontend

πŸ”§ AWS CDK Commands

# List all stacks
cdk list

# Synthesize CloudFormation template
cdk synth

# Compare deployed stack with current state
cdk diff

# Deploy stack
cdk deploy

# Deploy without approval prompts
cdk deploy --require-approval never

# Destroy stack and all resources
cdk destroy

πŸ“Š Stack Outputs

After deployment, the following outputs are available:

  • FrontendBucketName - Name of the S3 bucket hosting your frontend
  • FrontendBucketArn - ARN of the frontend bucket
  • CloudFrontDistributionUrl - Public URL to access your website

Access outputs via:

aws cloudformation describe-stacks --stack-name YOUR_STACK_NAME --query 'Stacks[0].Outputs'

πŸ” Security Considerations

  • S3 buckets are private by default with access only through CloudFront
  • HTTPS is enforced via CloudFront viewer protocol policy
  • Public assets bucket has controlled public read access for specific assets
  • Origin Access Identity (OAI) ensures CloudFront is the only way to access S3 content
  • Different retention policies for prod vs dev environments prevent accidental data loss

πŸ› Troubleshooting

Common Issues

1. CDK Deploy Fails with Permission Errors

# Ensure your AWS credentials have necessary permissions
aws sts get-caller-identity

2. Frontend Build Directory Not Found

# Make sure to build frontend before deploying
yarn buildreact  # or yarn buildvue
yarn build       # Compile TypeScript
yarn deploy

3. CloudFront Distribution Not Updating

# CloudFront caching can take 10-15 minutes to propagate
# Create an invalidation to force update:
aws cloudfront create-invalidation --distribution-id YOUR_DIST_ID --paths "/*"

4. SPA Routes Return 404

  • The error responses in cloudfront.ts handle this by redirecting 404/403 to index.html
  • Ensure your frontend has proper client-side routing configured

πŸ“š Technology Stack

  • Infrastructure: AWS CDK, TypeScript
  • Frontend Frameworks: React 19 / Vue 3
  • Build Tools: Vite, TypeScript
  • AWS Services: S3, CloudFront, CloudFormation
  • Package Manager: Yarn

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0).

You are free to:

  • βœ… Use this project for personal, educational, or non-commercial purposes
  • βœ… Share and redistribute the code
  • βœ… Modify and build upon the code

Under these conditions:

  • πŸ“ Attribution - You must give appropriate credit to the original author
  • 🚫 Non-Commercial - You may not use this project for commercial purposes

For commercial use or licensing inquiries, please contact the author.

See the LICENSE file for full details.

πŸ‘€ Author

GEO

πŸ”— Additional Resources

About

Hosting a web application with S3 and Cloudfront

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published