Serverless Web Apps on AWS

Sanjeewa WijesundaraCloudcdkAWSAbout 1 min

To create a serverless web app on AWS with CDK, you can follow these steps:

Install the AWS CDK CLI and create a new CDK project:

# Install the AWS CDK CLI
npm install -g aws-cdk-cli

# Create a new CDK project
cdk init sample-app --language=typescript

Add the required dependencies to your project:

# Install the AWS Lambda and Amazon S3 library
npm install @aws-cdk/aws-lambda @aws-cdk/aws-s3

Define your CDK stack and add the necessary resources. You can do this in the lib/sample-app-stack.ts file:

import * as cdk from 'aws-cdk-lib';
import * as s3 from '@aws-cdk/aws-s3';
import * as lambda from '@aws-cdk/aws-lambda';

export class SampleAppStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Create an S3 bucket to store the website files
    const websiteBucket = new s3.Bucket(this, 'WebsiteBucket', {
      websiteIndexDocument: 'index.html',
      publicReadAccess: true,
    });

    // Create a Lambda function to serve the website
    const websiteFunction = new lambda.Function(this, 'WebsiteFunction', {
      runtime: lambda.Runtime.NODEJS_12_X,
      code: lambda.Code.asset('website'),
      handler: 'index.handler',
      environment: {
        BUCKET_NAME: websiteBucket.bucketName,
      },
    });

    // Grant the Lambda function permission to access the S3 bucket
    websiteBucket.grantRead(websiteFunction);
  }
}

Create the website directory and add the necessary files for your web app. For example, you can add an index.html file and a handler.js file:

// website/handler.js
exports.handler = async (event) => {
  const bucketName = process.env.BUCKET_NAME;
  const fileKey = event.path.substring(1) || 'index.html';

  // Get the object from the S3 bucket
  const s3 = new AWS.S3();
  const file = await s3.getObject({ Bucket: bucketName, Key: fileKey }).promise();

  // Return the object in the response
  return {
    statusCode: 200,
    headers: {
      'Content-Type': file.ContentType,
    },
    body: file.Body.toString(),
  };
};

Deploy the stack:

cdk deploy

Info

This will create the necessary resources on AWS, including the S3 bucket and the Lambda function. You can then upload your web app files to the S3 bucket and access them through the Lambda function.