GatsbyJS Series — Integrate with CMS headless easy for everyone (Part 4)

Mr. Leo
mr-leo
Published in
5 min readJun 26, 2019

Our blog needs a backend to help manage data: content, tags, images, etc. We can build it manually from scratch: select backend framework, database, design database, implement backend logic, public APIs, find a server to host backend, etc. Honestly, it requires tons of work.

For anyone who doesn't know about CMS headless before, it’s a service that helps you to build content and then return data through APIs. Gatsby works well with CMS headless as well. We can see several suggestions from their official website here: wordpress, prismic, drupal, contentful, netlify cms, etc.

We’ll try to use Contentful service. It’s free, easy to use and suitable for a personal blog.

Space

Contentful will create an example Space after creating new account. A Space looks like a workspace or a database for one website/blog. Free version will support maximum of 2 Spaces.

We’ll create a new empty Space name mr-leo-dev instead the default one.

New empty space

Content Type

If Space is quite the same as a database, Content Type looks like a table in our database.

Next step is create one content type and define fields for it:

Select Create a content type
Add content type information: name, api identifier, description

So what are fields that blog post should have?

  • Title
  • Slug: slug or url of blog. It has to be unique.
  • Hero image
  • Description: short description or excerpt.
  • Body: body of blog. It should support markdown syntax.
  • Tags
  • Published date

We’ll create those fields for blog post content type in order:

Blog post’s fields finally

Create Content

So we have Space as database, Content Type as table, now we create data (Content) for our blog:

Content menu

Feel free to add any content you want to blog. Here I’ll move some posts from my Medium to Contentful’s content.

All contents

Generate Contentful API key

Contentful allows generating API key so that our Gatsby project can connect to its framework to fetch data.

Select API keys in Settings menu
Add API Key
Generate API keys successfully

Take note at Space ID and Content Delivery API — access token because we’ll use them later.

Setup Gatsby connect to Contentful service

The idea is Gatsby will connect to Contentful service to fetch all data we need. Then we can use GraphQL query to select suitable data to display on our blog.

gatsby-source-contentful

Is a plugin for pulling content types, entries, and assets into Gatsby from Contentful spaces. It creates links between entry types and asset so they can be queried in Gatsby by using GraphQL.

yarn add gatsby-source-contentful

At root folder, we’ll create a .contentful.json to store our Contentful APIs we created above. And remember to add this file to .gitignore because we don’t want to public sensitive information:

.contentful.json

Configuration Contentful

Next step is to configure Contentful in gatsby-config.js

gatsby-config.js

We load spaceId and accessToken from local with development environment. For production, we’ll load them as environment variables. I’ll show you how to configure that environment on Netlify later.

Now try to restart Gatsby server to apply new configuration. In order to playground GraphQL, Gatsby allows us to access http://localhost:8000/__graphql try to query some data first, before implementing to our code base. My first advice would be to always use the GraphiQL page while developing. It gives you an idea on how to use the query results on your components.

GraphiQL UI
  1. Explorer: helps us to know which entity we can query.
  2. GraphQL code
  3. Result

For example:

Query blog post from Contentful service

Fetching Data for Home Page

Time to integrate real data to our home page. We’ll need to adapt home page code a little bit. Using graphql supported by Gatsby in order to query data:

pageQuery

This query is used to query all contentul’s blog post order by publishedDate descendant.

Optimize Image loading

Gatsby supports us strongly when handling optimized images without work.

gastby-image is a React component specially designed to work seamlessly with Gatsby’s GraphQL queries. It combines Gatsby’s native image processing capabilities with advanced image loading techniques to easily and completely optimize image loading for your sites. I strongly recommend to their official documentation to understand more about this plugin and how well it is.

Install gatsby-image

yarn add gatsby-image

Note: we don’t need any more gatsby-image’s configuration in gastby-config.js as other plugins.

Update Featured Post component

Instead of hardcoding for FeaturedPost component, now we’ll adjust it a little bit:

FeaturedPost.tsx
  • Receive post information through property instead of hardcode.
  • We use Image from gastby-image instead of img html tag.
  • Update heroImage interface typescript.

Update Thumbnail Post component

Similar to FeaturedPost component, we’ll change ThumbnailPost component to support Image as well:

ThumbnailPost.tsx

Finally, our home page will become:

src/pages/index.tsx

Note: I refactored a little bit about styling.

In that example, we’re using get method from lodash to query nested objects more quickly. Install lodash as normal lirary:

yarn add lodash
yarn add @types/lodash

Looking good, let’s review our result now:

Our home page blog with real data from Contentful

Perfect!!!

Summary

So far so good. We already know how to fetch data from an external source into Gatsby project. Using GraphQL to query data and display to our frontend. We can optimize image performance easily thank for Gastby strongly support.

In the next part, we’ll create blog details pages dynamically. See you there.

--

--

Mr. Leo
mr-leo
Editor for

Developer provides high quality product. Personal blog: https://www.mrleo.dev