Gatsby and Contentful - How to use a headless CMS

richardmen11

Rich11

Posted on June 26, 2021

Gatsby and Contentful - How to use a headless CMS

Alt Text

What is Contentful?

Contentful is a CMS - which means Content Management System. These kinds of systems allow people
to manage content. Maybe the best known CMS is WordPress. In contrast to WordPress Contentful is headless.
What does this now mean? It means that it only provides the data which is presented by the CMS nothing else. A "normal" CMS would
also provide for example a visual part. Why is this good? Because it allows us as developers to use the
data from the headless CMS everywhere we want to. In our apps, websites and so on. The page could look completely different and the
data stays the same.

How to use Contentful with Gatsby?

As always in Gatsby we just have to use a plugin. The plugin is called gatsby-source-contentful.
This offers an easy and simple way to get the data from Contentful. Before you can start using the data, you have to set up a new account if you don't already have one.
Just sign up here for free. The basics are free and unless you do not need roles I think you are fine with the free plan.
Then you have to create your first space. You can image the space like a project you are making the content for.

Afterwards, you just could get your space ID and your accessToken. You can create them under settings > API Keys and then
generate a new one. First steps done. 🥳

Setup

Next is the setup of your Gatsby page. Just generate a new Gatsby project or use an existing one you would like to
add data from Contentful to. Then add the configuration to your gatsby-config file.

// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: `your_space_id`,
        // Learn about environment variables: https://gatsby.dev/env-vars
        accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
      },
    },
  ],
}
Enter fullscreen mode Exit fullscreen mode

Please remember to use environment variables. That is important because if somebody could get your accessToken
he could get all your content. Better be safe. 😉

First Content-Type

Now, as we are ready for take off, we would add our first content type to Contentful. But what does ContentType mean?
A ContentType is basically the layout of the content, for example a blog post could be one. Each post has a title, text and maybe an image.
Together they are a content type. So let's add our first one.

Therefore, you need to go to ContentModel and click on add content type. Then a new window appears which wants you to give the content type a name
and an autogenerated identifier. You also could provide a description which is useful for your content editor because they might not know
what a specific ContentType is used for.

After you finished this step. You are ready to add your first field. Click on add field and choose a type which fits your needs the most. For example, you could choose text.
Then you have to configure the field even further. Give it a name and change the fieldId if the auto generated not suits you. Afterwards, if you click on create and configure,
you have the chance to sharpen the configuration even more. This could make sense in different cases, but should not be a part of this article.

Then add all fields you need in your ContentType and publish the changes. Now we have added the first ContentType, but we are missing content. A ContentType is useless
without content. So let's add content. Go to the content tab and click right on the button add content. The button name could differ depending on the ContentType pre
selected. But if you have more than one ContentType you have the choice of which ContentType you want to add.

Choose the ContentType and add the content in the predefined fields. It should be like you described it before in the ContentType. Afterwards, do not forget to
save the content and publish it.

Now we are ready to use our first content pieces. 🚀

Start the Gatsby server with

gatsby develop
Enter fullscreen mode Exit fullscreen mode

After a few seconds the server has build, and we now could check if the data is available for us. To do this, visit: http://localhost:8000/\_\_\_graphql
The GraphiQL playground is really useful to see all of your data. Search for a data type called something with Contentful. The name should be something like allContentfulDataType where
dataType is the name of your ContentType you newly created on Contentful. If everything worked, you are now able to use the data from contentful in your page query.

That was easy, right?

Generate Pages

A really useful feature is that you are able to generate new pages from Gatsby. This is nothing special for Contentful but works perfect together with it.
For example, you could create a page from every blog post ContentType. So you never need to worry about adding a new page when adding a new post.

How does this work? You need to open your gatsby-node file.

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  return new Promise((resolve, reject) => {
    const template = path.resolve("./src/templates/template.js")
    resolve(
      graphql(
        `
          {
            <YOUR_GRAPHQL_CALL>
          }
        `
      ).then(result => {
        if (result.errors) {
          reject(result.errors)
        }

        const { content } = result.data

        content.edges.forEach(edge => {
          const slug = edge.node.slug
          createPage({
            path: `${slug}`,
            component: template,
            context: {
              slug,
            },
          })
        })
        return
      })
    )
  })
}
Enter fullscreen mode Exit fullscreen mode

That's a lot at once. Let me explain it. First, you get the createPages function from the actions, which we will use later.
Then you have to return a promise. Why? Because we have to call the api from Contentful and wait for the data, and we want to create pages which
also takes some time.

Then inside the promise, we take a file we created before. This file will be the template for the new created pages. Then we make our graphql query to get the data we need.
After the data comes back, we work with the result. We first check for an error and if everything is fine, we call the createPage function on every entries of the array
we got from the server. The function gets a path with has to be different for every iteration, otherwise the pages would be overwritten. Then a component which should be
our template. Lastly, it needs a context which will be available as props for the page.

That's it. I think this is awesome because you do not have to write similar pages by your own, and you are able to add content via a CMS.

What are the benefits?

But what is all this for. Why do you need this? We as developers might not need this. Because for us, it is easier to add text in our editor. For example
my personal blog is generated from Markdown. But if a non-technical person wants to add content to a page, Contentful is awesome.

At TechLabs we also build the page with contentful. We searched for an easy way to edit the pages of our locations. We wanted a way to give each
location the chance to edit their subpage. Contentful makes it easy to give them an interface to add the data and also publish new content by themselves.

Conclusion

The combination of Gatsby and Contentful could be useful for any page. It's easy to set up and gives the developer huge flexibility. As my own
experience I only could say that I really enjoy working with Contentful. Furthermore, you could configure apps and a lot more things to even
optimize your time with Contentful. But you have to try if by yourself. Contentful is free to set up and allows you to test most of its functionality
for free.

💖 💪 🙅 🚩
richardmen11
Rich11

Posted on June 26, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related