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:

  1. Prepare Oracle Content Management
  2. Build the minimal site in Gatsby
  3. 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:

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 image shows a landing page for a Gatsby minimal site.

This is what the contact us page will look like at the end of this tutorial:

This image shows the contact us page for an Gatsby minimal site.

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:

  1. Create a channel and asset repository.
  2. Create a content model using either of two methods:

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:

  1. Log in to the Oracle Content Management web interface as an administrator.

  2. Choose Content in the left navigation menu and then choose Publishing Channels from the selection list in the page header.

    This image shows the Publishing Channels option selected in the dropdown menu in the Content page header.

  3. 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.

    This image shows the publishing channel definition panel, with ‘OCEMinimalChannel’ in the channel name field.

  4. Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header.

    This image shows the Repositories option selected in the dropdown menu in the Content page header.

  5. In the upper right corner, click Create to create a new asset repository. Name the asset repository ‘OCEMinimalRepository’ for the purpose of this tutorial.

    This image shows the repository definition panel, with ‘OCEMinimalRepository’ in the repository name field.

  6. 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.

    This image shows the repository definition panel, with ‘OCEMinimalChannel’ in the Publishing Channels field.

Create a Content Model

The next step is to create a content model. You can use either of two methods:

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:

  1. 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.

  2. Log in to the Oracle Content Management web interface as an administrator.

  3. 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.

    This image shows the Repositories page, with the OCEMinimalRepository item selected.

  4. Upload OCEMinimal_data.zip from your local computer to the Documents folder.

    This image shows the upload confirmation screen for the OCEMinimal_data.zip file.

  5. Once it’s uploaded, select OCEMinimal_data.zip and click OK to import the contents into your asset repository.

    This image shows the selected OCEMinimal_data.zip file with the OK button enabled.

  6. 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.

    This image shows the OCEMinimalRepository repository, with all assets that were just imported.

  7. 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.

    This image shows the OCEMinimalRepository repository, with all assets selected and the Publish option in the action bar visible.

  8. Before publishing, you need to validate all the assets. First add OCEMinimalChannel as a selected channel, and then click the Validate button.

    This image shows the Validation Results page, with the OCEMinimalChannel channel added in the Channels field, all assets to be validated, and the Validate button enabled.

  9. 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.

    This image shows the Validation Results page, with the OCEMinimalChannel channel added in the Channels field, all assets validated, and the Publish button enabled.

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.)

This image shows the Assets page, with all assets pubished.

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.

This image shows the home page for the Minimal sample.

To create content types for the content model:

  1. Log in to the Oracle Content Management web interface as an administrator.
  2. Choose Content in the left navigation menu and then choose Asset Types from the selection list in the page header.
  3. Click Create in the top right corner.
  4. Choose to create a content type (not a digital asset type). Repeat this for all required content types.

This image shows the Create Asset Type dialog in the Oracle Content Management web interface.

We’ll create three content types, each with its own set of fields:

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:

This image shows the definition for the content type ‘MinimalMain’. It includes these data fields: headerLogo, footerLogo, pages.

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:

This image shows the definition for the content type ‘MinimalPage’. It includes this data field: sections.

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:

This image shows the definition for the content type ‘MinimalSection’. It includes these data fields: type, heading, body, image, actions.

Once you’ve created your content types, you can add these content types to the repository that you created earlier, OCEMinimalRepository:

  1. Log in to the Oracle Content Management web interface as an administrator.
  2. Navigate to OCEMinimalRepository.
  3. Edit the repository and, under Asset Types, specify all three newly created content types. Click the Save button to save the changes.

This image shows the Edit Repository page in Oracle Content Management, with the three newly created content types associated with the OCEMinimalRepository repository.

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.

This image shows content items on the Assets page in the Oracle Content Management web interface, with options on the left for collections, channels, languages, types, content item selection, and status.

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:

  1. Clone the sample repository and install dependencies
  2. Configure the Gatsby application
  3. 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

Gatsby Minimal Site Application Flow

The flow of the Gatsby minimal site application is as follows:

  1. On build time, after the installation of all necessary packages, Gatsby runs gatsby-node.js located under /src.
  2. The queries in the section Using GraphQL to Fetch Content in Gatsby are run, and the data is taken from the cache.
  3. 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.
  4. 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:

  1. 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.
  2. 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.
  3. 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.

minimalMain: oceAsset(name: {eq: "MinimalMain"}) {
      description
      oceType
      oceFields {
        pages {
          fields {
            sections {
              name
              id
              type
              typeCategory
            }
          }
          name
          slug
        }
        footerlogo {
          id
          name
          slug
        }
        headerlogo {
          id
          name
          slug
        }
      }
      slug
    }
    allTextData: allOceAsset {
      nodes {
        sections {
          name
          fields {
            type
            body
            heading
            image {
              name
              id
            }
            actions {
              name
              link
            }
          }
          id
        }
      }
    }
    allImageData: allOceAsset(filter: {staticURL: {ne: null}}) {
      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.
    */
    minimalMainPagesResult.pages.forEach((page) => {
      page.fields.sections.forEach((sectionPage) => {
        allTextDataResult.nodes.forEach((sectionTexts) => {
          if (sectionTexts.sections !== null) {
            sectionTexts.sections.forEach((sectionText) => {
              if (sectionText.id === sectionPage.id) {
                sectionPage.textData = sectionText.fields;
                if (sectionText.fields.image !== null) {
                  allImageDataResult.nodes.forEach((image) => {
                    if ((image.name)
                      .localeCompare(sectionText.fields.image.name) === 0) {
                      sectionPage.imageDir = image.staticURL;
                    }
                  });
                } else {
                  sectionPage.imageName = null;
                }
              }
            });
          }
        });
      });
    });

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:

minimalMainPagesResult.pages.forEach((page) => {
      if (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
            sectionItems.push(<Banner
              image={value.imageDir}
              title={value.textData.heading}
              text={value.textData.body}
              buttonData={{
                url: value.textData.actions[0].link,
                label: value.textData.actions[0].name,
              }}
              key={value.textData.heading}
            />);
          } else { // announcement with no button
            sectionItems.push(<Banner
              image={value.imageDir}
              title={value.textData.heading}
              text={value.textData.body}
              key={value.textData.heading}
            />);
          }
        } else { // main body type
          sectionItems.push(<MainBody
            title={value.textData.heading}
            text={value.textData.body}
            key={value.textData.heading}
          />);
        }
      }
    
      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.