How to host a Gatsby Website on Cloudflare
March 21, 2025
Cloudflare R2 is a powerful, cost-effective object storage solution that integrates seamlessly with Cloudflare's global network. This makes it an excellent choice for hosting static websites, including those built with Gatsby. This guide will walk you through the process of deploying your Gatsby site on Cloudflare R2.
Prerequisites
- A Gatsby website ready for deployment.
- A Cloudflare account.
- A Cloudflare R2 bucket.
Preparing the bucket
First make sure you connect the bucket to a domain, that will enable the contents of the bucket to be publicly accessible through the domain. To do this you can connect a domain in the bucket settings in Cloudflare R2.
Make sure you get create an API Token, that we will use in the next step to upload our static website to Cloudflare R2. You will need the Access Key ID, Secret Access Key and the Endpoint URL.
Uploading the static website into the Cloudflare R2 Bucket
If your website is already hosted on AWS S3 the process it's pretty straight forward, just upload the contents to Cloudflare R2 instead of AWS S3 by changing the endpoint to the one from Cloudflare R2 and use the credentials you have from the previous step.
Since Cloudflare R2 is compatible with AWS S3, we can use the aws cli tool to deliver the contents of our public folder to the Cloudflare R2 bucket.
You can find the instructions to install AWS clie tool here: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html.
Also AWS provides a Docker image: amazon/aws-cli that you can use to run the aws commands without installing the tool directly on your system.
Once you have the aws cli tool setup you can run the following command to upload the contents:
AWS_ACCESS_KEY_ID=<your_access_key_id> AWS_SECRET_ACCESS_KEY=<your_secret_access_key> aws s3 sync ./public s3://<your_bucket> --region auto --endpoint-url <your_endpoint> --checksum-algorithm=CRC32
Verify the contents
Once the files have been uploaded, try to access the index.html file of Gatsby on your connected domain in your browser: yourdomain.com/index.html.
Adjusting URLs
As you probably noticed to access the page on CloudFlare we need to add the suffix /index.html. To fix this we can use the Cloudflare's Rules feature, we can make a rule to overwrite the original request URL and append /index.html when accessing the pages from the Cloudflare R2 bucket.
Access the Cloudflare's Rules feature. Find the "Create rule" button and select the "URL Rewrite Rule" option.
In the rule configuration, create a custom filter expression, and specify a rule with URI Path ends with "/" and Rewrite to: concat(http.request.uri.path, "index.html").
This would write paths from /your-page to your-page/index.html. Try it out by accessing the domain directly like: https://yourdomain.com.