GatsbyJS and Bloomreach CMS

​ Ivo Bronsveld

​ 2018-09-21

Ivo Bronsveld

Ivo Bronsveld is Director of Solutions & Marketplace at Bloomreach. Often the guy to come up with great solutions to challenging problems to help new customers and partners see how using the BloomReach CMS technology stack can make their life easier.

 

 

With the release of version 12.3 Bloomreach massively improved the support for Single Page Applications. Bloomreach also released the first version of the React SDK, which makes it even easier to develop single page applications on top of the platform. GatsbyJS is an interesting approach to generate React cms applications. In this blog, I will explore if you can use GatsbyJS with the content APIs.

 

Step 1: Generate a new project

 

gatsby new gogreen-sample
cdgogreen-sample
gatsby develop

 

 

You can now browse to the project by opening your browser and pointing it to http://localhost:8000/

 

Step 2: Adding a new plugin

 

GatsbyJS uses the concept of GraphQL to add dynamic data to the pages. This can be supplied by creating a so-called Source Plugin. Let’s do that now. In order to use the data from the content API, you will have to add some logic to the project. This follows the data source tutorial pretty closely.

 

 

mkdir plugins
cd plugins
mkdir br-gogreen-source-plugin
cdbr-gogreen-source-plugin
npm init
npm install node-fetch query-string --save

 

 

Now, you can create a plugin. You do that by creating a gatsby-node.js file in the directory and add the following code to the plugin code:

 

// BloomReach Go Green Source Plugin
const crypto = require("crypto");
const fetch = require("node-fetch");
const queryString = require("query-string");

exports.sourceNodes = (
 { boundActionCreators, createNodeId },
 configOptions
) => {
 const { createNode } = boundActionCreators;

 // Gatsby adds a configOption that's not needed for this plugin, delete it
 delete configOptions.plugins;

 // Process the products
 const processProduct = product => {
   const nodeId = createNodeId(`gogreen-product-${product.canonicalHandleUuid}`)
   const nodeContent = JSON.stringify(product)
   const nodeContentDigest = crypto
     .createHash('md5')
     .update(nodeContent)
     .digest('hex')

   const nodeData = Object.assign({}, product, {
     id: nodeId,
     parent: null,
     children: [],
     internal: {
       type: `GoGreenProduct`,
       content: nodeContent,
       contentDigest: nodeContentDigest,
     },
   })

   return nodeData
 }

 
   // Convert the options object into a query string
 const apiOptions = queryString.stringify(configOptions)

 // Join apiOptions with the demo.onehippo API URL
 const apiUrl = `https://www.demo.onehippo.com/restapi/topproducts?${apiOptions}`

 // Gatsby expects sourceNodes to return a promise
 return (
   // Fetch a response from the apiUrl
   fetch(apiUrl)
     // Parse the response as JSON
     .then(response => response.json())
     // Process the JSON data into a node
     .then(data => {
       // For each query result (or 'hit')
       console.log(data)
       data.forEach(product => {

    const nodeData = processProduct(product)
// Use Gatsby's createNode helper to create a node from the node data
createNode(nodeData)          
       })
     })
 )
};

 

 

Finally, you have to set up the config in the project to include the project in the build.

Modify the gatsby-config.js file in the root of the project to the following:

 

module.exports = {
 siteMetadata: {
   title: 'Gatsby Default Starter',
 },
 plugins: [
  'gatsby-plugin-react-helmet',
  {
     resolve: "br-gogreen-source-plugin",
     options: {        
       _type: 'json',
       sortby: 'hippogogreen:rating',
       sortdir: 'descending',
       max: 40
     },
   },
 ],
}

 


 

This code makes the products available in the GraphQL UI as well. You can access this UI right here: http://localhost:8000/___graphql

 

In the query box, type the following query and verify that you get some results of this query.

 

query{
 allGoGreenProduct(limit:3) {
   edges {
     node {
       name
     }
   }
 }
}

 

 

 

 

 

Step 3: Adding the listing to the page

 

You can now start using this query by changing the second page in the starter project. Change the code in page-2.js to the following:

 

import React from 'react'
import Link from 'gatsby-link'

const SecondPage = ({data}) => {

return (
 <div>
   <h1>Top Products</h1>
   <p>These are the top selling products on the BloomReach Experience GoGreen site</p>
   <Link to="/">Go back to the homepage</Link>
   <div >
   <ul>
    {data.allGoGreenProduct.edges.map(({ node }, index) =>
           
             <li>
               {node.name}
             </li>            
     )}
     </ul>
     </div>
 </div>
)}


// Use our products here
export const query = graphql`
query top3Products{
 allGoGreenProduct(limit:3) {
   edges {
     node {
       name
     }
   }
 }
}
`
export default SecondPage

 

 

If everything went well, you should see something like this:

 

 

Next steps:

 

I hope this blog post gave you an idea of how easy it is to integrate Bloomreach CMS with GatsbyJS.

Now, you have a way to add data to the GatsbyJS app, but you need to ensure this data will be modified when the source changes.

To create a proper, reusable source-plugin for the gatsbyjs.org site we would need to create an archetype that has the Content REST API pre-defined with an existing Gatsby project inside of the archetype. And of course an NPM package for the plugin. So if there is anyone, who would like to take this a step further, Bloomreach is always looking for contributions from the community.

Did you find this page helpful?
How could this documentation serve you better?
On this page
    Did you find this page helpful?
    How could this documentation serve you better?