Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Contentful content data in Gatsby

I'm interested in using Gatsby to build a Netlify static site using content from Contentful

Netlify has this nice gettting started Gatsby guide: ​​https://www.netlify.com/blog/2016/02/24/a-step-by-step-guide-gatsby-on-netlify

But I'm a bit unsure of how to bring Contentful into the mix. Do I need to write scripts to convert my Contentful content into Gatsby 'markdown'?

Any ideas, ideas, links appreciated!

like image 456
Max Hodges Avatar asked Jun 14 '16 16:06

Max Hodges


People also ask

How does Contentful work with Gatsby?

Contentful and Gatsby Starter. Build your first Gatsby starter with Contentful. The combination of Gatsby with a headless CMS like Contentful provides an increase in performance optimization, faster build times and greatly improves the developer experience.

Is Gatsby headless?

With plugins, Gatsby supports several headless CMS services, including Contentful, Ghost and Prismic. If you use WordPress, there's no need to switch. You can use WordPress' REST API as a headless CMS, so that your content team can continue to use the editing tools with which they're familiar.


2 Answers

Since this question was posted, an official Contentful plugin's been added to Gatsby's collection (official as in created by Gatsby team, not Contentful): https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-source-contentful

An example site's src code is here: https://github.com/gatsbyjs/gatsby/tree/master/examples/using-contentful

The plugin processes markdown via gatsby-transformer-remark and produces the resultant HTML, which you can access via Gatsby's GraphQL server w/ a query like this one from the example proj:

 contentfulProduct(id: { eq: $id }) {
      productName {
        productName
      }
      productDescription {
        childMarkdownRemark {
          html
        }
      }
      price
    }

You can use the plugin to connect both to the Content API (for published assets/content) and/or the Preview API (for both published and draft content/assets).

We use NODE_ENV to pull from the Preview API in dev and the Content API in production.

like image 86
Brandon Avatar answered Oct 02 '22 09:10

Brandon


Here's the script I am using to pull down data from Contentful: https://gist.github.com/ivanoats/e79ebbd711831be2536d1650890055c4

I run this via an npm run script before gatsby build.

I would love to work on a plugin or get ideas on better architecture for this process.

I wrote a post on this architecture in more detail on the Aerobatic blog

like image 23
Ivan Avatar answered Oct 02 '22 09:10

Ivan