Build a Minimal Site in Gatsby with Headless Oracle Content Management
Introduction
Gatsby is a React-based open-source framework for creating websites and applications.
To consume our Oracle Content Management content in a Gatsby application, we can use the Gatsby minimal sample available as an open-source repository on GitHub.
In this tutorial, we’ll build a simple minimal site in Gatsby by leveraging Oracle Content Management as a headless CMS as well as its Gatsby source plugin to connect with Oracle Content. This Gatsby minimal sample is available on GitHub.
The tutorial consists of three steps:
- Prepare Oracle Content Management
- Build the minimal site in Gatsby
- Prepare your application for deployment
Prerequisites
Before proceeding with this tutorial, we recommend that you read the following information first:
To follow this tutorial, you’ll need:
- an Oracle Content Management subscription
- an Oracle Content Management account with the Content Administrator role
- a Windows or Mac computer with Node version 10 or higher
What We’re Building
With Gatsby minimal, you can easily retrieve images and other content from your Oracle Content Management repository.
To take a look at what we’re building, here’s the end state of our tutorial, a basic Gatsby minimal site that consumes content from Oracle Content Management:
https://headless.mycontentdemo.com/samples/oce-gatsby-minimal-sample
This is what the home page will look like at the end of this tutorial:
This is what the contact us page will look like at the end of this tutorial:
To proceed, you’ll need to have an active subscription to Oracle Content Management and be logged in with the Content Administrator role.
Task 1: Prepare Oracle Content Management
If you don’t already have an Oracle Content Management instance, see the Quick Start to learn how to register for Oracle Cloud, provision an Oracle Content Management instance, and configure Oracle Content Management as a headless CMS.
For this tutorial, you’ll need to create a content model. There’s a downloadable asset pack available that will fill your empty repository with content types and associated content.
To prepare Oracle Content Management:
- Create a channel and asset repository.
- Create a content model using either of two methods:
- Method 1: Import the Oracle Content Management Samples Asset Pack
- Method 2: Create your own content model
Create a Channel and Asset Repository
You first need to create a channel and an asset repository in Oracle Content Management so you can publish content.
To create a channel and an asset repository in Oracle Content Management:
Log in to the Oracle Content Management web interface as an administrator.
Choose Content in the left navigation menu and then choose Publishing Channels from the selection list in the page header.
In the upper right corner, click Create to create a new channel. Name the channel ‘OCEMinimalChannel’ for the purpose of this tutorial, and keep the access public. Click Save to create the channel.
Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header.
In the upper right corner, click Create to create a new asset repository. Name the asset repository ‘OCEMinimalRepository’ for the purpose of this tutorial.
In the Publishing Channels field, select the OCEMinimalChannel channel to indicate to Oracle Content Management that content in the OCEMinimalRepository repository can be published to the OCEMinimalChannel channel. Click Save when you’re done.
Create a Content Model
The next step is to create a content model. You can use either of two methods:
- Method 1: Import the Oracle Content Management Samples Asset Pack
- Method 2: Create your own content model
Import the Oracle Content Management Samples Asset Pack
You can download a preconfigured Oracle Content Management sample assets pack that contains all required content types and assets for this tutorial. If you prefer, you can also create your own content model rather than download the sample assets pack.
You can upload a copy of the content we’re using in this tutorial from the Oracle Content Management Samples Asset Pack. This will let you experiment with the content types and modify the content. If you want to import the Oracle Content Management Samples Asset Pack, you can download the asset pack archive, OCESamplesAssetPack.zip, and extract it to a directory of your choice:
Download the Oracle Content Management Samples Asset Pack (OCESamplesAssetPack.zip) from the Oracle Content Management downloads page. Extract the downloaded zip file to a location on your computer. After extraction, this location will include a file called OCEMinimal_data.zip.
Log in to the Oracle Content Management web interface as an administrator.
Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header. Now select OCEMinimalRepository and click the Import Content button in the top action bar.
Upload OCEMinimal_data.zip from your local computer to the Documents folder.
Once it’s uploaded, select OCEMinimal_data.zip and click OK to import the contents into your asset repository.
After the content has been imported successfully, navigate to the Assets page and open the OCEMinimalRepository repository. You’ll see that all the related images and content items have now been added to the asset repository.
Click Select All on the top left and then Publish to add all the imported assets to the publishing channel that you created earlier, OCEMinimalChannel.
Before publishing, you need to validate all the assets. First add OCEMinimalChannel as a selected channel, and then click the Validate button.
After the assets have been validated, you can publish all the assets to the selected channel by clicking the Publish button in the top right corner.
Once that’s done, you can see on the Assets page that all assets have been published. (You can tell by the icon above the asset name.)
After importing the Oracle Content Management Samples Asset Pack, you can start building the Minimal Site in Gatsby.
Create Your Own Content Model
Instead of importing the Oracle Content Management Samples Asset Pack, you can also create your own content model.
For this tutorial, we’re using a content type called ‘MinimalMain’ as the main content type for this sample. This content type consists of header and footer logos, and a list of pages that should be included on the nav.
To create content types for the content model:
- Log in to the Oracle Content Management web interface as an administrator.
- Choose Content in the left navigation menu and then choose Asset Types from the selection list in the page header.
- Click Create in the top right corner.
- Choose to create a content type (not a digital asset type). Repeat this for all required content types.
We’ll create three content types, each with its own set of fields:
- MinimalMain
- MinimalPage
- MinimalSection
The first content type, MinimalMain, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
headerLogo | Single-value media field | headerLogo | |
footerLogo | Single-value media field | footerLogo | |
pages | Multiple-value reference field | pages |
This is what your MinimalMain content type definition should look like:
The second content type, MinimalPage, should have the following field:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
sections | Multiple-value reference field | sections |
This is what your MinimalPage content type should look like:
The third and final content type, MinimalSection, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
type | Single-value text field | X | type |
heading | Single-value text field | heading | |
body | Single-value large-text field | body | |
image | Single-value image field | image | |
actions | Single-value embedded content field | actions |
This is what your MinimalSection content type should look like:
Once you’ve created your content types, you can add these content types to the repository that you created earlier, OCEMinimalRepository:
- Log in to the Oracle Content Management web interface as an administrator.
- Navigate to OCEMinimalRepository.
- Edit the repository and, under Asset Types, specify all three newly created content types. Click the Save button to save the changes.
After adding the content types to the repository, you can open the OCEMinimalRepository repository on the Assets page and start creating your content items for all the content types.
Task 2: Build the Minimal Site in Gatsby
To consume our Oracle Content Management content in a server-side rendered Gatsby application, we can use the Gatsby minimal site sample, which is available as an open-source repository on GitHub.
Note: Remember that using the Gatsby sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own Gatsby application.
To build the minimal site in Gatsby:
- Clone the sample repository and install dependencies
- Configure the Gatsby application
- Prepare your application for deployment
Clone the Sample Repository and Install Dependencies
The Gatsby minimal site sample is available as an open-source repository on GitHub.
You’ll first need to clone the sample from GitHub to your local computer and change your directory into the repository root:
git clone https://github.com/oracle/oce-gatsby-minimal-sample.git
cd oce-gatsby-minimal-sample
Now that you have your code base, you need to download dependencies for the application. Run the following command from the root directory:
npm install
Configure the Gatsby Application
In this Gatsby minimal site sample, you need to configure a few pieces of information so that your Oracle Content Management Content connection requests can target the correct instance URL and API version with the correct channel token. These values are used in the Gatsby source plugin to access GraphQL queries to the information in Oracle Content Management.
Open the .env file in a text editor. You’ll see the following:
# The connection details for the Oracle Content Management server to be used for this application
SERVER_URL=https://samples.mycontentdemo.com
CHANNEL_TOKEN=ba0efff9c021422cb134c2fd5daf6015
# (Optional) If you need to set a proxy URL so that the application can connect outside of a firewall
# PROXY_URL=http://myproxy.company.com:80
Change each key-value pair to reflect your instance URL, the API version you want to target, and the channel token associated with your publishing channel. The channel for this tutorial is OCEMinimalChannel.
Connecting to Oracle Content Management and Downloading the Data
The Gatsby Minimal sample uses a plugin called gatsby-source-oce to connect to Oracle Content Management and to retrieve the needed data. The default behavior is to download all assets defined on the provided channel and make them available to the application using GraphQL. This includes both text and binary data. An alternate mode - used in this application - will download all assets to the cache and then download all the binaries referenced by the assets to a directory in the build that will allow them to be loaded via static URLs.
You can find out more about the plugin by looking here.
File Structure of the Gatsby Minimal Sample
/public
/contentServer
/src
/components
/images
/pages
/styles
/templates
gatsby-browser.js
gatsby-config.js
gatsby-node.js
public/contentServer - This directory contains all the images downloaded using the Gatsby source plugin.
src/components - This directory contains React components that are used to build up the pages of the application. These components display data that is passed in from the pages or templates that use them.
src/images - This directory contains the four images for social media in the footer, and the data here is not stored in the minimal sample repository.
src/pages - This directory only contains a customized error page for invalid urls. The rest of the pages are created using the pageTemplate.
src/styles - The application uses a common stylesheet located in src/styles.
src/templates - Templates are a special kind of page that can take parameters to be used in a query. This allows pages to be generated based on data only available at build time.
Special files
- gatsby-browser.js - This file initializes the global css found in src/styles.
- gatsby-config.js - This file is used to configure the Gatsby plugins used in the project. All the settings and initializations occur here.
- gatsby-node.js - This file runs first to gather all the data needed to build the site using a GraphQL query, then parses through the data matching parts of the site together, and finally builds the site pages by calling createPage for each needed page from the data.
Gatsby Minimal Site Application Flow
The flow of the Gatsby minimal site application is as follows:
- On build time, after the installation of all necessary packages, Gatsby runs gatsby-node.js located under /src.
- The queries in the section Using GraphQL to Fetch Content in Gatsby are run, and the data is taken from the cache.
- The minimalMain variable from the first query is updated such that the proper image and text data associated with each section of the page is correct based on matching IDs and names here.
- Each page’s data is passed to the Gatsby function createPage along with the proper slug and pageTemplate. The data associated with each page is a different type of minimalSection, and the pageTemplate creates the HTML associated with each type of minimalSection on each page. A consistent header and footer are also associated with each page. More details can be found here.
Note that Gatsby is a static site builder, so all the steps above are done on build time.
Also, a global css found at src/styles/styles.css implements the entire site styles. This is configured in gatsby-browser.js.
Using GraphQL to Fetch Content in Gatsby
The hierarchy of files are as follows in the minimal site:
- There is one MinimalMain asset that contains minimalPage(s), header data, and footer data. The header and footer are the same across all pages of the sample.
- Each minimalPage contains minimalSection(s) of which can be type default or announcement. Default minimalSections look like a body of text, while announcement minimalSections look like text over an image.
- Each minimalSection contains the core data for producing the site, such as a title, body of text, and/or an image.
We can now leverage the Gatsby source plugin with Oracle Content Management to fetch content so that we can render it in our Gatsby application. Additional information about the Gatsby source plugin can be found here.
The plugin is used in the application under package.json listed as a dependency:
"@oracle/gatsby-source-oce": "~1.1.1"
Once connected to the plugin, all the data needed to create the minimal site is pulled. The following are the GraphQL queries that pull all the necessary data.
: oceAsset(name: {eq: "MinimalMain"}) {
minimalMain
description
oceType
oceFields {
pages {
fields {
sections {
name
id
type
typeCategory
}
}
name
slug
}
footerlogo {
id
name
slug
}
headerlogo {
id
name
slug
}
}
slug
}: allOceAsset {
allTextData
nodes {
sections {
name
fields {
type
body
heading
image {
name
id
}
actions {
name
link
}
}
id
}
}
}: allOceAsset(filter: {staticURL: {ne: null}}) {
allImageData
nodes {
name
oceId
staticURL
} }
The first query called minimalMain searches and reads the information for the asset called “MinimalMain” in the repository. This asset should be configured to contain the directory of pages, header/footer, and other metadata.
The second query called allTextData contains all the title and main body text seen on the site.
The third query allImageData contains all the names of images needed to create the site. These three queries are used to properly associate all the text and image data to each part of the minimal site based on unique IDs and image names.
Note that the actual images are downloaded using the Gatsby source plugin, and the actual images are found under public/contentServer.
Processing the Data
The three queries run above contain all of the data needed to produce the website, but are fully processed to create the website. In order to generate the site, we need to match images and text data to the proper location on the minimalMain query result. This is done right after the queries are run in gatsby-node.js.
const minimalMainPagesResult = result.data.minimalMain.oceFields;
const allTextDataResult = result.data.allTextData;
const allImageDataResult = result.data.allImageData;
/* Populates minimalMainPageResult with proper data such as:
* 1 - All text data associated with each section on the page
* 2 - All image data associated with each section on the page (if exists)
*
* Code loops through all pages, then sections, then all text data to find matching
* text based on ID. An image search is also performed if an image should exist with the
* section. The text data and image data (if applicable) is associated with the main data
* structure of the section, which is tied to a page, which are all tied to the variable
* minimalMainPageResult.
*/
.pages.forEach((page) => {
minimalMainPagesResult.fields.sections.forEach((sectionPage) => {
page.nodes.forEach((sectionTexts) => {
allTextDataResultif (sectionTexts.sections !== null) {
.sections.forEach((sectionText) => {
sectionTextsif (sectionText.id === sectionPage.id) {
.textData = sectionText.fields;
sectionPageif (sectionText.fields.image !== null) {
.nodes.forEach((image) => {
allImageDataResultif ((image.name)
.localeCompare(sectionText.fields.image.name) === 0) {
.imageDir = image.staticURL;
sectionPage
};
})else {
} .imageName = null;
sectionPage
}
};
})
};
});
}); })
After this section of code runs, the variable minimalMainPagesResult contains all necessary information such as the image names and text data associated with each section of each page.
Creating Pages and Generating HTML
Each page is generated by calling the Gatsby function createPage and passing in a pageTemplate. The call to createPage is done at the end of gatsby-node.js as follows:
.pages.forEach((page) => {
minimalMainPagesResultif (page.slug.localeCompare('home') === 0) {
createPage({
path: '/',
component: pageTemplate,
context: {
,
page,
};
})else {
} createPage({
path: `/${page.slug}`,
component: pageTemplate,
context: {
,
page,
};
})
}; })
Each page has data that is passed to the createPage function, and a pathname is given. In this case, the ‘/’ pathname corresponds to the home site, which is often referred to as the index page. The remaining pathnames are simply the slug of the page. Each page follows the same pageTemplate below:
const Page = ({ pageContext: { page } }) => {
/* Create page with sections in @page structure
* Dynamically select between announcement with button, without button, or main body
*/
const sectionItems = [];
for (const [, value] of page.fields.sections.entries()) {
if (value.textData.type.localeCompare('announcement') === 0) {
if (value.textData.actions !== null) { // announcement with a button
.push(<Banner
sectionItems={value.imageDir}
image={value.textData.heading}
title={value.textData.body}
text={{
buttonDataurl: value.textData.actions[0].link,
label: value.textData.actions[0].name,
}}={value.textData.heading}
key/>);
else { // announcement with no button
} .push(<Banner
sectionItems={value.imageDir}
image={value.textData.heading}
title={value.textData.body}
text={value.textData.heading}
key/>);
}else { // main body type
} .push(<MainBody
sectionItems={value.textData.heading}
title={value.textData.body}
text={value.textData.heading}
key/>);
}
}
return (
<>
<div className="page">
<Header headerImageDir={page.headerDir} headerAllPages={page.headerAllPages} />
<div>
{sectionItems}</div>
<Footer footerImageDir={page.footerDir} />
</div>
</>
;
); }
For each section of each page, the HTML is placed in order into a sectionItems array and then returned below with the header and footer information. Each section type (announcement with button, announcement without button, main body) is determined from the data type, and if a button exists.
Task 3: Prepare Your Application for Deployment
The Gatsby Minimal application can run in either development or release (build) mode. Development mode is used when making and testing modifications to the project and release mode is used when producing a final result for deployment. In either mode the program will first update its cache from the Content Server as part of the build process.
To run in development mode, you need to run:
npm run develop
This will build the project and then run it giving you a URL that can be used to view it.
To produce a release build, you need to run:
npm run build
This will produce a complete static build in the /public directory of your project. This can then be deployed on a web server. If you want to test it in place you can run:
npm run serve
This will start up a local web server to host the application. It will give a base URL that can be used to view the application.
Build a Minimal Site in Gatsby with Headless Oracle Content Management
F39968-01
August 2021
Copyright © 2021, Oracle and/or its affiliates.
Primary Author: Oracle Corporation