How to build a blog with GatsbyJS and Contentful?

Published : 7th April 2020 | by @faisaljebali
#gatsbyjs#react#contentful

In this article I will show you how to create a blog with GatsbyJS and Contentful.

What is GatsbyJS?

Gatsby is a React-based, GraphQL powered, static site generator. What does that even mean? Well, it weaves together the best parts of React, webpack, react-router, GraphQL, and other front-end tools in to one very enjoyable developer experience. Don’t get hung up on the moniker ‘static site generator’. That term has been around for a while, but Gatsby is far more like a modern front-end framework than a static site generator of old.

What is Contentful ?

Contentful is content infrastructure. Platform lets you create, manage and distribute content to any platform. Unlike a CMS, and give you total freedom to create your own content model so you can decide which content you want to manage.

Install GatsbyJS

You’ll need the gatsby-cli tool to get started. Run npm i -g gatsby in your terminal.

$ npm install -g gatsby

Then we will create a new project folder called gatsby-contentful-blogsite and include all of the starter files.

$ gatsby new gatsby-contentful-blogsite

Switch inside the directory gatsby-contentful-blogsite and run gatsby develop.

$ cd gatsby-contentful-blogsite

$ gatsby develop

Run gatsby develop and open up localhost:8000 in your browser of choice.

1 Gatsbyjs

Open your project with your favourite text editor.

node_modules/ src/ — layouts/ — — index.css — — index.js — pages/ — — 404.js — — index.js — — page-2.js yarn.lock package-lock.json package.json README.md LICENSE gatsby-browser.js gatsby-config.js gatsby-node.js gatsby-ssr.js

Create new content type in contentful

Great! We now we’ll go to the Contentful website and create a new account. Than we need to create a space for the project. Open up the sidebar and click on Create Space. Choose the free option and give your space any name. I’ll call mine posts. Select the empty space option, click Proceed to confirmation, and confirm your options.

posts

After creating the content type, we’ll start to add some fields to it A field is a building block for our content. If you have a blog post for instance, a few fields could be the title, the body, the tags and an image. This will generate a form that you’ll fill later on when we start to create actual blog posts. Follow the next steps to create a title field.

  1. Click on the Add Field button to the right of the dashboard.

  2. Select Text as the type of field you want.

  3. In the form on the next screen, enter title as the name, then click on create.

titlefield

We need to create slug field. Start by selecting Text as the type and call it slug. This time, instead of clicking Create as above, click on Create and Configure. On the next screen go to the Appearance tab and select slug as the way the field should be displayed. Also, in the Validations tab select unique field to be sure that no two blog posts have the same slugs.

Slug field

Save your changes and click on the Content button at the top of the page and select Add Post. Let's create a first blog post.

Install plugin gatsby-source-contentful

Let’s start by installing the data source plugin for Contentful.Run yarn add gatsby-source-contentful to install the package

$ yarn add gatsby-source-contentful

Or

$ npm install gatsby-source-contentful

We’ll be using Contentful’s Content Delivery API since we want to retrieve published data only, so be sure to grab the Content Delivery API key and not the Content Preview API key.

Head to your gatsby-config.js to finish the configuration.

// In your gatsby-config.js, add plugins: [ { resolve: `gatsby-source-contentful`, options: { spaceId: `your_space_id`, accessToken: `your_access_token`, }, }, ];

You should restart your development server again at this point for the new configs to kick in. When the server restarts, gatsby-source-contentful's GraphQL queries will be available to use. We can easily test if everything is working by using the GraphiQL playground that Gatsby provides for us. Open http://localhost:8000/___graphql in your browser and run the query below by pasting it into the left window on the page. The query name is allContentfulPosts because our content model is called Posts.

{ allContentfulPosts { edges { node { id slug title } } } }

The gatsby-source-contentful plugin handles all the behind the scenes fetching from the Contentful API using the keys we provided in the gatsby-config file. It then makes a semantically named GraphQL query available to us.

Then open page index.js in src/pages/index.js and paste this code bellow.

import React from "react" import { graphql, Link } from "gatsby" import Layout from "../components/layout"; export const query = graphql` { posts: allContentfulPosts { nodes { title slug } } } ` export default ({ data }) => ( <Layout> <h1>Posts : </h1> {data.posts.nodes.map(post => ( <div key={`post-${post.slug}`}> <h2> <Link to={`/${post.slug}`}> {post.title} </Link> </h2> </div> ))} </Layout> )

Programmatical page creation in Gatsby

Now we get to the fun stuff. Creating pages manually is often good enough when you don’t have a lot of content and can rely on editors knowing how to code, but in our use case that won’t work. Open up your gatsby-node.js and add this code.

exports.createPages = async ({ actions, graphql, reporter }) => { const result = await graphql(` { allContentfulPost { nodes { slug } } } `) if (result.errors) { reporter.panic("Error loading posts", JSON.stringify(result.errors)) } result.data.allContentfulPost.nodes.forEach(post => { actions.createPage({ path: `/${post.slug}/`, component: require.resolve("./src/templates/post-template.js"), context: { slug: post.slug, }, }) }) }

Then go to "src/templates" and create new page "post-template.js"

// Page src/templates/post-template.js

import React from "react" import { graphql } from "gatsby" export const query = graphql` query($slug: String!) { post: contentfulPost(slug: { eq: $slug }) { title slug } } ` const PostTemplate = ({ data: { post } }) => ( <div> <h1>{post.title}</h1> </div> ) export default PostTemplate

You should restart your development server again at this point for the new configs to kick in.

To build your Blog, you need to run gatsby build

$ gatsby build

We’re finally done with our code. The code we built isn’t that optimized, and we could style the pages a lot, but that’s not that relevant for our example.

giphy

Thanks for reading

Home page