Static hosting on S3

alt text

One solution for hosting the front end part of a project is to use Amazon S3 to store and serve the HTML/JavaScript that will talk to your Serverless API's. This walk through will show you the basics of how to do that.

 

Fortunately, there is a fancy plugin to do all the heavy lifting for you.

If you have followed the first serverless project tutorial you can build on to that directly.

npm install --save serverless-finch

 

After that you can generate your first HTML page:

mkdir -p client/dist
touch client/dist/index.html

 

Here will be the content of index.html. (Be sure to replace {YOUR_API_ID} with the api id you created.)

<html>
    <head>
        <title>Static Website</title>
    </head>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>

This will send the request to the hello world lambda function.

 

Add the config to your yaml file replacing {YOUR_BUCKET_NAME} with the name of a bucket that you want to create.

service: static-website

provider:
  name: aws
  runtime: nodejs8.10
  region: eu-west-1
  profile: default
  memorySize: 256 # optional, in MB, default is 1024
  stage: dev

plugins:
  - serverless-finch

custom:
  siteName: static-website.com
  client:
    bucketName: ${self:service}-${opt:stage, self:provider.stage}-${self:custom.siteName}
    # distributionFolder: client/dist

resources:
  Resources:
  
    StaticSite:
      Type: AWS::S3::Bucket
      Properties:
        AccessControl: PublicRead
        BucketName: ${self:custom.client.bucketName}
        WebsiteConfiguration:
          IndexDocument: index.html
          ErrorDocument: error.html

    # specifying the policies to make sure all files inside the Bucket are avaialble
    WebAppS3BucketPolicy:
      Type: AWS::S3::BucketPolicy
      Properties:
        Bucket:
          Ref: StaticSite
        PolicyDocument:
          Statement:
            - Sid: PublicReadGetObject
              Effect: Allow
              Principal: "*"
              Action:
              - s3:GetObject
              Resource: arn:aws:s3:::${self:custom.client.bucketName}/*

 

In order to deploy this fancy website on S3, just run the command:

serverless client deploy

 

Keep in mind that the bucket contents will be overridden if they already exist.

Now, you can go to your S3 buckets in the AWS console, find your bucket, press Properties and find Static S3 Hosting URL looking similar to http://{YOUR_BUCKET_NAME}.s3-website-{REGION}.amazonaws.com If you open up the url in a browser, you should see the alert Our lambda is saying hello, which is coming from your api.