Have you wondered how a Gatsby blog could work while it consumes a Strapi API? In this tutorial, you’ll learn how to deploy a Gatsby blog on Cloudflare Pages that fetches content from a Strapi instance deployed on a cloud hosting providers like Heroku or AWS.
Let’s dive in!
Strapi is a powerful and open-source headless Content Management System (CMS) based on Node.js that gives developers the freedom to choose their favorite tools and frameworks and allows editors to manage and distribute their content using their application's admin panel. You can also directly tinker with the source code itself.
If you are unfamiliar with the term headless CMS, it refers to the backend part of your application without any “front-end” or “head.” There are two kinds of headless CMSes: git-based and API-based. Strapi is API-based, and an example of a git-based headless CMS is Netlify CMS.
The benefit a headless CMS has over a traditional one is that, unlike the latter, you are not tied to any specific “head,” allowing you to consume the content of your headless CMS in a web app, a mobile app, or any other platform.
Strapi allows you to scaffold your API faster and consume it using any “head”: an HTTP client, or GraphQL enabled front-end, etc. It is another tool in the arsenal of front-end developers as it helps them create APIs without knowing back-end development.
Cloudflare Pages is a new service by Cloudflare. They are famous for its CDN and DNS services. This new service is similar to Netlify and Github Pages. Cloudflare Pages lets developers deploy static sites by letting them connect their GitHub or Gitlab accounts and just selecting a repository.
Your site is live in no time, and with each git push
, it gets automatically redeployed. In essence, Cloudflare Pages is a hosting provider for static websites. This tutorial will use Cloudflare Pages to host our Gatsby blog.
To be able to follow this tutorial, you need to have Node and git installed and have a basic understanding of the following:
Many tutorials on the web use Heroku to demonstrate deploying the Strapi API. These tutorials ask you to sign up for a Heroku account and a Cloudinary account as well. The reason for the Cloudinary account is to host image assets since Heroku would restart at least once a day, removing any files not tracked in source control (in this case, it could be the thumbnails for our blog posts). The tutorials would then ask you to click on a link that would install Strapi for you on Heroku.
However, Heroku has ended its free tier, so an alternative offering a free tier is Render (with some limitations) or other free options like back4app. In their documentation, Render has a complete guide on deploying Strapi to their hosting platform.
You can check out guides for other hosting providers in the Strapi docs or this deployment options article. You can also create your own Heroku-like service to deploy the Strapi API by using Dokku with something like DigitalOcean.
The front-end using Strapi can be anything: a website, a mobile app, or something else. In this tutorial, we will use a Gatsby blog. We could have gone with any other web-based solution, like another static site generator (e.g., Eleventy), a React-powered front-end, another front-end framework, or a website with just Vanilla JS.
You can check these guides out to learn how to integrate Strapi with other technologies.
For this tutorial, we will use Render to host our Strapi API for the blog. We are going to use a starter template provided by Strapi called “Strapi Starter Gatsby Blog” to easily create both our front-end (Gatsby blog) and back-end (Strap API) projects. We will use this starter template to:
💾 Database The starter template uses SQLite, so we don’t need to create a database separately in Render.
Let's install this template. Creating a Gatsby blog powered by a Strapi API using this template is as simple as running a single command on your computer. You can choose to run this command either with npm
or yarn
, replacing <my-project>
with the name of your project:
// Run either of these commands in your computer terminal
# Using Yarn
yarn create strapi-starter <my-project> gatsby-blog
# Or using NPM
npx create-strapi-starter <my-project> gatsby-blog
I chose the name to be “sg-test-blog”, you can choose anything you want. The terminal will then ask you to choose between Quickstart and Custom. For this tutorial, we will go ahead with the Quickstart option. Press Enter on the Quickstart option and let the installation continue.
It will install the starter template for you, including creating a monorepo (both your Strapi API and your Gatsby blog), and installing dependencies. It will also run your project automatically.
API Token: The starter template’s GitHub repo mentions that you will need to manually create a full-access API token in Strapi: “Once it's created, save it as STRAPI_TOKEN
in your environment variables”, we will deal with it later.
💽 Installation Note that this tutorial only covers the Strapi installation on Render for GitHub and GitLab.
We will initialize two separate git repositories, one for the front-end and one for the back-end, in their respective folders. First, we must create two separate repositories in our GitHub or Gitlab account.
🧑💻 Environment variables Make sure your repos are private since they will have the
.env
files. We need to comment out the “.env” file in our.gitignore
file (in both the front-end and the back-end folders) to make sure that it gets deployed as well. You need to do it like this (it was at the bottom of the page, in my case):# .env
. If there is no.env
file, you must create one.
We then need to initialize the git repos we just created in our projects and push them by running the following commands:
// We are in the root of the project
cd frontend
git init
git add .
git commit -m "first commit"
git branch -M main
// replace "shammadahmed" with your username and "sg-gatsby-test" with your frontend repo name
git remote add origin git@github.com:shammadahmed/sg-gatsby-test.git
git push -u origin main
cd ../backend
git init
git add .
git commit -m "first commit"
git branch -M main
// replace "shammadahmed" with your username and "sg-gatsby-test" with your backend repo name
git remote add origin git@github.com:shammadahmed/sg-strapi-test.git
git push -u origin main
Wait for the commands to finish. After this, we can connect our backend git repo to Render for deployment.
🛠️ Build command The “production” build command for Strapi is
npm run build
oryarn build
.
🚦 Memory limit If your deployment keeps getting failed, it could be because we are using the free plan on Render and the free plan has memory limits. I replaced the images in
backend/data/uploads
with tiny file-size images, made a commit, and redeployed, and the deployment finally succeeded.
your.app/admin
(replace your.app with your specific domain) or just click the link at the top (in this case, https://sg-strapi-test.onrender.com/)./admin
on our new website. Opening this for the first time will redirect you to your.app/admin/auth/register-admin
. We are done with the back-end deployment part; let’s copy the URL of our Strapi API for use in our front-end (in my case https://sg-strapi-test.onrender.com/).
There is still one more step remaining: do you remember that the starter template asked us to create a full access token? We need to create one and save it as well for our front-end. We will go to the “Settings” tab in our Admin UI to create one.
Next, we need to click on API Tokens under Global Settings:
Now, click on the “Create new API Token” button:
Ensure that the token type is full access, choose a suitable name and suitable token duration, and click on the save button. You have successfully created your API Token. Copy it for our front-end, just like the Strapi API URL.
📡 API & permissions If you have trouble loading your API through REST endpoints, it could be related to your permissions settings in the admin panel.
Now that we have our API URL, we need to write it in our front-end's .env
file. Open this file (you may need to create one if not already there) and add both your URL and API Token like this:
STRAPI_API_URL=https://sg-strapi-test.onrender.com/
STRAPI_TOKEN=thisisthetokenthatyougenerated
Next, make a small change at the top of your gatsby-config.js
file:
// from this
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
// to this (we only removed .${process.env.NODE_ENV} from the 2nd line
// make sure the rest of the file is as it was
require("dotenv").config({
path: `.env`,
})
Now that our .env
and gatsby-config.js
files are ready, we will commit these changes:
git add .
git commit -m "add strapi api url"
git push -u origin main
We now need to create an account on Cloudflare Pages. After you are logged in, head on to the Pages tab if not already there:
Click the ‘Create a project’ button, which takes you to this screen asking you to choose from one of three options:
We will go ahead and use the “Connect to a git provider” option. Click the “Connect to git” button to proceed. Choose your git platform and select your account where you have the gatsby blog (front-end) that we created. Finally, select that repo.
I selected sg-gatsby-test
and clicked the “Begin setup” button. This opens up the settings page for this deployment. Here, we will change the “Framework preset” setting to “Gatsby”.
Click on the “Save and Deploy” button to start your deployment.
🚦 Plan limits Make sure that your Strapi server is active when you start the deployment of your front-end on Cloudflare Pages. It is necessary since Render shuts down after 15 minutes of inactivity, and you also lose the admin account. If you lose your current Render server instance, create a new admin account, regenerate your API Token, and commit it into your repository.
🛠️ Build command Note that the “production” build command for Gatsby is
build
. You can rungatsby build
with Gatsby CLI ornpm run build
.
If your deployment fails, it could be because of different Node versions on your computer and the Cloudflare servers. To solve this error, check your node version on your computer with node -v
and add it to your project settings in Cloudflare Pages in the “Environment variables” tab like this:
💵 Cache Another reason your deployment can fail is because of the cache. To solve this, either you can run
gatsby clean
(you need to have the CLI installed) before you push your repo, or you can just add thepublic
and.cache
folders in your.gitignore
file (each folder on each line). This is important, make sure that you do either of them.
Wait for your deployment to finish.
Congratulations! We have successfully deployed our app. Click on the URL generated by Cloudflare Pages in the top right corner just below the “Manage deployment” button to load our site:
Hurray! Our Gatsby blog is ready live and looking beautiful.
Cloudflare and Strapi announced their partnership through the Cloudflare Deploy Hooks for Strapi feature. With this feature, you can set up a connection between your front-end and back-end such that when you add new content (or make some other change) to your API through the Admin UI, it can trigger a new build of your front-end, refreshing the content of your site. We will do the following:
You may be wondering how this works. Well, it is pretty simple: generate a URL in your Cloudflare Pages dashboard, add it to your Strapi Admin UI, and select the events that trigger the URL. When you make such an event happen, for example, adding a new article to your blog will change the data in your API endpoint, and Strapi will trigger the Cloudflare Pages URL.
Cloudflare Pages will listen to the trigger and start a new build of your front-end site, and when your Gatsby site is being compiled, it will access the new data through the API, creating the updated site for you.
Your new site will be live and showing your changes without having you trigger the deployment yourself. This whole scenario is called a webhook. Neat, isn’t it? Let’s make use of this feature in our blog.
To create a Deploy Hook (the URL we were talking about that you generate in Cloudflare Pages and add to your Strapi Admin UI), go to your Cloudflare dashboard. In the Pages tab, select your project (in our case, sg-gatsby-test
).
Now go to the “Settings” tab and select "Builds & deployments” from the sidebar. Scroll down to the bottom of the page, and you will find the “Deploy hooks” section. Click the “Add deploy hook” button to create a deploy hook for our Strapi API.
It will now ask you to choose a suitable name for your deploy hook and the branch of your front-end repo to build. Let’s go with “strapi-api-admin-on-render” where the branch is “main”.
🪪 Naming You see, I chose this particular name so that in case of any error, I can easily identify the source of the build trigger in the Cloudflare Pages dashboard.
We have successfully generated our Deploy hook URL:
Copy this URL for use in our Strapi Admin UI.
🔑 Keep your deploy hooks secure Deploy Hooks do not require authentication for usage, so it is important to keep them secret and not share them with anyone, just like we did in the case of our API Token in our
.env
file. If you suspect someone unauthorized is using your Deploy Hook, you should delete the Deploy Hook and generate a new one.
In your Strapi Admin UI, go to the “Settings” tab and select “Webhooks” under “Global settings.”
🚦 Plan limits Your Render server may have already become inactive and deleted the admin account you created. You may now need to load your Strapi API first so it becomes active. You will then need to create another admin account, generate a new token, replace the previous one in your frontend
.env
file with this new one and finally commit the changes. Wait for the deployment of your front-end to finish, and then continue with the tutorial.
Click the “Create new webhook” button to open this page:
Select a name (I named it “Cloudflare Pages Gatsby Blog”) and paste the Deploy Hook URL you copied in the respective fields. You will also see an “Events” section: you can configure your webhook to be triggered based on events.
You can adjust these checkboxes to request a new build of your Cloudflare Pages site automatically when a Strapi “entry” or “media” asset is created, updated, or deleted. Choose which events should trigger a rebuild by selecting their respective checkboxes.
I chose all the events in the “Entry” row. This means that the Deploy Hook would only be triggered when I “create,” “update,” “delete,” “publish,” and “unpublish” an entry, like an article or author, and not when I change a media file.
Click the “Save” button to save your webhook.
Let’s test our webhook by changing the name of our site from “Strapi Blog” to “Hammad’s Blog” in our Admin UI. In the Admin UI sidebar, select the “Content Manager” tab and go to “Global” under “Single types”:
Here I will change the “siteName” field from “Strapi Blog” to “Hammad’s Blog”:
Now, click on the “Save” button. Strapi will automatically trigger the webhook, causing Cloudflare Pages to start a new build. It will take some time and then reload your site to see your changes live:
Huzzah! Our site name has successfully changed through the webhook. If your site doesn’t change, ensure that you access it without the particular deployment code before your subdomain (e.g., https://574ad6b1.sg-gatsby-test.pages.dev/) and access it like this: https://sg-gatsby-test.pages.dev/.
At this point, you might think that this webhook auto-deploy feature isn’t that useful since you can easily trigger a new build whenever you want simply by going into your Cloudflare Pages dashboard and triggering a new build. This webhook feature is useful because it helps writers or content teams publish content without any developer intervention.
🪵 Deployment logs A new build will be triggered every time a request is sent to your Deploy Hook. You can see the Source column of your deployment log (“All deployments,” the second thing under the Deployments tab” of your Pages project) to see which deployments were triggered by a Deploy Hook. Let’s check them out (notice the first one, it is the one that we just triggered by changing the site name):
Don’t let the words “run gatsby clean” confuse you; it is just the commit message, telling us the specific commit the deployment used for the “build.” Our webhook triggers the first deployment and the two below are triggered by “git commit and push” on our repo.
I hope you enjoyed reading and were able to deploy your project successfully. We first learned the different technologies in use in this tutorial. Then, we headed towards the actual deployment process: first, we deployed our back-end on Render and then deployed our front-end on Cloudflare Pages. We connected them both using a simple webhook. Finally, we wrapped it up by reviewing our deployment log in our Cloudflare Pages dashboard.
That’s it for this tutorial about deploying Strapi on Cloudflare Pages. I had a lot of fun writing this. If you have any questions, feel free to ask in the comments section, or if you just want to say hi, feel free.
Til then, happy coding!
Software Developer and Writer focusing on the web. He likes to explore both the hardware and software facets and is passionate about making the interwebs a better place for everyone.