JAMstack Basics: How to Create a Gatsby Starter with Contentful and Deploy to Netlify

Connor Wilson
ITNEXT
Published in
9 min readOct 10, 2018

--

The JAMstack has inspired some of the greatest web development tools we’ve ever seen. Publishing amazingly fast, secure, and accessible websites has never been easier, or so free. I’m still having a hard time believing my own personal website now runs for free instead of on a $15/month VPS. If you’re able to convert an older architecture to what we will discuss today, you can invest those savings in your personal development with a course or educational membership.

Photo by Pankaj Patel on Unsplash

Here’s the list of things you may learn from this article:

  • What are these new technologies and what do they do?
  • How to build a Gatsby starter, or how to start with the one I built.
  • How to setup Contentful and create your first bit of data.
  • How to link Contentful and Gatsby, use GraphQL to fetch this data and display it, and how to use Gatsby’s GraphQL playground to test queries.
  • How to deploy to Netlify, connect Contentful to Netlify to trigger builds when your data changes.

Beginner React experience is a must for developing with Gatsby.

Gatsby, Contentful, Netlify

These tools are on top of the movement, providing first-in-class services to developers in their respective areas. There are alternatives for each, which are doing similarly great things, but when I am looking for relevance for my own projects, I like to use the best.

Gatsby is a static site generator. You build your site in React, query for data with GraphQL (which is easier than it sounds) and Gatsby turns it all into static files to be served to a browser. Gatsby is pretty configurable and has a lot of plugins for you to do more advanced things, but by default it does a lot for you out of the box.

Contentful is a headless CMS. It’s like WordPress, but there is no site waiting for the user. It allows you to define the types of content you want to create, then gives you forms to create it. It then serves your content up over an API, which our static site generator will talk to when it builds.

Netlify is going to deploy our site and serve it on the web for free. All we need to do is sign in with GitHub, create a new site from our repo and do some light configuration work. Since Gatsby starters are typically hosted on GitHub anyway, we can even create a button to do all the config in advance. After your site has been deployed successfully, Netlify offers domain registrations (or you can use your own) and free HTTPS support.

The way we will be using these tools today is very simple and barely scratches the surface of what is possible, but getting your first JAMstack site under your belt is key to getting hooked on this setup. These tools do so much work for us, we can focus on building the cool stuff and let the DevOps take care of itself.

Creating a Gatsby Starter

The easiest way to get going on a Gatsby project is to use a starter. At the time of writing, there is almost 70 in the official Gatsby Starter Library, each offering different features, plugins, and extras. I’m a fan of creating my own boilerplates (like my React component library boilerplate), so let’s look at the bare minimum for a Gatsby app.

  • The baseline dependencies of React, ReactDOM, Gatsby
  • src/pages/index.js exports a React component

That’s it! A lot of starters will include a second page to demonstrate the Link component that comes with Gatsby, but we can skip that for now. There is a repo that has this bare bones starter, and you can see it on Gatsby’s GitHub. We won’t need to modify this for now, before we dive into data and plugins we need to have something to fetch!

If you want to play around with the “Hello World” example, you can do the Gatsby setup:

$ npm i -G gatsby-cli # lets us call Gatsby commands
$ gatsby new my-fun-site https://github.com/gatsbyjs/gatsby-starter-hello-world
$ cd my-fun-site
$ yarn install # or npm i
$ gatsby develop

Check out src/pages/index.js and make some changes. It will update live in your browser!

Create Contentful… Content

When you originally sign up for Contentful, they will present you with a fairly guided tutorial, so I’ll just go over the requirements for what we’re doing here.

  1. Create a space. I prefer not to use the given example space, so I deleted that and created a space called “Starter Site” that I will use here.
  2. Create a Content Model. You can think of this as something like a blog post. A blog post content model would have a title, content, tags, and any other fields you like. In your Content Model, you define these fields as well as their appearance in the form where you edit them. For the first Content Model, I am going to create one called “Home Page”. Contentful will turn your title into an API identifier, like homePage, which will be important later. I like to stick to what they generate.
  3. Create some fields in the Content Model. There are a lot to choose from, but for this example we will select four fields to get some variety once we expand our Gatsby starter. I will take the default settings for each. The fields are:
    - Title (short text)
    - Content (long text)
    - Date (date & time)
    - Image (single media)
    Don’t forget to save!
  4. Add some actual content. In the Content tab, there should be a button for “Add Home Page” if you have only made the single content type as I have. You’ll notice the editor is pretty rich, and the long text field offers a Markdown editor. Go nuts with the content here, make sure to pick a nice image and try some Markdown features in the editor. If you need content, I recommend some Cat Ipsum.
  5. Publish! Contentful will save your content.

Now that we have some basic content living in Contentful, let’s expand on the basic Gatsby starter to get this out of the cloud and into our local browser.

Hook Gatsby to Contentful and Let’s Get GraphQL

The 56th key to being a great developer is to never miss a pop culture pun. Now that we have content living in someone else’s computer, a Gatsby site running in our browser, we can connect the two. In your Contentful’s Space dashboard, there will be a button that says “Use the API”. This page will have your space ID and your access token. This is all we need to get our content, the plugin will handle everything else.

In the root directory of your Gatsby project, create a file named .env and populate it with the Contentful keys:

spaceId=**********
accessToken=***************************

Now, before you proceed, make sure your .gitignore file has .env so you never commit this file. When it comes to production keys, we will configure that later. For now, we are just getting our content locally. Now we will start to add some configuration to Gatsby. Speaking of Git, since we only created a Gatsby site, but not a repository, let’s take this time to run git init.

Quick Recap and Status Check

Thus far, we have done the following steps:

  1. Installed gatsby-cli globally on our machine, created a new project from the Gatsby Hello World starter and have installed and run it.
  2. Signed up for Contentful’s free plan and made some content.
  3. Added our keys to .env.
  4. Ran git init to create a repo.

Now, run git status and verify that .env is not being tracked. What we should see on the status report is:

On branch masterNo commits yetUntracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
LICENSE
README.md
package-lock.json
package.json
src/
nothing added to commit but untracked files present (use "git add" to track)

Installing Gatsby Plugins and Talking to Contentful

Now we can enter our first bit of configuration of Gatsby. To add configuration, we can create a file in our project root called gatsby-config.js and in the module.export object of that file, we can specify plugins. We will need to add some simple dependencies to continue:

npm i -S dotenv gatsby-source-contentful

In our gatsby-config.js file, we’ll just specify our plugin and credentials for our development environment like this:

Now, if all is well you should be able to make a query with GraphQL to talk to your Contentful API. If your terminal is running the Gatsby server, you can try looking at this query in the playground. You can see the returned object is structured much like the GraphQL query. If you’re not coding along, here is the query:

{
contentfulHomePage {
title
date
content {
content
}
image {
file {
url
}
}
}
}

The first time I did this, I had no idea where the contentfulHomePage key came from. I knew I wanted the homePage part of it, but thankfully the GraphQL playground in Gatsby has autocomplete for everything you have access to. Press (Mac) Ctrl + Space and type home and notice the options presented. From there I knew my keys of my fields, title, date, content, image and used CMD + Click on the field names to explore their properties. Having all this info at your fingertips is very useful for discovering what Contentful provides to your Gatsby site.

Now that we can see some data returned in the playground, let’s change the file at src/pages/index.js to display this. To get this content on the screen, we will use the StaticQuery component from Gatsby to send this query, and provide our JSX content via the render prop. I wrapped the rendered stuff in a React Fragment, and used some destructuring to expose the values.

You may notice that the content is displayed as raw Markdown. There is of course a Gatsby plugin for this, and it changes the query slightly. Since we’re so close to putting this content on the internet, I am going to add it in and you can view it in the source code in this diff. Let’s get this online!

Deploying to Netlify

If you haven’t already, signup for Netlify using your GitHub account. You should see from your dashboard a button that says “New site from Git”. Click it! Follow the steps to allow Netlify access to your repos. You can select specific ones, or allow it access to all current and future repos.

When you select your repo, it will likely populate the config options for you, as Netlify has identified you are working with Gatsby. Let it deploy, and let it work its magic for maybe a minute or so.

But wait… The build has failed because we haven’t told Netlify about our environment variables. The .env file we made for local work doesn’t get deployed, so in Netlify track down Site Settings > Build & Deploy > Build Environment Variables. Add your spaceId and accessToken with the same values as before.

Then, back in the Deploys tab, click the “Trigger Deploy” button, and leave the cache checkbox blank. If you have followed along this whole way, you should have a long Netlify subdomain, which contains your Contentful code generated by Gatsby!

Get Content Updates Automatically

One more thing! Since Gatsby sites are static, that means updates to your Contentful entries will not show automatically. You need to trigger a build to re-query and rebuild everything when you make content updates. Luckily, or perhaps predictably, this is easy to setup.

Back in the same section where we added the environment variables in Netlify is a section to generate a Web Hook URL. Create a new build hook, I called mine “Contentful” and copy the resulting URL to your clipboard. Make sure not to take the full CURL command they offer.

Now, in Contentful under the settings for Web Hooks, you’ll notice on the right a bunch of templates. Click the Netlify template, paste your URL and save.

Now What Do We Have?

Netlify deploys and hosts a Gatsby site with data powered by Contentful. When you update data, a new build will be triggered to keep your site up to date.

This may sound like a lot, but if you were able to follow along here and get something up on Netlify, you’re a certified published JAMstack member! Welcome to the future of web development.

Next Steps

Now that you have this all hooked up, you are able to get data, but we didn’t add much styling or anything else. Personally, I am going to evolve the starter that I’ve developed with this process with some fun bells and whistles and submit it to the Gatsby Starter Library. Let me know on Twitter how the process goes for you!

--

--

Engineering Manager @coursera, former Director of Frontend Education at @itsbridgeschool. Building things and teaching folks in Toronto.