REVISED AND UPDATED: 15 JUNE 2019

Gatsby Strapi

A static website contains Web pages with fixed content. Technically, it is a simple list of HTML files, which displays the same information to every visitor. Unlike dynamic websites, they do not require any back-end programming or database. Publishing a static website is easy: the files are uploaded on a simple Web server or storage provider. The two main advantages of static websites are security and speed: there is no database so it can not be hacked and there is no need to render a page for each request, which makes Web browsing faster.

To make their creation easier, numerous open-source static websites generators are available: Jekyll, Hugo, Hexo, etc. Most of the time, the content is managed through static (ideally Markdown) files or a Content API. Then, the generator requests the content, injects it in templates defined by the developer and generates a bunch of HTML files.

Progressive Web Apps (PWA) are web applications, highly based on JavaScript, and are reliable, fast and engaging. Since they make web browsing much faster and offer a better user experience, PWA has become the default way to build Web interfaces. Thus, many amazing front-end frameworks appeared over the last couple years: Angular, React and more recently, Vue.

Gatsby: when static websites meet Progressive Web Apps

Both static websites and PWAs have strong advantages which make us crave for a way to use them together in the same project! Luckily, we have tools that bridge the gap between them and the one we recently heard of is definitely Gatsby. So, we decided to give you a complete example of how to get started with Gatsby. A static website needs a source of content: in this example, we will deliver it using an API built with Strapi.

What is Gatsby?

Gatsby is a blazing-fast website framework for React. It allows developers to build React based websites within minutes. Whether you want to develop a blog or a corporate website, Gatsby will fill your needs.

Gatsby logo

Because it is based on React, the website pages are never reloaded which makes the generated website super fast. A large set of plugins is available to allowing developers to save time coding. For example, plugins exist to get data from any source (Markdown files, CMS, etc.). Gatsby is strongly based on the "node" interface, which is the center of Gatsby's data system.

Created by Kyle Mathews, the project was officially released in July 2017. (As of February 2109,Gatsby is in Gatsby v2 and is now used by many companies and for hundreds of websites.

What is Strapi?

Strapi is an open source Headless CMS Front-End Developers Love. It's more than a Node.js Framework and more than a Headless CMS, it saves weeks of API development time, and allows easy long-term content management through a beautiful administration panel anyone can use.

Thanks to its extensible plugin system, it provides a large set of built-in features: Admin Panel, Authentication & Permissions management, Content Management, API Generator, etc.

Unlike other CMSs, Strapi is 100% open-source, which means:

  • Strapi is completely free.
  • You can host it on your own servers, so you own the data.
  • It is entirely customisable and extensible, thanks to the plugin system.

Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series

Please follow along watching the videos below and reading the text. You can watch just the videos or read just the text, but you will get the most from this tutorial by watching and reading both. The videos are designed to be used together with this article.

The videos follow the exact sequence of this article. The videos contain additional information and additional configuration details for a few sections. However, for intermediate to advanced users this article will be sufficient to get oriented and started building Strapi powered Gatsby projects.

Index of Tutorial

  1. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Introduction
  2. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Installation
    2A. Learn Gatsby's with Strapi Headless CMS Video Tutorial Series - Administrators and Users
  3. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Content Types
  4. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Roles and Permissions
  5. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Setting up Gatsby
  6. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Create the Index page view
  7. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Create the Article page view
  8. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Gatsby Images & the Article page view
    8B. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Specify Node Version
  9. Learn Gatsbyjs with Strapi Headless CMS Video Tutorial Series - Deploy Strapi to Heroku
    9A. Learn GatsbyJS with Strapi Headless CMS Tutorial Series - Configure again Permissions
  10. Learn GatsbyJS with Strapi Headless CMS Tutorial Series - Set-up Cloudinary & Netlify Predeploy
  11. Learn GatsbyJS with Strapi Headless CMS Tutorial Series - Deploy Gatsby to Netlify
  12. Learn GatsbyJS with Strapi Headless CMS Tutorial Series - Webhooks with Gatsby & Strapi
  13. Learn GatsbyJS with Strapi Headless CMS Tutorial Series - Adding Markdown Support

Note: Final tutorial and code is available at the GitHub repo for the Strapi and Gatsby tutorial. In this repo, you can download and/or copy/paste the example content.

Note: Within the content below we provide links that open a running localhost project. For either Strapi or Gatsby. These will not work if your server(s) have not been started.

1. Introduction

This video series will take you step by step through creating a blog in Gatsby and teach you how to connect it to the open sourced headless CMS - Strapi

Important links from Video:

2. Installation

Important links from Video:

Strapi CMS Setup

To make the magic happen, let's create a Strapi headless CMS and add some content.

Create a Strapi project

Install Strapi

Requirements: please make sure Node 10 is installed and running on your machine. Strapi does not support Node.js versions 11 or 12.

Install Strapi using npm:

npm install strapi@beta -g  

Note: Strapi is in Beta version.

Generate a Strapi project

Create a directory named tutorial:

mkdir tutorial  

Navigate into tutorialand then, using a single command, set-up and start your project inside your tutorial folder:

cd tutorial  
strapi new cms --quickstart  

Using the --quickstart flag creates a full Strapi project and automatically starts the server and opens up a tab in your browser.

(If you leave off --quickstart. Strapi allows you to configure the project according to your needs, Strapi will ask you some questions about your preferences. In this case, reply to each of them or press enter to keep the default values. If you choose a different database than SQLite, you will need to separately install that database onto your system and have it running in the background.)

Additional information can be found in the Official Strapi documentation.

Create your first Administrator

Add your first Administrator using the registration page. This will be an Administrator role.

Tutorial

Restarting Strapi

After installation, and initial use, you will often close your project and work on other things, reboot your computer, etc. Therefore, you will need to restart Strapi and your project.

Enter inside your project folder, on the command line, (in this case tutorial/, :

cd cms  

From cms/, launch the Strapi server:

strapi develop

// or

npm run develop  

Starting here, you should be able to visit the admin panel of your project: http://localhost:1337/admin. You will now be directed to a login screen. Login using your Administrator role.

2A. Administrators and Users

Administrators and Users are separate roles.

  • An "Administrator" has access and rights to the backend of Strapi. They have the ability to add content, add plugins, upload images, etc...
  • A "User" is someone who interacts with your project through the front-end. Someone who makes a purchase, has an account, leaves a review, a comment, etc.

At this point, you have created an Administrator, now you will need to create a User.

Click on Users located under CONTENT TYPES in the left-hand menu.

  • Click the blue + Add New User button in the top right corner.
  • Next, complete the Username, Email, and Password fields.
  • Select ON for the Confirmed toggle field.
  • To the right, under Role, select Authenticated.

3. Content Types

Important links from Video:

Create a Content Type

Strapi CMS projects are based on a data structure called Content Types (equivalent to models in frameworks and Content Types in Wordpress).

Create a Content Type named article with four fields:

  • title (type string)
  • content (type text)
  • image (type media)
  • author (type relation, many articles to one user)

Tutorial

Tutorial

After creating your fields, as above, save your new content type and wait for Strapi to restart.

Insert some entries

Add some articles in the database. To do so, follow these instructions:

  1. Visit the articles list page.
  2. Click on Add New Article.
  3. Insert values, link to an author and submit the form.
  4. Create two other articles.

Note: You can download the sample content from the video here.

Tutorial

4. Roles and Permissions

Allow access to Article

For security reasons, API access is, by default, restricted. To allow access, visit the Auth and Permissions section for Public role, click on Public, select the Article - find action and save. At this point, you should be able to request the list of articles.

Tutorial

Static website development

Great job, our API is ready! We can start developing the static website.

5. Setting up Gatsby

Important links from Video:

Install Gatsby

First, install Gatsby CLI:

npm install --global gatsby-cli  

Generate a Gatsby project

In the folder tutorial that you previously created, generate your brand new blog:

gatsby new blog  

Start in development mode

Enter in your project's folder:

cd blog  

Start the server:

gatsby develop  

At this point, you should already be able to get access to your Gatsby website at this address: http://localhost:8000.

Install the Strapi source plugin

When you manage a static website, your data can come from different sources: Markdown files, CSV files, a WordPress website (using the JSON REST API plugin), etc.

Gatsby understands this pretty well. So its creators decided to build a specific and independent layer: the data layer. This entire system is strongly powered by GraphQL.

To connect Gatsby to a new source of data, you have to develop a new source plugin. Fortunately, several source plugins already exist, so one of them should fill your needs.

In this example, we are using Strapi. Obviously, we are going to need a source plugin for Strapi APIs. Good news: we built it for you!

Let's install it:

Path: blog/

npm install --save gatsby-source-strapi  

This plugin needs to be configured. Replace the content of gatsby-config.js with:

NOTE: Please understand that the apiURL:, e.g. http://localhost:1337 does NOT have a trailing slash. This will create issues, as a slash is added by other code in the plugin.

Path: blog/gatsby-config.js

Allow access to User

Remember, when we created the content type we created a relation between User and Articles.

Like Article,User, link is likewise, by default, restricted. But Gatsby needs access, so to allow access, visit the Auth and Permissions section for Public role, click on Public, select the User - find action and save. After saving; Gatsby will have access to all the necessary content types managed by Strapi (for this tutorial).

Restart Strapi from the command line, inside the cms folder - first by Ctrl+ C to stop the server; and then typing strapi develop, to restart it.

Next, restart the Strapi server to allow Gatsby to register these updates, the next time you restart Gatsby.

Optional: Modify the <Layout /> component. Add Strapi to the footer.

Replace the following <footer> section.

Path: blog/src/components/layout.js

<footer>  
  © {new Date().getFullYear()}, Built with
          {` `}
  <a href="https://www.gatsbyjs.org">Gatsby</a> and {" "}
  <a href="http://strapi.io">Strapi</a>
</footer>  

6. Create our Index Page

Important links from Video:

Articles list

First, we want to display the list of articles. To do so, add the following content in the existing home page file:

Path: blog/src/pages/index.js

What are we doing here?

At the end of the file, we export pageQuery, a GraphQL query which requests the entire list of articles. As you can see, we require only the id, title and content fields, thanks to the precise GraphQL query language.

Then, we pass the { data } destructured object as parameter of IndexPage and loop on its allStrapiArticle object to display the data.

Tutorial

Tip: generate your GraphQL query in seconds!

Gatsby includes a useful GraphiQL interface. It makes GraphQL queries development way easier and intuitive. Take look at it and try to create some queries.

Adding images

To add images, we will need to import Img from package gatsby-image installed by default. Replace the content of blog/src/pages/index.js with the following :

Path: blog/src/pages/index.js

Tutorial

7. Create the Article page view

Important links from Video:

Article view

Our website now starts looking like a blog which is a good thing. However, an important part is still missing: the article’s details page.

Let's create the template, containing a specific GraphQL request and defining the content displayed:

In order to do this, first create a folder called templates in your src directory. Then within templates create a file called article.js.

Path: blog/src/templates/article.js

That looks fine, but at this point, Gatsby does not know when this template should be displayed. Each article needs a specific URL. So, we are going to inform Gatsby about the new URLs we need thanks to the createPage function.

First, we are going to code a new function called makeRequest to execute the GraphQL request. Then, we export a function named createPages in which we get the list of articles and create a page for each of them. Here is the result:

Path: blog/gatsby-node.js

Restart the Gatsby server.

From now on, you should be able to visit the detail page by clicking on URLs displayed on the homepage.

Tutorial

8. Gatsby Images and author page

Important links from Video:

Fluid Images

Note: In the video, the maxWidth attribute of the image (in the graphql variable) was set to 500. However, this should have been set to 960, which matches the max-width of the enclosing container div.

Give your header image a fluid/responsive image.

Path: blog/src/templates/article.js

A. Edit the query variable export to match:

export const query = graphql`  
  query ArticleTemplate($id: String!) {
    strapiArticle(id: { eq: $id }) {
      title
      content
      image {
        childImageSharp {
          fluid(maxWidth: 960) {
            ...GatsbyImageSharpFluid
          }
        }
      }
      author {
        id
        username
      }
    }
  }
`

B. Edit the <Img /> component tag as follows:

<Img fluid={data.strapiArticle.image.childImageSharp.fluid} />  

Author view

Articles are written by authors. They deserve a dedicated page.

The processes for creating author views and article pages are very similar. First, create a new file in our templates folder called, author.js. Add the code below to this file.

Path: blog/src/templates/author.js

Second, we update the gatsby-node.js file to create the URLs (with the below code):

Path: blog/gatsby-node.js

Finally, restart the server and visit the author page from the article view's links.

Tutorial

8B. Specify Node Version

Important links from Video:

On April 23, 2019 Node v12.0.0 was released. There is an incompatibility or bug that is present regarding SQLite.

Therefore, make the following change to your package.json file found in your Strapi project root:

Path: cms/package.json

Change the enginesobject from:

  "engines": {
    "node": ">= 10.0.0",
    "npm": ">= 6.0.0"
  },

To:

  "engines": {
    "node": "10.x",
    "npm": ">= 6.0.0"
  },

After changing your file and saving it, you may simply continue to the next section.

9. Deploy to Heroku

Important links from Video:

We will deploy Strapi to Heroku. You will need a free account with Heroku.

Next install the Heroku CLI.

These commands are to login to Heroku and to create a new Strapi Project.

Path: ./

heroku login  

Edit .gitignore file

Open your editor and add package-lock.json to the .gitignore file.

Path: cms/.gitignore

############################
# Strapi Heroku
############################

package-lock.json

Next, you will need to init Git and commit your project

cd cms  
git init  
git add .  
git commit -m "Initial Commit"  

Create a Heroku Project.

heroku create  

You NEED TO set-up a database to work with Strapi. Here are step-by-step instructions to set-up a PostgreSQL or a MongoDB database. Follow the steps in the links, and then continue below.

Lastly, commit, push to heroku, and open your project.

git commit -am "Update database config"  
git push heroku master  
heroku open  

If your browser window open at the Heroku URL, congratulations. If not, please review the documentation and the video for additional details.

Set-up Administrator and User Roles

Your browser should have opened back up to the Strapi Welcome page. Click on the /admin link to enter the Administrator User.

  • Complete the form for the first Administrator User.
  • Click on Users located under CONTENT TYPES in the left-hand menu.
    • Click the blue + Add New User button in the top right corner.
    • Next, complete the Username, Email, and Password fields.
    • Select ON for the Confirmed toggle field.
    • To the right, under Role, select Authenticated.

Configure the WYSIWYG Editor View

When you locally created the Article content, you checked WSYISWG as a setting for the content field. When you created a new install for Heroku with PostreSQL, you lost these settings. You will now reset these settings:
- Click on Content Manager in the left-hand menu - Then under Content Types, click on Article - Click the Edit View (Settings) tab and then under LAYOUT - Displayed Fields - click and highlight the content field. - Scroll down and toggle ON for Display as WYSIWYG

Continue to adding content below.

Insert some entries

Articles now need to be added again to the Production installation of Strapi. Add some articles in the database. To do so, follow these instructions:

  1. From you Dashboard, click on the Articles content type in the left-hand menu.
  2. Click on Add New Article.
  3. Insert values, link to an author and submit the form.
  4. Create two other articles.

Note: You can download the sample content from the video here.

9A. Configure again Permissions

You have to allow access through the API under Roles & Permission from your Strapi Dashboard.

You have already set these permissions on your local Dev environment. But these settings need to be set again for Heroku as these settings are saved to a database and the Heroku PostgreSQL database is different than your local Dev environment.

  • Login to your Strapi Dashboard, from https://your-heroku-url.herokuapp.com/admin.
  • Go to Roles and Permission and then click on Public. Set your Article permissions so find and findone are checked.

  • Within Roles and Permissions and Public, scroll to and click on USERS-PERMISSIONS, and set User permissions find to checked.

  • Save these changes

You have now allowed access through the API to Articles, Article and Users.

10. Set-up Cloudinary & Netlify Predeploy

Important links from Video:

DEMO Urls:

API demos:

At this point, when you upload images to Strapi on Heroku, the images are not permanently saved. The reason is because they are saved to a temporary cache which gets deleted whenever Heroku goes to sleep.

Therefore, you will want to use a 3rd party service to upload to and then serve your images from. This tutorial continues with Cloudinary.

Next, install the plugin with npm, commit and push your changes to Heroku:

Path: ./cms

npm i --save strapi-provider-upload-cloudinary  
git add .  
git commit -m "Installed Cloudinary Plugin"  
git push heroku master  

Wait for Heroku to install the packages and to restart the server instance.

From your Cloudinary console, you will find your Cloudinary credentials to enter in Strapi:

From the Strapi Dashboard, click on Plugins and then for FILES UPLOAD click the cog icon.

Select Cloudinary in the Providers dropdown and enter in your credentials:

  • Cloud name
  • API Key
  • API Secret

Then save your changes in the Upload - Settings.

Delete from Files Upload the references to previously uploaded images.

Now, for each content-type containing images, upload again the images that corresponds to your existing content:

From now on, new content will automatically have their images saved and served from Cloudinary.

11. Deploy Gatsby to Netlify

Important links from Video:

You are going to need to prepare a few things:

Next, the Gatsby part of your project, needs to be pushed to your new GitHub repo:

Path: ./blog/

git init  
git add .  
git commit -m "first commit"  
git remote add origin git@github.com:YOUR-NAME/YOUR-NEW-EMPTY-REPO.git  
git push -u origin master  

After setting up your Gatsby site on GitHub for deployment to Netlify, we need to edit the gatsby-config.js.

Locate gatsby-source-strapi plugin object and replace it with the following code:

Path: ./blog/gatsby-config.js

    {
      resolve: `gatsby-source-strapi`,
      options: {
        apiURL: process.env.DEPLOY_URL
          ? "https://YOUR-APP-URL.herokuapp.com"
          : "http://localhost:1337",
        contentTypes: [`article`, `user`],
        queryLimit: 1000,
      },
    },

Open your .gitignore file and add package-lock.json to the ignore list.

Path: ./.gitignore

...

# Yarn
yarn-error.log  
.pnp/
.pnp.js
# Yarn Integrity file
.yarn-integrity

package-lock.json  

Next, you need to git add, git commit and git push your new changes. From your command line:

Path: ./blog/

git add .  
git commit -m "Update config-gatsby.js and .gitignore file"  
git push  

In order to easily push your Gatsby site to Netlify, you have to install and login to Netlify using the Netlify CLI:

From your command line:

npm install netlify-cli -g  
netlify login  

Press the Authorize button and close the tab or window.

Netlify is now set-up on your computer. It's time to initialize your project (Please pay close attention to the build command and directory):

Path: ./blog/

netlify init  
? What would you like to do? + Create & configure a new site
? Site name (optional): 
? Team: YOUR NAME HERE

Site Created

Admin url: https://app.netlify.com/sites/SITE-NAME  
Site url:  https://SITE-NAME.netlify.com  
Site ID: YOUR-UNIQUE-SITE-ID

? Your build command (hugo/yarn run build/etc): gatsby build
? Directory to deploy (blank for current dir): public
? No netlify.toml detected. Would you like to create one with these build settings? Yes

Creating Netlify Github Notification Hooks...  
Netlify Notification Hooks configured!

Netlify CI/CD Configured!

The site is now configured to automatically deploy from github branches & pull requests

Next steps:

  git push       Push to your git repository to trigger new site builds
  netlify open   Open the Netlify adlin URL of your site  

A last git add, git commit and git push are needed in order to finish the connection between your github and Netlify. Then open your Netlify Deployment Console.

From your command line:

Path: ./blog/

git add .  
git commit -m "netlify config settings files"  
git push  
netlify open  

After Netlify finishes deploying your site, you can click the green site link to see it.

12. Webhooks with Gatsby & Strapi

Important links from Video:

Create and Copy a Netlify WebHook URL

  1. Login into your Netlify Login
  2. From your App, go to: Settings -> Build & deploy -> Continuous deployment -> Build hooks
    • Click Add build hook
    • Give your app a build hook name, e.g. strapiUpdate
    • Save it and then copy the issued URL to the clipboard.

Add a Variable to your custom.json file

You will need to create a variable for the webhook. We will use this variable to update any content-type and their models. If the webhook changes, you will only need to change this variable.

Path: ./cms/config/environments/production/custom.json

Add the following line:

  "staticWebsiteBuildURL": "https://api.netlify.com/build_hooks/5cc30b_YOUR_CUSTOM_URL_2a83"

And it should look like this after:

{
  "myCustomConfiguration": "This configuration is accessible through strapi.config.environments.production.myCustomConfiguration",
  "staticWebsiteBuildURL": "https://api.netlify.com/build_hooks/5cc30b_YOUR_CUSTOM_URL_2a83"
}

Modify the model for the Article Content Type

The following is the new Article.js file. This file now has additional code that use the variable withe the netlify webhook. Whenever this Content Type is creates a new instance, updates one or deletes one of the content types, it will fire a Post request to Netlify using the Webhook URL.

Path: ./cms/api/article/models/Article.js

'use strict';

const axios = require('axios');

/**
 * Lifecycle callbacks for the `Article` model.
 */

module.exports = {  
  // Before saving a value.
  // Fired before an `insert` or `update` query.
  // beforeSave: async (model, attrs, options) => {},

  // After saving a value.
  // Fired after an `insert` or `update` query.
  // afterSave: async (model, response, options) => {},

  // Before fetching a value.
  // Fired before a `fetch` operation.
  // beforeFetch: async (model, columns, options) => {},

  // After fetching a value.
  // Fired after a `fetch` operation.
  // afterFetch: async (model, response, options) => {},

  // Before fetching all values.
  // Fired before a `fetchAll` operation.
  // beforeFetchAll: async (model, columns, options) => {},

  // After fetching all values.
  // Fired after a `fetchAll` operation.
  // afterFetchAll: async (model, response, options) => {},

  // Before creating a value.
  // Fired before an `insert` query.
  // beforeCreate: async (model, attrs, options) => {},

  // After creating a value.
  // Fired after an `insert` query.
  // afterCreate: async (model, attrs, options) => {
  afterCreate: async entry => {
    axios
      .post(strapi.config.currentEnvironment.staticWebsiteBuildURL, {})
      .catch(() => {
        // Ignore
      });
  },

  // Before updating a value.
  // Fired before an `update` query.
  // beforeUpdate: async (model, attrs, options) => {},

  // After updating a value.
  // Fired after an `update` query.
  // afterUpdate: async (model, attrs, options) => {
  afterUpdate: async entry => {
    axios
      .post(strapi.config.currentEnvironment.staticWebsiteBuildURL, {})
      .catch(() => {
        // Ignore
      });
  },

  // Before destroying a value.
  // Fired before a `delete` query.
  // beforeDestroy: async (model, attrs, options) => {},

  // After destroying a value.
  // Fired after a `delete` query.
  // afterDestroy: async (model, attrs, options) => {
  afterDestroy: async entry => {
    axios
      .post(strapi.config.currentEnvironment.staticWebsiteBuildURL, {})
      .catch(() => {
        // Ignore
      });
  },
};

Install Axios

Your new code changes require the installation of an npm package called, axios.

From you command line:

Path: ./cms

npm i axios --save  

Commit and Push to Heroku and Update Netlify

You will now need to add, commit and push your changes in the project. These changes were made in the Strapi files. Doing this will automatically fire a Post request to Netlify, which will update Netlify automatically.

From your command line:

Path: ./cms/

git add .  
git commit -m “added webhook for netlify”  
heroku login  
git push heroku master  

Webhooks configured

After Netlify has had a moment to issue the command to rebuild and has done so, you will be able to login into your Heroku based Strapi project and make updates which automatically update Netlify.

Additional Content Types

In this example tutorial we created one Content Type called, article. You will need to update the model file (as above) for every additional Content Type you create for your project AND which should trigger a Gatsby rebuild.

13. Adding Markdown Support

Important links from Video:

Adding Markdown Support

The next steps involve adding Markdown support to the Gatsby build. In this way, your content from Strapi will properly transform from Markdown to HTML.

In this example, the tutorial article, "Bed and breakfasts Give a Personal Touch", the main content area is not properly formatted.

At the end of this section, the content will properly transform Markdown to HTML. You can see the final transformation here.

A React package called React Markdown needs to be installed in order properly parse the Markdown and transform it to HTML.

Install React Markdown

The package repo can be found at React Markdown.

From your command line:

Path: ./blog/

npm install --save react-markdown  

Use React Markdown in a Component

Next, several steps need to occur. These steps include importing the package into each of the index.js, article.js and author.js template pages. And then, adding the React component.

The import statement looks like this:

import ReactMarkdown from "react-markdown"  

And the ReactComponent for the article.js file looks like this:

<ReactMarkdown  
   source={document.node.content}
/>

Note: The source option from react-markdown is simply accepting the content from the graphQL query. You will need to also delete <p>{document.node.content}</p> from the markup.

Path: ./blog/src/templates/article.js

The complete article.js code looks like this at this point:

import React from "react"  
import { Link, graphql } from "gatsby"  
import Img from "gatsby-image"  
import Layout from "../components/layout"  
import ReactMarkdown from "react-markdown"

const ArticleTemplate = ({ data }) => (  
  <Layout>
    <h1>{data.strapiArticle.title}</h1>
    <p>
      by{" "}
      <Link to={`/authors/User_${data.strapiArticle.author.id}`}>
        {data.strapiArticle.author.username}
      </Link>
    </p>
    <Img fluid={data.strapiArticle.image.childImageSharp.fluid} />
    <ReactMarkdown source={data.strapiArticle.content} />
  </Layout>
)

export default ArticleTemplate

export const query = graphql`  
  query ArticleTemplate($id: String!) {
    strapiArticle(id: { eq: $id }) {
      title
      content
      image {
        childImageSharp {
          fluid(maxWidth: 960) {
            ...GatsbyImageSharpFluid
          }
        }
      }
      author {
        id
        username
      }
    }
  }
`

You have to repeat these steps for the index.js and author.js.

Note: There source option is different as each of these templates are querying the data differently than the article.js file.

Path: ./blog/src/templates/author.js

The complete author.js code looks like this at this point:

Note: You will need to also delete <p>{article.content}</p> from the markup.

import React from "react"  
import { Link, graphql } from "gatsby"  
import Layout from "../components/layout"  
import ReactMarkdown from "react-markdown"

const UserTemplate = ({ data }) => (  
  <Layout>
    <h1>{data.strapiUser.username}</h1>
    <ul>
      {data.strapiUser.articles.map(article => (
        <li key={article.id}>
          <h2>
            <Link to={`/Article_${article.id}`}>{article.title}</Link>
          </h2>
          <ReactMarkdown source={article.content} />
        </li>
      ))}
    </ul>
  </Layout>
)

export default UserTemplate

export const query = graphql`  
  query UserTemplate($id: String!) {
    strapiUser(id: { eq: $id }) {
      id
      username
      articles {
        id
        title
        content
      }
    }
  }
`

Path: ./blog/src/pages/index.js

The complete index.js code looks like this at this point:

Note: You will need to also delete <p>{document.node.content}</p> from the markup.

import React from "react"  
import { Link, graphql } from "gatsby"  
import Img from "gatsby-image"  
import Layout from "../components/layout"  
import ReactMarkdown from "react-markdown"

const IndexPage = ({ data }) => (  
  <Layout>
    <h1>Hi people</h1>
    <p>Welcome to your new Gatsby site.</p>
    <p>Now go build something great.</p>
    <ul>
      {data.allStrapiArticle.edges.map(document => (
        <li key={document.node.id}>
          <h2>
            <Link to={`/${document.node.id}`}>{document.node.title}</Link>
          </h2>
          <Img fixed={document.node.image.childImageSharp.fixed} />
          <ReactMarkdown source={document.node.content} />
        </li>
      ))}
    </ul>
    <Link to="/page-2/">Go to page 2</Link>
  </Layout>
)

export default IndexPage

export const pageQuery = graphql`  
  query IndexQuery {
    allStrapiArticle {
      edges {
        node {
          id
          image {
            childImageSharp {
              fixed(width: 200, height: 125) {
                ...GatsbyImageSharpFixed
              }
            }
          }
          title
          content
        }
      }
    }
  }
`

If you take a look at your project, you will see that the Markdown is now properly transforming into HTML. However, still missing is the ability to parse images from within the content.

Use Images with your Content

Strapi easily saves your images to whichever Provider is configured. In this tutorial, it is Cloudinary. However, not all projects will use Cloudinary and in development, images are often saved to Strapi locally. Therefore, you will need to set an environment variable and instruct Gatsby how to parse the image path.

Setting and using environment variables is a big subject. This Gatsby article does a good job explaining how Gatsby uses them.

In this tutorial, an environment variable is used to prepend http:localhost:1337 to the image path for image uploaded in Development (gatsby develop) as Strapi is saving the images locally.

Path: ./blog/

In the Gatsby project root create a file and call it .env.development. Add the following line:

IMAGE_BASE_URL=http://localhost:1337  

This has created a variable called IMAGE_BASE_URL which the Reactmarkdown component will use IF the image path does not have a complete URL.

React-markdown has an option called, transformImageUri. This option makes the image path available for use within the component and so within its value pair, a ternary operator will be used to provide the logic and check if its a complete path or not. If it is not a complete path, the env variable will be used to create one.

In index.js the component now looks like this:

Path: ./blog/src/pages/index.js

<ReactMarkdown  
   source={document.node.content}
   transformImageUri={uri => uri.startsWith('http') ? uri : `${process.env.IMAGE_BASE_URL}${uri}`}
/>

Edit the article.js and author.js and add the transformImageUri option to their <ReactMarkdown> components:

Path: ./blog/src/templates/article.js

<ReactMarkdown  
   source={data.strapiArticle.content}
   transformImageUri={uri => uri.startsWith('http') ? uri : `${process.env.IMAGE_BASE_URL}${uri}`}
/>

Path: ./blog/src/templates/author.js

<ReactMarkdown  
   source={article.content}
   transformImageUri={uri => uri.startsWith('http') ? uri : `${process.env.IMAGE_BASE_URL}${uri}`}
/>

NOTE: This simple checks if uri starts with http, if it does then it's a complete path and if it doesn't then it is locally hosted with a relative path and the IMAGE_BASE_URL is prepended.

Note: You can check if this works by going to Plugins > FILES UPLOAD > cog and changing the Provider back from Cloudinary to Local Provider. You will need to add back your images from within your Content Types to test this.

You content is now properly parsed and transforming from Markdown to HTML. The following section is an Optional section that will provide some styling (and instruction) for the index.js and author.js pages and also implement and allow the use of plain HTML within the content.

OPTIONAL: Creating a Basic Blogroll

The index.js page currently displays every article. The issue is that the page displays the entire article. Normally, on this type of index page, a snippet is showed with a Read more link.

To accomplish this functionality various things need to be done:

  1. Add a CSS class through the react-markdown package and component
  2. This CSS class allows for removing the images as well as give a uniform height with CSS for the content in the index type pages.
  3. Add JavaScript to omit any text after 500 characters and add ... to the end of the snippet.
  4. Add a link for the Read more.
  5. Add a global.css stylesheet with a few styles.

These changes are the same for both the index.js page and the author.js template. Edit these files like this:

index.js

Path: ./blog/src/pages/index.js

<ReactMarkdown  
   source={document.node.content.substring(0, 500).concat("...")}
   transformImageUri={uri => uri.startsWith('http') ? uri : `${process.env.IMAGE_BASE_URL}${uri}`}
   className="indexArticle"
/>

<Link to={`/${document.node.id}`}>Read more</Link>

author.js

Path: ./blog/src/templates/author.js

<ReactMarkdown  
   source={article.content.substring(0, 500).concat("...")}
   transformImageUri={uri => uri.startsWith('http') ? uri : 
   `${process.env.IMAGE_BASE_URL}${uri}` }
   className="indexArticle" 
/>

<Link to={`/Article_${article.id}`}>Read more</Link>  

NOTE: Make sure the above code is within the closing li tag.

Add the CSS

Path: ./blog/src/

Create a folder and call it styles.

Path: ./blog/src/styles/

Create a file called global.css

Within the global.css file, add the following styles to provide a uniform height to each of your snippets and Read more links. The CSS will also hide any images within the content there.

Note: The follow CSS styles target the className option above.

.indexArticle {
  max-height: 250px;
  overflow: hidden;
}

.indexArticle img {
  display: none;
}

Link the CSS file

In order to use this new global.css file, you need to import it at the top of each page and template.

For example, for the index page, add import "../styles/global.css

Path: ./blog/pages/index.js

import React from "react"  
import { Link, graphql } from "gatsby"  
import Img from "gatsby-image"  
import Layout from "../components/layout"  
import ReactMarkdown from "react-markdown"

import "../styles/global.css"  

Add the import statement for each of the other pages you would like to have global CSS Styles for.

OPTIONAL: Adding plain HTML support to the markdown

Your project has index pages that show snippets and provide your users a link to read the full article. The next optional part of this section is to add HTML-in-Markdown support to your markdown.

By default, react-markdown escapes HTML contained with the markdown. This is done when the editing environment is not controlled and unwanted code injections are being guarded against. However, with the Strapi editor this is not a problem and there are various scenarios where supporting HTML-in-Markdown is desirable.

In this tutorial, the use case demonstrated is the ability to add classes to the images within the content. It is expected that your CSS will have a default size for the content images. In this case, using markdown syntax for the images is perfect.

For smaller, larger or floated images, for example, HTML support is needed as markdown does not natively support adding classes within the editing experience.

There are two steps to configure your project to allow HTML-in-Markdown:

  1. Add the react-markdown option that sets the escapeHTML={false} from {true}
  2. Add a few CSS classes for .small and .large CSS classes.

Set the 'escapeHTML' option

React-markdown sets an option called, escapeHTML to true by default. You need to set this to true. Add the escapeHTML={false} option to your <Reactmarkdown /> component. Like this:

For the article.js

Path: ./blog/src/templates/article.js

<Reactmarkdown  
   source={article.content.substring(0, 500).concat("...")}
   transformImageUri={ uri =>
   uri.startsWith("http")
      ? uri
      : `${process.env.IMAGE_BASE_URL}${uri}`      }
      className="articleContent"
      escapeHtml={false}
 />

NOTE: Add escapeHTML={false} to the index.js and author.js files in the same way.

Add the classes to the CSS

In this tutorial, two classes are demonstrated. They are added to the global.css file.

Path: ./blog/src/styles/global.css

.articleContent img {
  display: block;
  margin: 0 auto;
  width: 400px;
}

.articleContent .small {
  width: 100%;
  max-width: 250px;
}

.articleContent .large {
  width: 100%;
  max-width: 600px;
}

This CSS gives a standard size and centers any images added with markdown. And images can now be added with HTML directly in markdown and with the classes added.

For example,

<img class="small" src="path-to-image/gatsby.png" alt="Small Gatsby Logo" />  

Update Git repo for the project to update Netlify

Netlify makes it easy to update the project. Once you push to GitHub, Netlify will automatically rebuild the project.

Path: ./blog/

git add .  
git commit -m "added markdown support"  
git push  

After a few minutes, your Gatsby project hosted on Netlify will have its files updated and you can go to your Strapi installation on Heroku and add an article Content Type which will now use and properly display markdown.

Conclusion

Congrats! You’ve successfully built a super fast and easy-to-maintain blog!

Since the content is managed by Strapi, the authors can write articles through a nice UI and developers only have to rebuild the Gatsby blog in order to update the content.

Where to go next?

Feel free to continue this project to discover both Gatsby and Strapi advantages. Here are some features you can add: list of authors, article's categories, and comment system with the Strapi API or Disqus. You can also create other types of websites (e-commerce shop, corporate website, etc.).

When your project is achieved, you will probably want to deploy it. The static website generated by Gatsby can easily be published on storage providers: Netlify, S3/Cloudfront, GitHub pages, GitLab pages, Heroku, etc. The Strapi API is a headless CMS, so it can be hosted on Heroku or any Linux instance that has Node.js installed.

The code source of this tutorial is available on GitHub. To see it live, clone the repository, run npm run setup, start the Strapi server (cd cms && strapi start) and the Gatsby server (cd blog && gatsby develop).

We hope you enjoyed this tutorial. Feel free to comment on it, share it, and let us know how you create sites built with React and how you manage their content.