Customizing Headers for an AWS Amplify Deployment


Borislav Hadzhiev

Last updated: Apr 22, 2021


Photo from Unsplash

Setting Custom Headers for AWS Amplify Deployments #

We often need to customize the headers of an AWS Amplify hosted website.

Common use cases include:

  • specifying a Cache-Control header because caching is always more intuitive / transparent if we manage it ourselves.By default AWS Amplify doesn't cache content in order to provide instant updates on deployment.

  • adding headers related to security.

To customize the headers of our AWS Amplify deployed site, we need to create a file named customHttp.yml in our project's root directory.

For the caching use case, we could provide additional headers to an AWS Amplify deployment like so:

customHeaders: - pattern: '**/*' headers: - key: 'Cache-Control' value: 'max-age=60, stale-while-revalidate=60'

Let's go over the yaml properties, we've specified.

The pattern property serves as a matcher, the headers are only applied if the pattern matches. In our case we're doing a catch all, but you could be more specific, with a pattern like: '*.html' or '*.png', which would mean the defined headers only apply to html or png files.

The headers property is just the name of the custom header, i.e. Cache-Control, and the value is the value we want to set for the header.

Deploying the Header changes to AWS Amplify #

The way we persist the changes we've made to the Headers of our AWS Amplify site differs, depending on our selected deployment method.

When using CI/CD deployments with Git, you have to push to the repository's main branch, in the same way you push changes to your site.

When using manual deployments you have to re-deploy your app for the changes to take effect.

Note that your custom headers will not be updated in the Amplify console, which is a little weird, but they will work regardless.

For example, my custom headers are empty in the Amplify console, but the Cache-Control is still applied:

custom headers empty

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.