You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/docs/sourcing-from-graphcms.md
+167-85
Original file line number
Diff line number
Diff line change
@@ -4,158 +4,240 @@ title: Sourcing from GraphCMS
4
4
5
5
## Headless the GraphCMS way
6
6
7
-
[GraphCMS](https://graphcms.com?ref="gatsby-headless-docs-top") is a headless CMS that is optimized for working with GraphQL. Content structures like posts, authors, products and more are broken down into content types called "models." These models can then be queried with the familiar GraphQL syntax.
8
-
9
-
One of the benefits of GraphCMS when working with Gatsby is that it supports GraphQL natively which allows you to test your content queries before even starting your Gatsby project.
7
+
[GraphCMS](https://graphcms.com?referrer=gatsby-headless-docs-top) is a GraphQL native Headless Content Management System (Headless CMS) that lets you programmatically deliver content across platforms. With features like an intuitive schema builder, GraphQL mutations API, and out of the box localization, GraphCMS enables you to rapidly build digital projects with your preferred frameworks and languages.
10
8
11
9
## Getting started
12
10
13
-
In this guide you'll create a complete project capable of querying data from GraphCMS.
11
+
In this guide you'll create a Gatsby site capable of querying data from GraphCMS.
12
+
13
+
### Prerequisites
14
+
15
+
This guide assumes the following:
14
16
15
-
### Install the boilerplate
17
+
- You have an active GraphCMS account
18
+
- You've created a new GraphCMS project (preferably using the `Blog Starter` template)
16
19
17
-
To begin, let's create a Gatsby starter site.
20
+
All schema and data references in this guide are from the GraphCMS `Blog Starter` template.
21
+
22
+
### Create a new Gatsby site
23
+
24
+
To begin, let's create a new Gatsby site using the default starter.
18
25
19
26
```shell
20
27
gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-default
21
28
```
22
29
23
-
Navigate inside of the project with `cd gatsby-site`.
30
+
Once finished, navigate inside of the project with `cd gatsby-site`.
31
+
32
+
### Add the `gatsby-source-graphcms` plugin
24
33
25
-
### Add the source plugin
34
+
> This plugin is in **beta**. Please use at your own risk!
26
35
27
-
Additionally, you need the `gatsby-source-graphql` library. Because GraphCMS uses GraphQL natively, you will take advantage of Gatsby's ability to simply stitch two GraphQL APIs together, reducing the time required to transform content. There is no need to use a special gatsby-source-x-cms plugin, the GraphQL source plugin is all you need.
36
+
In order to fetch data from your GraphCMS project, you will need to install [`gatsby-source-graphcms`](https://github.com/GraphCMS/gatsby-source-graphcms).
28
37
29
-
You can install this component with:
38
+
You can install this package with:
30
39
31
40
```shell
32
-
# Optionally with `npm install`
33
-
npm install gatsby-source-graphql
41
+
yarn add gatsby-source-graphcms@next
34
42
```
35
43
36
44
### Configure the plugin
37
45
38
-
The last step required before you can query your data is to configure the `gatsby-source-graphql` plugin. Open `gatsby-config.js` and add the following object to the plugins array. This example uses an open API from GraphCMS but you will most likely want to replace this with your own API and provide a `fieldName` that makes the most sense to your project. [Here's more information on working with GraphCMS APIs.](https://docs.graphcms.com/docs/api)
46
+
The last step required before you can query your data is to configure `gatsby-source-graphcms`. Inside of `gatsby-config.js`, add a new plugin configuration.
47
+
48
+
> We recommend using environment variables with your GraphCMS `token` and `endpoint` values. You can learn more about using environment variables with Gatsby [here](https://www.gatsbyjs.com/docs/environment-variables).
39
49
40
50
```js
41
51
{
42
-
resolve:"gatsby-source-graphql",
43
-
options: {
44
-
// The top level query type, can be anything you want!
45
-
typeName:"GCMS",
46
-
// The field you'll query against, can also be anything you want.
47
-
fieldName:"gcms",
48
-
// Your API endpoint, available from the dashboard and settings window.
49
-
// You can use this endpoint that features US mountains for now.
// Your GraphCMS API endpoint. Available from your project settings.
55
+
endpoint:process.env.GRAPHCMS_ENDPOINT
56
+
// A PAT (Permanent Auth Token) for your project. Required if your project is not available publicly, or you want to scope access to a specific content stage (i.e. draft content).
57
+
token:process.env.GRAPHCMS_TOKEN
51
58
},
52
59
},
53
60
```
54
61
55
-
If everything works correctly, you should now have your GraphCMS data added to the Gatsby source API!
56
-
57
-
### Querying for content
62
+
### Inspecting the schema
58
63
59
-
From the root of your project, run the development environment with `gatsby develop`. Once the server has started and is error free, you should be able to open the following URL in your browser:
64
+
Start the Gatsby development environment with `gatsby develop`. Once running, you will be able to access the GraphiQL explorer in your browser:
60
65
61
66
`http://localhost:8000/___graphql`
62
67
63
-
This will show you an interface where you can test your new content API.
68
+
From here, you will be able to browse the generated GraphQL schema of your Gatsby project.
69
+
70
+

71
+
72
+
The generated Gatsby types for the GraphCMS project models will all be prefixed accordingly. For example, the `Post` model from our GraphCMS project becomes a `GraphCMS_Post` type inside of Gatsby. This prefix can be [configured](https://github.com/GraphCMS/gatsby-source-graphcms#options).
73
+
74
+
Query fields also follow a similar naming convention and are prefixed by the same value as types. Gatsby will generate two root query fields per type. For example, for our `Post` model Gatsby will generate the following root query fields:
64
75
65
-
Try running this query:
76
+
-`allGraphCmsPost` for querying multiple `Post` entries
77
+
-`graphCmsPost` for querying a single `Post` entry
78
+
79
+
### Querying for content
80
+
81
+

82
+
83
+
Using the generated schema, we can begin to write GraphQL queries for Gatsby data. Consider the query below, which will return a full list of all available `GraphCMS_Post` nodes.
66
84
67
85
```graphql
68
-
query {
69
-
gcms {
70
-
mountains {
71
-
title
72
-
elevation
73
-
image {
86
+
{
87
+
allGraphCmsPost {
88
+
nodes {
89
+
id
90
+
content {
91
+
markdown
92
+
}
93
+
coverImage {
74
94
url
75
95
}
96
+
date
97
+
slug
98
+
title
76
99
}
77
100
}
78
101
}
79
102
```
80
103
81
-
Again, if everything is working properly, you should see a successful response in the shape of:
"markdown": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ergo? Huius ego nunc auctoritatem sequens idem faciam. Duo Reges: constructio interrete. Sed in rebus apertissimis nimium longi sumus. Itaque his sapiens semper vacabit. Non semper, inquam;\n\n\n\nVerum hoc idem saepe faciamus. Quamquam haec quidem praeposita recte et reiecta dicere licebit.\n\n\n\nAt coluit ipse amicitias. Certe non potest. Bonum incolumis acies: misera caecitas. Quo studio Aristophanem putamus aetatem in litteris duxisse? Idem iste, inquam, de voluptate quid sentit? Facillimum id quidem est, inquam.\n"
"markdown": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Id enim natura desiderat. Falli igitur possumus. Negat enim summo bono afferre incrementum diem. Indicant pueri, in quibus ut in speculis natura cernitur.\n\n\n\n# Lorem Ipsum\n\n\n\nNe amores quidem sanctos a sapiente alienos esse arbitrantur. Summus dolor plures dies manere non potest? Expectoque quid ad id, quod quaerebam, respondeas. Non est ista, inquam, Piso, magna dissensio. Respondeat totidem verbis. Non est igitur summum malum dolor.\n\n\n\nHic ambiguo ludimur. Nam Pyrrho, Aristo, Erillus iam diu abiecti. Si longus, levis dictata sunt. Duo Reges: constructio interrete. Deinde dolorem quem maximum?\n"
"title": "Union Types and Sortable Relations with GraphCMS"
101
132
}
133
+
102
134
// ...more results
103
135
]
104
136
}
105
137
}
106
138
}
107
139
```
108
140
109
-
### Getting content on the page
141
+
### Query implementation
142
+
143
+
Gatsby offers two means of data querying: [page queries](https://www.gatsbyjs.com/docs/page-query) and [static queries](https://www.gatsbyjs.com/docs/static-query).
144
+
145
+
#### Page query
110
146
111
-
For the purpose of this tutorial I've removed all the layout, SEO, link or other components that comprise a page in the Gatsby starter. The components are still there and 99% of users will likely want to put them back in once they understand what's happening in the code. You are just looking at the nails for right now, but the hammers, saws and other tools are still in the toolbox. Open the index file located at `src/pages/index.js` and replace the content with this code:
147
+
Page queries run at build time and can accept GraphQL variables via page context. As the name suggest, they can only be used on pages and **not** on non-page components.
148
+
149
+
The resulting data is available via the page props `data` key.
112
150
113
151
```jsx
114
152
importReactfrom"react"
115
-
import { StaticQuery } from"gatsby"
116
-
117
-
constIndexPage= () => (
118
-
<StaticQuery
119
-
query={graphql`
120
-
query {
121
-
gcms {
122
-
mountains {
123
-
title
124
-
elevation
153
+
import { graphql } from"gatsby"
154
+
155
+
functionIndexPage({ data: { posts } }) {
156
+
return (
157
+
<ul>
158
+
{posts.nodes.map(post=> (
159
+
<li key={post.id}>
160
+
<h3>{post.title}</h3>
161
+
</li>
162
+
))}
163
+
</ul>
164
+
)
165
+
}
166
+
167
+
exportconstpageQuery= graphql`
168
+
query IndexPageQuery {
169
+
posts: allGraphCmsPost {
170
+
nodes {
171
+
id
172
+
content {
173
+
markdown
174
+
}
175
+
coverImage {
176
+
url
177
+
}
178
+
date
179
+
slug
180
+
title
181
+
}
182
+
}
183
+
}
184
+
`
185
+
186
+
exportdefaultIndexPage
187
+
```
188
+
189
+
#### Static query hook
190
+
191
+
Static queries also run at build time, but can be used in all components via the `useStaticQuery` hook or `<StaticQuery />` component. However they do **not** accept GraphQL variables.
192
+
193
+
```jsx
194
+
importReactfrom"react"
195
+
import { graphql, useStaticQuery } from"gatsby"
196
+
197
+
functionIndexPage() {
198
+
const { posts } =useStaticQuery(graphql`
199
+
{
200
+
posts: allGraphCmsPost {
201
+
nodes {
202
+
id
203
+
content {
204
+
markdown
205
+
}
206
+
coverImage {
207
+
url
125
208
}
209
+
date
210
+
slug
211
+
title
126
212
}
127
213
}
128
-
`}
129
-
render={data=> (
130
-
<div>
131
-
<h1>USA Mountains</h1>
132
-
<ul>
133
-
{data.gcms.mountains.map(mountain=> {
134
-
const { title, elevation } = mountain
135
-
return (
136
-
<li>
137
-
<strong>{title}:</strong>
138
-
{elevation}
139
-
</li>
140
-
)
141
-
})}
142
-
</ul>
143
-
</div>
144
-
)}
145
-
/>
146
-
)
214
+
}
215
+
`)
216
+
217
+
return (
218
+
<ul>
219
+
{posts.nodes.map(post=> (
220
+
<li key={post.id}>
221
+
<h3>{post.title}</h3>
222
+
</li>
223
+
))}
224
+
</ul>
225
+
)
226
+
}
147
227
148
228
exportdefaultIndexPage
149
229
```
150
230
151
-
With this code, you have:
231
+
## Learn more
232
+
233
+
For additional examples of how to query and use GraphCMS data in the context of Gatsby, check out the following references:
152
234
153
-
1. Added the `StaticQuery` component to a page that allows you to fetch content from the GraphQL API.
154
-
2. Fetched some simplified data from the Mountain API, namely the title and elevation.
155
-
3. Rendered the list in the StaticQuery's RenderProp called "render".
Hopefully you've seen how easy it is to start working with GraphCMS and Gatsby. With projects of all sizes gravitating towards the benefits of the JAM stack, the time has never been better to learn how to work with Gatsby. Adding a content API in the backend with GraphCMS provides a scalable CMS that you can start using within minutes and keep using for the life of your project.
241
+
Its extremely easy to start working with GraphCMS and Gatsby. With projects of all sizes transitioning to an API-first approach, creating, enriching, and delivering your content via API to your Gatsby projects is a breeze. Adding a content API in the backend with GraphCMS provides a scalable CMS that you can start using within minutes, and have your project up and running quickly.
160
242
161
-
[Check out GraphCMS today and build "fast websites", fast!](https://graphcms.com?ref="gatsby-headless-docs-bottom")
243
+
Try GraphCMS by [getting started with the free-forever community plan](https://graphcms.com?referrer=gatsby-headless-docs-bottom&utm_source=gatsby&utm_medium=referral)
0 commit comments