Following the theme of our previous post, “Static Website Hosting With CloudFormation“, I thought that before moving onto a radically different topic we could keep exploring alternative ways of reaching similar outcomes.

To no one’s surprise, there’s always multiple ways of doing the same thing on AWS. Options typically vary on pricing, functionality, ease of use, management overheard and more, so today we will be having a look at Amplify Console. The Amplify brand is all geared towards making web and mobile development as easy and streamlined as possible (the “umbrella” contains client side libraries, backend provisioning, hosting, CI/CD, CLI). So with Amplify Console we see their approach to hosting and CI/CD, in an easier and significantly less “hands-on” approach compared to having to roll out your deployment pipelines, buckets, SSL, etc.

The Application

Feel free to follow this step by step or use your own applications. In my case, I’ll be using the calculator app from the community built React applications that you can find on their site. The majority of the instructions would apply to any application with some exceptions needed for apps built using create-react-app.

Getting Started

Head over to the Amplify homepage and create a new app and choose “Host web app”

 

 

 

 

We’re now presented with a choice for our source code provider. In my case, I’ll be using CodeCommit but you can choose from the most common ones as well as manually uploading your application (which unless being a quick prototype, it kind of defeats the purpose). Depending on your provider of choice, you’ll need to accept and enable the various different permissions for the service to be able to read your repository as that’ll be needed in order to detect changes and pull the code.

 

The first bit of magic will come in after hitting the Next button. You might find there’s a slight delay and that’s because Amplify is looking into your repository in order to find build settings for your application or auto create one for you. Amplify will be able to detect and automatically create settings for most common setups. It’ll be able to see if you use NPM or YARN, React or Vue and even if you’re using a static site generator such as Hugo or Gatsby. You could be in luck and the auto generated settings don’t need any manual intervention but even if you need to change a value here or there, what’s presented to you will get you at least 80% of the way there.

 

After that, you’re presented with everything up to that point and you should be able to save your project. The service will bootstrap your application and it’ll start a new deployment, providing you with an unique URL (with SSL enabled) to access your site. There are also a number of settings on the left hand side menu such as domain management, notifications, access control (i.e setting a password for your site), monitoring, redirects and more. Let me know if you would like to dive deeper on those on future posts.

And that’s it! Your site should be up and running, a deployment pipeline is set up for you behind the scenes so any future changes that you make to the connected branch will trigger a new deployment.

 

A note on create-react-app

If you followed along with the same application or are using create-react-app for yours, you are going to see that things won’t work out of the box. I’ll list below the changes I made in order to have it running, however you could also make some adjustments within the actual build process to move files across.

Redirects

The index.html is located under the “public” folder as opposed to the root of the repository so a redirect rule was needed there.

 

Build Settings

Not much needed to change here except where our base directory is located. The create-react-app build process will save all its files under the “build” folder so I just needed to adjust that to reflect that difference.

 

Homepage

Finally, create-react-app uses the “homepage” value in your package.json to assume where your app lives. All I had to do there was setting it up as an empty value (“”).

When using Azure API Manager, one of it’s benefits is the ability to respond to certain API requests without having to ping your backend for the response. Essentially short circuiting API responses and offloading that computer power to a simple API management layer. In this case, we are specifically talking about being able to respond to a browser’s OPTIONS request (e.g. using CORS), without your entire application pipeline kicking into gear.

Now like most things, there are multiple ways to achieve the same result. So we are first going to talk about how we can get API manager to respond to the request without involving your backend API at all, but later we will also show you how you can allow a pass through to your API if you prefer to manage CORS configuration inside your application code, rather than API manager.

Using A CORS Policy

If you’re looking for the most hands off approach possible, your best bet is to use a CORS Inbound Policy within APIM. Previously, you had to manage most of this via XML copy and paste, but now there is an easy configuration wizard to follow. Inside Azure API Manager, select your API, All Operations, then go ahead and select “Add Policy” on Inbound processing.

On the next screen, find the option to “Allow cross-origin resource sharing (CORS)” as shown below

By default, the options presented to you will only be to select the “Allowed origins”, which is defaulted to *. I highly recommend instead to select the “Full” options and complete them. If you use Basic, by default, it will only allow GET and POST requests. This might be OK for some API’s, but generally modern applications make use of things like PUT, DELETE and PATCH.

After saving the configuration on this screen, your API manager will actually “short circuit” all OPTIONS requests and respond with these options defined here. Meaning that your backend service never has to put in computing power for trivial requests again!

Under the hood, using this wizard actually just adds the following custom policy to the inbound policy XML :

<cors>
  <allowed-origins>
    <origin>*</origin>
  </allowed-origins>
  <allowed-methods>
    <method>GET</method>
    <method>POST</method>
    <method>PUT</method>
    <method>DELETE</method>
  </allowed-methods>
</cors>

You may find guides around Azure API manager that still refer to pasting in this XML manually via the Azure Portal, and it’s still a valid way to do it, but for the most part Azure has added a tonne of quick wizards that essentially do the same thing, but don’t involve you having to do janky notepad copy and pastes all over the place.

Using A Wildcard OPTIONS Request

This is actually the default when you add a backend service like an Azure App Service to APIM via the wizard, instead of mapping each endpoint manually. When you do this, it actually creates a wildcard OPTIONS operation that does nothing but pass every request to your backend.

If this wildcard operation doesn’t show for you, simply create a new operation for OPTIONS that has a wildcard URL as depicted above.

After doing this, it will be up to your application to respond to OPTIONS requests. This means that your application is now getting hit when APIM could take the load off for you, but it does mean that you have more fine grain control if you prefer to manage CORS from within your existing application code rather than Azure API Manager.

Map Individual OPTIONS Requests

Instead of using a wildcard operation inside APIM, you can of course map each endpoint individually. In some cases this may be more effort than it’s worth but if you want complete fine grain control over what requests are forward to your application, this is an option.

I personally try and avoid this as it it essentially means duplicating each request to add an OPTIONS operation. If you are looking at doing this for security reasons, then in my opinion the use of a CORS inbound policy, and making the attack surface area be handled by Azure API Manager, is a much better option.

Static site generators such as Hugo, Gatsby and Jekyll as well as front-end development practices of decoupling presentation and APIs have pushed static web hosting to primetime. One of the many benefits of doing this, is the ability to very easily deploy these sites on simple object stores without the need of provisioning virtual machines.

Enabling Amazon S3 Static Web Hosting

Amazon S3 is one of AWS’ oldest services and it has been able to host static website at the click of a button for as long as it has been around.

I’ll show you how to enable static web hosting on an existing bucket, the complexity of doing this at creation is the same but the UI might look slightly different. Head over to the bucket you want to enable static web hosting, select the Properties tab and scroll to the bottom of the screen. By default, this functionality is disabled so you should see something like this.

 

Go ahead and click the Edit button. Here you will be presented with a number of very straight forward options such as whether you want to enable the functionality and what type of hosting you want. By default, S3 will look for an index.html file at the root of your bucket but you can specify a different file in the Index document section. Pay attention to the information banner telling you that for this to work, not only you need to enable the functionality you also need make the content in your bucket public.

You can also configure redirection rules which we wont cover now, so scroll to the bottom and save your changes.

 

If everything went according to plan, you should now see it enabled and ready to be used.

 

You can also achieve this programmatically with CloudFormation (or any other IaC provider). Here’s what the YAML version of a CloudFormation template would look to achieve similar results.

AWSTemplateFormatVersion: 2010-09-09
Resources:
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead
      WebsiteConfiguration:
        IndexDocument: index.html
    DeletionPolicy: Retain
  BucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      PolicyDocument:
        Id: MyPolicy
        Version: 2012-10-17
        Statement:
          - Sid: PublicReadForGetBucketObjects
            Effect: Allow
            Principal: '*'
            Action: 's3:GetObject'
            Resource: !Join 
              - ''
              - - 'arn:aws:s3:::'
                - !Ref S3Bucket
                - /*
      Bucket: !Ref S3Bucket
Outputs:
  WebsiteURL:
    Value: !GetAtt 
      - S3Bucket
      - WebsiteURL
    Description: URL for website hosted on S3

 

A Few Things To Note

HTTPS

S3 doesn’t let you make HTTPS requests to your site (you will be greeted by a nice 403). If this is a pre production environment that might be enough, however, the moment you start serving content to your customers you want to secure the traffic over the wire. You can get that functionality by pairing your newly hosted website on S3 with AWS’ CDN offering, CloudFront.

Domain Name

Two different endpoint formats are supported to access your content, let see if you can spot the difference.

http://your-bucket-name.s3-website-Region.amazonaws.com

http://your-bucket-name.s3-website.Region.amazonaws.com

Don’t feel bad if you haven’t. The only difference is the choice of “.” and “” in between s3-website and the region in which your bucket lives.

CNAME and Custom Domains

Both CNAME and custom domains are supported. For CNAME, if you have a registered domain let’s say www.your-bucket-name.com you can create of bucket with that as its name and then create a DNS CNAME entry that points to www.your-bucket-name.com.s3-website.[region-placeholder].amazonaws.com. On the other hand, if you want a completely different name for your site that doesn’t match your bucket’s name, you can use your domain registered on Route53 by creating an Alias with your bucket’s information.

There has been a boom in recent years of people falling in love with static site generators such as Hugo, Jekyll and Gatsby to name a few. Along with this, there has been a need for cheap static website hosting with little (to no) compute power required. After all, there’s no reason to spin up a huge VM to serve a couple of HTML pages!

Azure has entered the fray with their option titled “App Service Static Web Apps”, which is really just the ability to use blob storage to serve files as a website, under a custom domain. Officially, it’s still under preview at the time of writing, but it’s still a very solid service for hosting static websites of any size. On top of this, it can be a great place to host front ends of your single page application, built in Angular, React, or Vue, that can then call directly into an App Service or Function written in your favourite backend programming language.

Let’s get started!

Configuring App Service Static Web Apps

Head to your Azure Storage Account via the Azure Portal, and select the “Static Website” option under the left hand settings menu.

Then go ahead and enable your static website. You will be given a primary endpoint, and have the option to enter a index file name, and an error file name. These  are the files that blob storage should serve when someone hits the index of your site, and when a user requests a file that doesn’t exist (404), respectively.

For static websites, it will likely be index.html and something like 404.html, however for front end frameworks such as Angular, you will want to direct the “error” page to the index also as all requests should be directed to the root page, irrespective of the URL, for Angular routing to handle the request. In this context, a 404 is whether a physical file exists in blob storage with a particular URL, not whether your angular application has a route for the URL.

In the end, things should end up looking a bit like below :

Also notice the message about a container being created for you, this does exactly what it says on the tin! If we hit save and check our containers within the account, we will see Azure has created a container named $web. Uploading content to this will automatically be served under our primary endpoint URL on the previous screen.

Deploying via Azure Devops/AZCopy

If you are using Azure Devops to deploy your code, then you already have an inbuilt way to send files to your blob storage account.

Consider the following YAML :

- task: [email protected]
  inputs:
    sourcePath: '$(Pipeline.Workspace)/FileFolder/*'
    azureSubscription: '$(serviceConnectionNameHere)'
    destination: 'AzureBlob'
    storage: '$(storageAccountName)'
    containerName: '$web'

Nice and easy! If you are using the classic editor instead of YAML, the same “AzureFileCopy” task is available to you via the GUI.

It’s also extremely important to note that AZCopy by default will try and guess mimetypes on your files. This is a good thing! However in various versions of both AZCopy, and the AzureFileCopy task, this can be easily accidentally overridden. For example, in some versions of the AzureFileCopy task, it will guess the mimetype *unless* you pass in additional flags, in which case it will automatically stop guessing mimetypes.

There is no one size fits all solution as different versions of the task, and AZCopy behave differently. But if you are finding that your files are not being uploaded with the correct mimetypes, or you are finding that your files “download” in your browser instead of being rendered in the browser, it’s likely an issue of AZCopy not guessing mimetypes correctly.

Adding A Custom Domain

Adding a custom domain is actually very simple, simply take your favourite domain provider and create a CNAME record between your domain, and your “zX.web.core.windows.net” primary endpoint domain. That’s it! It’s highly recommended to use Azure CDN in front of your static website which can help with handling of custom domains and HTTPS, but it’s not a hard requirement and for many Dev/Test scenarios, using the primary endpoint directly is more than sufficient.

What About ARM Templates?

At the time of writing, and probably owing to the fact that the service is in preview, users are currently unable to configure Static Web Applications via ARM Templates. While the storage account itself can be created via template, the actual configuration of a Static Web Application, including even the ability to turn the feature on, is required to be done via the Azure Portal.