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.
Info
If want to skip ahead, clone the repository on GitHub to run the demo locally.
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.
- 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.
- 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
-
You should now be able to view your app on your localhost, for example, http://localhost:8000/.
-
Open your Gatsby project with your preferred code editor, for example, Visual Studio Code.
-
Go to the
src/pages
folder and replace the contents of theindex.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.
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.
- Create a folder called
lib
in thesrc
folder. Then, create a file calledprepr.js
in this folder. Copy the following code to this file to set up the endpoint:
// ./src/lib/prepr.js
export async function Prepr(query, variables) {
const response = await fetch(`${process.env.PREPR_ENDPOINT}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query, variables }),
})
return await response.json()
}
- 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_ENDPOINT=<YOUR-PREPR-API-URL>
-
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.
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.
- Make the
env
file visible to the project by updating thegatsby-config.js
file with the following configuration:
// ./gatsby-config.js
/**
* @type {import('gatsby').GatsbyConfig}
*/
// Add the .env to the basic configuration
require("dotenv").config({
path: `.env`,
})
module.exports = {
siteMetadata: {
title: `My Gatsby Site`,
siteUrl: `https://www.yourdomain.tld`,
},
plugins: [],
}
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. The next step is to fetch content from Prepr using the installed Apollo client.
npm run develop
Step 3: Fetch multiple articles
Now that your app is connected to Prepr, fetch the blog articles from Prepr.
Add a GraphQL query
-
Create a
queries
folder in thesrc
folder and create a file namedget-articles.js
in here. -
Add the following query to this file to retrieve all articles:
// ./src/queries/get-articles.js
const GetArticles = `
query {
Articles {
items {
_id
_slug
title
}
}
}
`
export default GetArticles
Tip
You can create and test GraphQL queries using the Apollo explorer from Prepr. Open the API Explorer from the Article content item page in Prepr or the access token page.
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.
In the next step, we'll fetch and process the query response.
Fetch data
Now that the query has been added, fetch the articles from Prepr and display them in the app.
- Go to the
src/pages
folder and update theindex.js
to execute the query and display the results:
// ./src/pages/index.js
import * as React from "react"
// Import the endpoint and the query
import {Prepr} from "../lib/prepr.js";
import GetArticles from "../queries/get-articles.js";
// Include the queried data as a parameter
const IndexPage = ({ serverData }) => {
// Assign a variable to the query results
const articles = serverData.data.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>
// Add function to execute the query and return the response
export async function getServerData() {
const response = await Prepr(GetArticles)
return {
props: response,
}
}
Now when you view the website on your localhost, you'll see something like the image below.
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.
Add links
First add links to the articles.
- 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 {Prepr} from "../lib/prepr.js";
import GetArticles from "../queries/get-articles.js";
const IndexPage = ({ serverData }) => {
const articles = serverData.data.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>
export async function getServerData() {
const response = await Prepr(GetArticles)
return {
props: response,
}
}
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 make this page visible when clicking on an article.
- Create a file called
get-article-by-slug.js
in thequeries
folder and add the following query to this file to query a specific article by its slug:
// ./src/queries/get-article-by-slug.js
const GetArticleBySlug = `
query ($slug: String) {
Article (slug: $slug) {
_id
title
content {
__typename
... on Text {
body
text
}
... on Assets {
items {
url
}
}
}
}
}`
export default GetArticleBySlug
Now that the query is added, fetch the individual article by its slug. Fetch the article title and the article content.
Note
The Article content is stored in a Dynamic content field. Check out the GraphQL docs for more details on how to fetch the data within this field.
- Go to the
src/pages
directory and create a file called[slug].js
with the following code to execute the query that you just created:
// ./src/pages/[slug].js
import * as React from "react"
import {Prepr} from "../lib/prepr.js";
import GetArticleBySlug from "../queries/get-article-by-slug.js";
const IndexPage = ({ serverData }) => {
const article = serverData.data.Article
return (
<main>
<h1>
{article.title}
</h1>
{article.content.map((content,index) => (
<div key={index}>
{
content.__typename === "Assets" &&
<img src={content.items[0].url} width="300" height="250" alt="{article.title}" />
}
{
content.__typename === 'Text' &&
<div dangerouslySetInnerHTML={{ __html: content.body }}></div>
}
</div>
))}
</main>
)
}
export default IndexPage
export const Head = () => <title>Home Page</title>
export async function getServerData(props) {
const slug = props.params['slug'];
const response = await Prepr(GetArticleBySlug, {slug})
return {
props: response,
}
}
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.
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: