Deploy your Gatsby.js site to AWS S3 and clear CloudFront cache with one simple command.
yarn run deploy
First, let’s get our AWS components we need for this set up.
Set Up AWS S3 Bucket
Set up a new S3 Bucket and make sure you mark the bucket for hosting a website in it’s properties.
Set Up AWS CloudFront
Add index.html as the default root object.
Set the alternate CNAME to your domain (blog.benenewton.com in my case)
Important: Use the actual domain name of the S3 bucket so it resolves to index.html. This will
avoid errors when a visitor accesses one of your pages directly without loading the home page first.
Get domain name for…
Set Up DNS
Set up a CNAME record to point point to the CloudFront domain name. In my case, I am using AWS Route 53.
Now that our AWS components are ready, let’s go into our Gatsby.js project and make the additions we need
to get this rolling.
We’re going to add a couple of components to our webpack build. https://github.com/import-io/s3-deploy and aws-cloudfront-invalidate.
From the command line in the root of your Gatsby.js project, run the following:
yarn add s3-deploy
yarn add aws-cloudfront-invalidate
Now, let’s add the commands we need so we can deploy from the command line.
Add the following properties to the
scripts object in your package.json
"deploy": "gatsby build --prefix-paths && s3-deploy './public/**' --cwd './public/' --bucket [your bucket name] --deleteRemoved --gzip && npm run clear",
"clear": "aws-cloudfront-invalidate [your CloudFront Distribution ID]"
yarn run deploy and you should see your site build and deploy,
then a cache clear sent to CloudFront. When that is complete, you should see your latest code live.