Gatsby Quick start guide

Estimated duration: 10 minutes

This guide shows you how to connect Prepr to a Gatsby project to get data from Prepr CMS. You'll learn how to make a simple blog with Gatsby and Prepr CMS. By the end of this guide, you'll have a working app that looks like the image below.

Blog site end result

Info

Prerequisites

You need to have the following setup before you connect your Gatsby project to Prepr.

Step 1: Create a new Gatsby project

The instructions below will guide you on how to create an empty Gatsby project for your blog app.

If you have an existing Gatsby project then you can skip this step.

  1. Execute the command below to create a new Gatsby project.
npm init gatsby

Enter the options as shown in in the image below to create the prepr-gatsby project structure used in this guide.

gatsby options

  1. When the project is successfully created, execute the commands below to go to the prepr-gatsby folder, the root directory of the project, and to start the project.
cd prepr-gatsby
npm run develop
  1. You should now be able to view your app on your localhost, for example, http://localhost:8000/.

  2. Open your Gatsby project with your preferred code editor, for example, Visual Studio Code.

  3. Go to the src/pages folder and replace the contents of the index.js file with the following code to display your blog:

// ./src/pages/index.js 

import * as React from "react"

const IndexPage = () => {
  return (
    <main>
    <h1>
        My blog site
    </h1>
</main>
  )
}

export default IndexPage

export const Head = () => <title>My blog site</title>

You should now see something like the image below on your localhost.

view component

Step 2: Connect to Prepr

Set up a connection to Prepr to retrieve CMS data with GraphQL. The instructions below show you how to connect to Prepr directly from your project so that you can execute GraphQL queries to request data from the Prepr API.

  1. For this project we use the gatsby-source-graphql data layer to connect to Prepr. Install the data layer by executing the following command in your terminal:
npm install gatsby-source-graphql
  1. We recommend using environment variables to store sensitive information like access tokens. To add environment variables, create a .env file in the root directory of your project and add the API URL as follows:
# ./.env

PREPR_GRAPHQL_URL=<YOUR-PREPR-API-URL>
  1. Replace the placeholder value <YOUR-PREPR-API-URL> with the API URL of an access token from Prepr. This URL includes the access token for the environment you want to query from. Get this URL by logging into your Prepr account:

    a. Go to Settings > Access tokens to view all the access tokens.

    b. Copy the API URL value from the GraphQL Production access token to only retrieve published content items.

access token list

Note

Use the GraphQL Production API URL to request published content items for your live app and use the GraphQL Preview value to make a preview of unpublished content items for your content editors.

  1. Add a plugin for the Gatsby data layer and make the .env file visible to the project by updating the gatsby-config.js file with the following configuration:
// ./gatsby-config.js

/**
 * @type {import('gatsby').GatsbyConfig}
 */

// Make the .env file available to the project
require("dotenv").config({
  path: `.env`,
})

module.exports = {
  siteMetadata: {
    title: `Prepr Gatsby Quickstart`,
    siteUrl: `https://www.yourdomain.tld`,
  },

  // Include a plugin for the Gatsby data layer 
  plugins: [
    {
      resolve: "gatsby-source-graphql",
      options: {
        typeName: "Prepr",
        fieldName: "prepr",
        url: process.env.PREPR_GRAPHQL_URL,
      }
    }
  ],
}

The next step is to fetch content from Prepr using the Gatsby data layer.

Step 3: Fetch multiple articles

Now that your app is connected to Prepr, fetch the blog articles from Prepr.

  1. Go to the src/pages folder and update the index.js to add a query to retrieve all articles and display the fetched articles in the front end.
// ./src/pages/index.js

import * as React from "react"

// Import functions to execute the query
import {graphql, useStaticQuery} from "gatsby";

const IndexPage = () => {

  // Execute the query
  const preprData = useStaticQuery(graphql`
    query {
      prepr {
        Articles {
          items {
            _id
            _slug
            title
          }
        }
      }
    }
  `)

  // Assign a variable to the query results
  const articles = preprData.prepr.Articles

  return (
    <main>
      <h1>
        My blog site
      </h1>

      {/* Display a list of articles from the query results */}
      <ul>
        {articles.items.map(article => (
          <li key={article._id}>
            {article.title}
          </li>
        ))}
      </ul>
    </main>
  )
}

export default IndexPage

export const Head = () => <title>My blog site</title>

Tip

If you’re using preloaded demo data in your Prepr CMS environment as mentioned above in the Prerequisites section, you should have a few published articles as shown in the below image. The query will retrieve the ID, Slug, and Title of each article.

demo articles

Stop the server you started before (CTRL-C) and execute the command below in the terminal. If your app runs without errors, then the setup above was done correctly.

npm run develop

Now when you view the website on your localhost, you'll see something like the image below.

articles on site

Step 4: Fetch individual articles

Now that you have the list of articles, add links to them. When a visitor clicks on a link, your app should open a detailed article page automatically. The instructions below show you how to create a route from the main page to the detailed page and how to fetch the article details based on the slug of the article that was clicked.

First add links to the articles.

  1. Update the index.js file to include a link on each article title as shown in the code below.
// ./src/pages/index.js

import * as React from "react"
import {graphql, useStaticQuery} from "gatsby";

const IndexPage = () => {
  const preprData = useStaticQuery(graphql`
    query {
      prepr {
        Articles {
          items {
            _id
            _slug
            title
          }
        }
      }
    }
  `)

  const articles = preprData.prepr.Articles

  return (
    <main>
      <h1>
        My blog site
      </h1>
      <ul>
        {articles.items.map(article => (
          <li key={article._id}>

            {/* Add a link that references the article slug */}
            <a href={article._slug}>{article.title}</a>
          </li>
        ))}
      </ul>
    </main>
  )
}

export default IndexPage

export const Head = () => <title>My blog site</title>

Now when you view the app, each article has its own link. When you click on the link, a new page opens with the slug in the URL, but a Page 404 error is displayed. Continue with the next step to fetch the article details and resolve this error.

Fetch article details

Add another query to fetch a specific article by its slug and display the article detail page with the fetched data when a visitor clicks an article title in the main page.

  1. Go to the src folder and create a new subfolder called templates. In this folder create the article.js page with the query to retrieve a specific article by its slug.
// ./src/templates/article.js

import * as React from "react"
import {graphql} from "gatsby";

const ArticlePage = ({data}) => {
  const article = data.prepr.Article
  return (
    <main>
      <h1>
        {article.title}
      </h1>

      {article.content.map((content,index) => (
        <div key={index}>

          {
            content.__typename === "Prepr_Assets" &&
            <img src={content.items[0].url} width="300" height="250" alt="{article.title}" />
          }

          {
            content.__typename === 'Prepr_Text' &&
            <div dangerouslySetInnerHTML={{ __html: content.body }}></div>
          }
        </div>
      ))}
    </main>
  )
}

export const query = graphql`
  query($slug: String!) {
    prepr {
      Article(slug: $slug) {
        _id
        title
        content {
          __typename
          ... on Prepr_Text {
            body
            text
          }
          ... on Prepr_Assets {
            items {
              url
            }
          }
        }
      }
    }
  }
`

export default ArticlePage

export const Head = () => <title>Article Page</title>

Now that the query is added, fetch the individual article by its slug. Fetch the article title and the article content.

Note

  1. Go to the root directory and create a new config file called gatsby-node.js. Add the following configuration to this file to define dynamic pages for each article:
// ./gatsby-node.js


// Retrieve the article slug to create dynamic pages
exports.createPages = async ({ actions, graphql }) => {
  const { data } = await graphql(`
    query {
      prepr {
        Articles {
          items {
            _slug
          }
        }
      }
    }
  `)
  data.prepr.Articles.items.forEach( (item) => {
    const slug = item._slug

    // Create dynamic pages based on the slug of an article
    actions.createPage({
      path: slug,
      component: require.resolve(`./src/templates/article.js`),
      context: { slug },
    })
  })
}

Stop the server you started before (CTRL-C) and execute the command below in the terminal. If your app runs without errors, then the setup above was done correctly.

npm run develop

Now, when you view your site, you can click on an article which will direct you to that specific article like in the image below.

Article end result

All done

Congratulations! You have successfully connected a Gatsby project to Prepr for a simple Blog app.

Next steps

To learn more on how to expand your project, check out the following resources: