Setting Up a Continuous Deployment Pipeline with Gatsby.js, Contentful and Netlify

Ever since I published my first entry a couple of weeks ago, I have been asked a couple questions regarding the approach I followed to set up Gatsby.js, Contentful and Netlify, so I thought it would be a good idea to write a post about it.

Please note that this is not a detailed explanation on how I modeled my Content Types inside Contentful, nor on how I queried them using GraphQL inside of Gatsby. I might write a post that addresses those subjects in the future, but for now, I wanted to focus more on the build and deployment aspect. That is, making sure that whenever you publish a new entry in Contentful (i.e. a Post, a Tag, a Category, etc), Netlify automatically generates and publishes a new version of your site with the updated content.

For this tutorial I am gonna assume you already have the following:

  • An already functional Gatsby site in your local development environment with the gatsby-source-contentful plugin installed and working.
  • A Contentful account with Administrator access to the Contentful Space you are using for your Gatsby site.
  • A Netlify account with Administrator access to your Gatsby site.

If you haven’t created a Netlify account or you haven’t linked your Git repository to it, you can use the following tutorial which will guide you step by step through that process: https://www.netlify.com/blog/2016/02/24/a-step-by-step-guide-gatsby-on-netlify

Ready? Let’s proceed then!

1. Remove your Contentful Credentials from your repository (optional)

This step is optional because you might have already taken this precaution when setting up the gatsby-source-contentful plugin, so feel free to skip to the next step if that is the case.

If not, I would urge you to follow it. Why? It is never a good idea to commit any type of credentials to your Git repository — private or public.

When you first set up the gatsby-source-contentful plugin you are required to provide both the Contentful Space ID, as well as a Contentful Access Token. So, if you hard-coded those values somewhere along the way, now it’s probably a good time to fix that — you might also want to use a tool like BFG Repo Cleaner to make sure you don’t leave any trace of those credentials in your repository history.

Assuming your gatsby-config.js file looks something like this:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: 'your-hard-coded-space-id',
        accessToken: 'your-hard-coded-access-token',
      },
    },
   }

We need to make sure to remove those hard-coded values and make it look more like this:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: process.env.CONTENTFUL_SPACE_ID || '',
        accessToken: process.env.CONTENTFUL_ACCESS_TOKEN || '',
      },
    },
   }

In other words, we need to assign those credentials to Node.js environment variables and reference those instead.

During development, the easiest way to achieve this is by installing the dotenv package from NPM, and create a file named .env at the root of your project:

npm install --save-dev dotenv
touch .env

Then in your .env file:

CONTENTFUL_SPACE_ID=your-space-id
CONTENTFUL_ACCESS_TOKEN=your-access-token

Next, make sure to tell Git to ignore that .env file from your repository by adding it to the .gitignore file:

node_modules/
public
.gatsby-context.js
.DS_Store
.intermediate-representation/
.cache/
.env

Finally, you can easily reference those environment variables by adding this line of code at the top of your gatsby-config.js file:

// gatsby-config.js

require('dotenv').config()

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: process.env.CONTENTFUL_SPACE_ID || '',
        accessToken: process.env.CONTENTFUL_ACCESS_TOKEN || '',
      },
    },
   }

If everything is set up correctly, you should be able to start Gatsby locally and the gatsby-source-contentful plugin should be fetching your content from Contentful.

2. Add your Environment Variables inside of Netlify

Since we are not committing the file which contains our Contentful credentials, we need to find another way to reference them during our build process. Fortunately, Netlify makes this extremely easy. Just go to the “Settings > Build & Deploy” section inside your Netlify Admin Dashboard and you should see an area called “Build environment variables”, where you can create the same environment variables you just added to the .env file in your local development environment.

Configuring Environment Variables in Netlify

(Before going any further, make sure to push an updated version of your Gatsby site to your remote master branch. This, in turn, should automatically trigger an initial build in Netlify.)

3. Create a Build Hook

Just below the “Build environment variables” form, you should also see another one called “Build hooks”. Add a new hook which we will specifically use to trigger Netlify’s Build process from our Contentful installation. That being the case, I recommend you to name that hook appropriately so you never forget what its purpose is — as you can see, I decided to just name mine “contentful”.

Creating Webhook in Netlify

4. Attach your Build Hook to Contentful

Now you need to log in to your Contentful Dashboard and go the Webhooks section of the Contentful Space you are working on. It should look something like this:

Contentful Webhook Screen

Click on the “Add Webhook” button and fill in the following two fields:

  1. Name: This can be anything you want, but again, I suggest you choose a name that makes sense. For example, I named mine “Trigger Netlify Build”, because that is exactly what this Webhook will do.

  2. URL: In this field, you will paste the URL endpoint you got from Netlify in the previous step (i.e. https://api.netlify.com/build_hooks/xxxxxxxxxxx)

(You can leave the HTTP authentication fields empty since they are not required by Netlify)

Lastly, you need to configure which actions in your Contentful Space will trigger a build in Netlify. You could leave the default option, “All events”, but I wouldn’t recommend it since this will end up in you triggering way too many unrequired builds.

Instead, I suggest you click on the “Only selected events” options, and select every event on the Entry row, with the very important exception of the Autosave event. Why not Autosave? Simply put, the Autosave events gets constantly triggered on Contentful when you are writing a post, even if you haven’t finished writing it. So, if you select the Autosave field, you will constantly build a site that has a half-written post on it, and we generally don’t want that.

You should end up with a Webhook configuration screen similar to this one:

Contentful Netlify Webhook Config

Save your new Webhook and voila!, we have now set up a Continuous Deployment pipeline with Gatsby.js, Contentful and Netlify. Not that difficult, right?

The next time you create, delete or update any entry inside your Contentful Space you should be able to see the changes reflected on your site within a couple of minutes. If for any reason you are not seeing the changes, go to your Netlify dashboard and review the logs of the last triggered build. In most cases, this should give you a good idea of what the problem is.

Published on: Fri Nov 24 2017
View Comments
Powered by ContentfulHosted on Netlify