You are viewing the preview version of this book
Click here for the full version.

Client-side

Now that we have everything ready on the backend-side, let's move on to how to use all this on the frontend! Since this book focuses on the backend primarily, we'll only lightly cover these topics, but it's good to know about some potential issues.

Frontend code

Code example

Implementation here.

First, let's see how to deploy the frontend files and how to provide environment configuration.

Frontend configuration

The frontend is usually just a bunch of static files that makes it easy to deploy. In AWS, serving files builds on two services: CloudFront and S3.

CloudFront provides a user-facing entry point to the client app. It is a CDN that does routing for different kinds of backends, and it can be configured with a a custom domain and an AWS-provided certificate as well.

S3 on the other hand provides a place to store objects, in this case the files for the frontend. It can be integrated with CloudFront so whenever a client request comes in it is served from the S3 bucket.

Uploading the files

To serve files from S3, they need to be uploaded into a bucket. The Terraform configuration creates a bucket first:

resource "aws_s3_bucket" "frontend_bucket" {
  force_destroy = "true"
}

Then it reads the directory of the frontend project and adds an object for every file found there:

resource "aws_s3_object" "frontend_object" {
  for_each = fileset("${path.module}/frontend", "*")
  key      = each.value
  source   = "${path.module}/frontend/${each.value}"
  bucket   = aws_s3_bucket.frontend_bucket.bucket

  etag          =
    filemd5("${path.module}/frontend/${each.value}")
  content_type  =
    local.mime_type_mappings[
      concat(regexall("\\.([^\\.]*)$", each.value), [[""]])[0][0]
    ]
  cache_control = "no-store, max-age=0"
}

To set the correct mime types, a local variable defines them per extension:

locals {
  mime_type_mappings = {
    html = "text/html",
    js   = "text/javascript",
    mjs  = "text/javascript",
    css  = "text/css"
  }
}
Frontend files in the bucket

Distribution

Next, we'll create a CloudFront distribution.

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions