@kontent-ai/gatsby-source
v10.0.1
Published
Source plugin providing Kontent.ai data from REST Delivery API
Downloads
6,034
Readme
Gatsby source plugin for Kontent.ai
Description
Source plugin for Kontent.ai REST Delivery API.
This repo contains a Gatsby source plugin that retrieves data from the Kontent.ai REST Delivery API.
How to install
Gatsby documentation uses npm
for installation. This is the recommended approach for plugins as well.
This plugin does not need to use yarn
, if want to use it in you project, see the documentation for switching package managers.
Install the @kontent-ai/gatsby-source NPM package.
npm install --save @kontent-ai/gatsby-source
Configure the plugin in
gatsby-config.js
file.module.exports = { plugins: [ { resolve: '@kontent-ai/gatsby-source', options: { projectId: '<ProjectID>', // Fill in your Project ID languageCodenames: [ 'default', // Languages in your project (Project settings -> Localization), ], }, }, ], };
Available options
projectId
* - <string
> Project ID from Project settings -> API keyslanguageCodenames
* - <string[]
> array of language codenames that defines what languages a configured for the project - the first one is considered as the default one. Initial "Getting started" project has configured just one languagedefault
.includeTaxonomies
- <boolean
> include taxonomies to GraphQL model. Turned off by default.includeTypes
- <boolean
> include types to GraphQL model. Turned off by default.authorizationKey
- <string
> For preview/secured API key - depends onusePreviewUrl
config. Consider using dotenv package for storing keys securely in environment variables.usePreviewUrl
- <boolean
> whentrue
, "preview-deliver.kontent.ai
" used as primary domain for data source. Turned off by default.proxy
:deliveryDomain
- <string
> Base url used for all requests. Defaults todeliver.kontent.ai
.previewDeliveryDomain
- <string
> Base url used for preview requests. Defaults topreview-deliver.kontent.ai
.
includeRawContent
- <boolean
> allows to includeinternal.content
property as a part fo the GraphQL model. Turned off by default.experimental
:managementApiTriggersUpdate
- <boolean
> allows to handle workflow step change Management API webhook trigger. Turned off by default.additionalItemFilterParams
- <string
> Additional item filter parameters to reduce the content in GraphQL model. Examplesystem.collection=marketing&system.workflow_step[neq]=archived
Empty by default.
* required property
Logging
Since the plugin is using Gatsby Reporter for error logging. You could turn on --verbose
option to see the whole error object. Be careful with these options, the output log could contain some sensitive data such as authorizationKey
.
Examples of usage
An example showing how to include this plugin in a site's gatsby-config.js
file.
module.exports = {
plugins: [
/// ...
{
resolve: '@kontent-ai/gatsby-source',
options: {
projectId: '09fc0115-dd4d-00c7-5bd9-5f73836aee81', // Fill in your Project ID
languageCodenames: [
'default', // Or the languages in your project (Project settings -> Localization),
'Another_language',
],
includeTaxonomies: true, // opt-out by default
includeTypes: true, // opt-out by default
usePreviewUrl: true, // false by default
authorizationKey: '<API KEY>', // for preview/secured API key - depends on `usePreviewUrl` setting - consider using environment variables to store the key securely
includeRawContent: true, // opt-out by default - include `internal.content` property in the gatsby nodes
proxy: {
deliveryDomain: 'custom.delivery.kontent.my-proxy.com',
previewDeliveryDomain: "custom.preview.delivery.kontent.my-proxy.com"
},
experimental: {
managementApiTriggersUpdate: true // opt-out by default
}
},
},
/// ...
],
};
The plugin creates GraphQL nodes for all Kontent.ai taxonomies, content types, content items language variants.
The queries start with kontentTaxonomy
, kontentType
, or kontentItem
prefix (respectively allKontentTaxonomy
, allKontentType
, or allKontentItem
) and their type is kontent_taxonomy_X
, kontent_type_X
, or kontent_item_X
where X
is a codename of the taxonomy
, type
, or item
.
Look at the How to query for data section for example queries.
GraphQL nodes produced by the source plugin provide the same structure as Kontent.ai Delivery REST API, but there are alternations for better usability, you could find more detailed description in Delivery API alternations section
Learning Resources
To see upgrade instructions see Upgrade section.
For more developer resources, visit the Kontent.ai Docs.
Delivery API alternations
Some of the data from Kontent.ai Delivery API requires to be altered or extended to be usable in Gatsby. There is a list of them with its description.
Preferred language
Besides of system.language
every item node contains the property preferred_language
to distinguish which language version it represents. Using this property, it is easy to distinguish whether the language fallback is used. When preferred_language
is not the same as system.language
, item was not translated to preferred_language
and the delivery API returned fallback language (system.language
).
Linked items as links
Each linked items element in linked items element as well as in rich text element is using Gatsby GraphQL node references that can be used to traverse to the nodes linked through the use of the Linked items element.
The resolution is using the createFieldExtension
called languageLink
that is resolving the codenames. Embedded @link
extension is not used because the links have to be resolved by preferred_language
as well as system.codename
equality and embedded link resolution allow using only one field to make the links out of the box.
Linked Items element
query PersonQuery {
allKontentItemPerson {
nodes {
elements {
friends {
value {
... on kontent_item_person {
id
elements {
name_and_surname {
value
}
}
}
}
}
}
}
}
}
Rich text element
query PersonQuery {
allKontentItemPerson {
nodes {
elements {
bio {
modular_content { // inline linked items as well as content components
... on kontent_item_website {
id
elements {
name {
value
}
url {
value
}
}
}
}
value
}
}
}
}
}
Rich text images and links
Kontent.ai REST API returns images and links for Rich Text element in the form of the object, not as an array:
{
"bio": {
"type": "rich_text",
"name": "Bio",
"images": {
"fcf07d43-46d4-46ef-a58d-c7bf7a4aecb1": {
"image_id": "fcf07d43-46d4-46ef-a58d-c7bf7a4aecb1",
"description": null,
"url": "https://assets-us-01.kc-usercontent.com:443/09fc0115-dd4d-00c7-5bd9-5f73836aee81/0faa87b4-9e1e-41b8-8b38-c107cbb35147/2.jpg",
"width": 1600,
"height": 1065
}
},
"links": {
"59002186-1886-48f3-b8ba-6f053b5cf777": {
"codename": "developer_community_site",
"type": "website",
"url_slug": ""
}
},
"modular_content": [],
"value": "..."
}
}
This wrapper transforms these objects into the arrays. In case of an image the ID of the image is already stored there, in case of link, the id of a link is moved to linked_id
property. The query then looks like:
query PersonQuery {
allKontentItemPerson {
nodes {
elements {
bio {
images {
# Object transformed to array
image_id
url
description
height
width
}
links {
# Object transformed to array
codename
type
url_slug
link_id # Newly generated property from object keys
}
}
}
}
}
}
Types' elements
property
Elements property is transformed from object to array.
This is the "Website" type sample. As you can see there is element
property, which is an object in Kontent.ai delivery REST API.
{
"system": {
"id": "aeabe925-9221-4fb2-bc3a-2a91abc904fd",
"name": "Website",
"codename": "website",
"last_modified": "2019-04-01T18:33:45.0353591Z"
},
"elements": {
"url": {
"type": "text",
"name": "URL"
},
"name": {
"type": "text",
"name": "Name"
},
"description": {
"type": "rich_text",
"name": "Description"
}
}
}
And here is the example how the source plugin transforms the data.
Query
{
kontentType(system: { name: { eq: "Website" } }) {
system {
codename
id
last_modified
name
}
elements {
name
codename
type
}
}
}
Result
{
"data": {
"kontentType": {
"system": {
"codename": "website",
"id": "aeabe925-9221-4fb2-bc3a-2a91abc904fd",
"last_modified": "2019-04-01T18:33:45.0353591Z",
"name": "Website"
},
"elements": [
{
"name": "URL",
"codename": "url",
"type": "text"
},
{
"name": "Name",
"codename": "name",
"type": "text"
},
{
"name": "Description",
"codename": "description",
"type": "rich_text"
}
]
}
}
}
How to query for data
This section should help you with the first queries. For further exploring it is recommended to use GraphiQL explorer available in gatsby development environment]. If you are using developer environment for the source plugin development, you could experiment according to the How to develop locally section
Querying Items
Example is showcasing how to query type article
.
For rich text resolution resolution see Rich text element component.
For url slug resolution see Rich text element component.
query ArticleQueries {
allKontentItemArticle(filter: { preferred_language: { eq: "en-US" } }) {
# filtering articles in 'en-US' preferred language (see section `Preferred language` for more information)
nodes {
elements {
title {
value # title of article (text element)
}
content {
# content element (rich text)
value # plain html
images {
image_id
url
description
}
links {
link_id
url_slug
codename
type
}
modular_content {
# inline linked items and components data
... on kontent_item_author {
id
elements {
name {
value
}
avatar_image {
value {
url
description
name
}
}
}
}
}
}
tags {
# tags element (linked items)
value {
... on kontent_item_tag {
elements {
title {
value
}
slug {
value
}
}
}
}
}
}
}
}
}
To see an example, how you can query an asset element (mainly image assets), check out the Development site example.
Querying Types
To query content types it is required to opt-in this in plugin configuration by using includeTypes
option in the configuration..
query Types {
allKontentType {
nodes {
Type: system {
# system information about the type
name
codename
}
elements {
# type's elements information
name
codename
type
options {
# filled in case the element is multiple choice
codename
name
}
taxonomy_group # filled in case the element is taxonomy
}
}
}
}
Querying Taxonomies
To query content types it is required to opt-in this in plugin configuration by using includeTypes
option in the configuration..
query Taxonomies {
allKontentTaxonomy {
nodes {
system { # system information about the type
name
codename
}
terms { # taxonomy terms
codename
name
terms { # terms are nested according to the model
codename
name
# terms ...
}
}
}
}
}
How to integrate with Gatsby Cloud
If you choose to maintain your Gatsby site on Gatsby Cloud, you will need to register two webhooks from Kontent.ai to Gatsby Cloud. Follow the "Getting started" tutorial for more information. All webhook notifications that are not mentioned in the tutorial will be ignored by the plugin.
Once you integrate your site with Gatsby Cloud, you will be able to lavarage the new cool features as Intelligent caching, true Incremental builds, or Real-time Gatsby preview.
Please note that change in taxonomies or content types require a complete rebuild of the site, because these structural data affects GraphQL schema.
Experimental workflow change handling
The source plugin is able to handle the workflow change of Kontent.ai as an experimental feature. This allows your editor in Kontent.ai to decide when to make a preview rebuild rather than automatically trigger rebuild on every auto-save event which can effectively lower the number of rebuilds in the Gatsby Cloud queue. To trigger a gatsby preview incremental build editor needs to change workflow step to the one configured in gatsby preview webhook configuration.
To allow the feature you need to:
- Allow
managementApiTriggersUpdate
option in the configuration. - Reconfigure your Gatsby preview webhook by registering new event to your for Management API trigger for workflow step change to the step you want to react on (and remove the Preview API trigger for "Preview content item Events to watch" > "Create or Update").
Disclaimer - since the Management API triggers should be used in combination with Management API and the source plugin is using Delivery (incl. Preview) API, there is no guarantee that the data will be up-to-date on Delivery/Preview API when Management API trigger is fired - so it can happen that in time of update (handling Management API trigger), there will be old data on Delivery Preview API.
Gatsby preview updates
The source plugin is capable of handling Kontent.ai Preview webhooks triggered by Delivery Preview API triggers. That means setting ENABLE_GATSBY_REFRESH_ENDPOINT
environment variable to true
opens a /__refresh
endpoint which could be used as a target endpoint to webhook with these triggers.
If you want to trigger the whole website rebuilt, it could be done by sending a post request with an empty body. It could be useful i.e. if you want to rebuild the whole site when you are developing locally (curl -X POST http://localhost:8000/__refresh
).
How to use Web Spotlight with Gatsby
Web Spotlight is an additional tool for Kontent.ai focused on website management. Feel the power of a headless CMS while enabling your content creators to produce and update content in the context of your website.
You can find more resources about this tool in the official documentation, in the recording of "Sneak Peek: An introduction to Web Spotlight" webinar, or in the blog post "Use Web Spotlight with your existing Kontent.ai projects".
To integrate your Gatsby site with Web Spotlight, it is required to do three steps:
- Prepare the code for the Web Spotlight preview environment by decorating the HTML using Kontent.ai Smart Link SDK.
- Turn on Web Spotlight on your Kontent.ai project
- Use newly enabled features to connect the Kontent.ai project to the preview environment.
How to run tests
The package is using Jest framework for testing.
To run all tests, there is an npm script prepared.
npm run test # run all tests in the repository
How to develop locally
Use a development site in development mode. And start watch mode for this repository.
npm run watch
To run complete development environment, follow the debug section the master readme
Tracking usage
The package is including tracking header to the requests to Kontent.ai, which helps to identify the adoption of the source plugin and helps to analyze what happened in case of error. If you think that tracking should be optional feel free to raise the feature or pull request.
Further information
To see upgrade instructions see Upgrade section.
For more developer resources, visit the Kontent.ai Docs.
Running projects
- Kentico Developer Community Site [source code]
- Kentico Advantage [source code]
- Richard Shackleton's Personal portfolio and blog website [source code]
- Untools by Adham Amran [source code]
- Ondřej Chrastina's personal site [source code]
- Aaron Collier's Czech Theather site [source code]
- NetConstruct agency website
- Matt Nield's personal blog site
- Ilesh Mistry's personal blog site
Guides and blog posts
- Sourcing from Kontent.ai
- Getting started with Gatsby Cloud and Kontent.ai
- Kontent.ai - The fastest headless CMS for Gatsby
- Using Gatsby with Kontent.ai
- Rendering Kontent.ai linked content items with React components in Gatsby by @rshackleton
- Adding and retrieving localized strings from Kontent.ai to GatsbyJS and GraphQL
- Automated builds with Netlify and Kontent.ai webhooks by @rshackleton
- Learning about Gatsby schema customisation with Kontent.ai by @rshackleton
- Implementing search with Gatsby and Algolia by @rshackleton
Check out the development site for some hints in the example section
Previous versions
- For version 2 see this branch.
- For version 3 see this branch.
- For version 4 see this branch.
- For version 5 see this branch.
- For version 6 see this branch.
- For version 7 see this branch.
How to contribute
Check out the contributing page to see the best places for file issues, to start discussions, and begin contributing.
- Written according to Gatsby plugin template