Build a Blog in Oracle JET with Headless Oracle Content Management

Introduction

Oracle JavaScript Extension Toolkit (Oracle JET) is a complete, modular, open-source JavaScript development toolkit designed to help developers build engaging user interfaces. It’s based on industry standards and popular open-source frameworks. Oracle JET adds advanced functionality and services to help developers build better applications faster.

In this tutorial, we’ll build a simple blog in Oracle JET by leveraging Oracle Content Management as a headless CMS as well as its software development kit (SDK) for content delivery. This Oracle JET sample is available on GitHub.

The tutorial consists of three steps:

  1. Prepare Oracle Content Management
  2. Build the Blog in Oracle JET
  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

Our blog will consist of a three-page site that lets visitors explore blog articles organized into topics. The first page, the home page, will consist of branding (company name and logo), some links, and a list of blog topics.

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

This image shows the home page for Cafe Supremo demo site with a list of the available topics.

The second page, the topic page, shows previews of each blog article that belongs to the topic. Here’s how an individual topic page will look:

This image shows a topic page called ‘Recipes’ with a list of the available articles for that topic.

Lastly, the article page renders the final blog article, including information about the blog’s author. Here’s how an individual article page will look:

This image shows an individual article page, with the content and an author reference.

To proceed, you’ll need to have an active subscription to Oracle Content Management and be logged in with the Content Administrator role.

Step 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 in either of two ways. There’s a downloadable asset pack available that will fill your empty repository with content types and associated content, or you can create your own content model and 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 ‘OCEGettingStartedChannel’ 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 ‘OCEGettingStartedChannel’ 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 ‘OCEGettingStartedRepository’ for the purpose of this tutorial.

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

  6. In the Publishing Channels field, select the OCEGettingStartedChannel channel to indicate to Oracle Content Management that content in the OCEGettingStartedRepository repository can be published to the OCEGettingStartedChannel channel. Click Save when you’re done.

    This image shows the repository definition panel, with ‘OCEGettingStartedChannel’ 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 OCEGettingStarted_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 OCEGettingStartedRepository and click the Import Content button in the top action bar.

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

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

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

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

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

  6. After the content has been imported successfully, navigate to the Assets page and open the OCEGettingStartedRepository repository. You’ll see that all the related images and content items have now been added to the asset repository.

    This image shows the OCEGettingStartedRepository 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, OCEGettingStartedChannel.

    This image shows the OCEGettingStartedRepository 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 OCEGettingStartedChannel as a selected channel, and then click the Validate button.

    This image shows the Validation Results page, with the OCEGettingStartedChannel 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 OCEGettingStartedChannel 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 blog in Oracle JET.

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 ‘OCEGettingStartedHomePage’ to build the home page for our blog. This home page consists of branding (company name and logo), some URLs for links, and a list of blog topics that should be included on the page.

This image shows the home page for the Cafe Supremo demo site.

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 four content types, each with its own set of fields:

The first content type, OCEGettingStartedHomePage, should have the following fields:

Display Name Field Type Required Machine Name
Company Name Single-value text field X company_name
Company Logo Single-value text field X company_logo
Topics Multiple-value reference field X topics
Contact URL Single-value text field X contact_url
About URL Single-value text field X about_url

This is what your OCEGettingStartedHomePage content type definition should look like:

This image shows the definition for the content type ‘OCEGettingStartedHomePage’. It includes these data fields: Company Name, Company Logo, Topics, Contact URL, and About URL.

The second content type, OCEGettingStartedTopic, should have the following field:

Display Name Field Type Required Machine Name
Thumbnail Single-value image field X thumbnail

This is what your OCEGettingStartedTopic content type should look like:

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

The third content type, OCEGettingStartedAuthor, should have the following fields:

Display Name Field Type Required Machine Name
Avatar Single-value image field X avatar

This is what your OCEGettingStartedAuthor content type should look like:

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

The fourth and final content type, OCEGettingStartedArticle, should have the following fields:

Display Name Field Type Required Machine Name
Published Date Single-value date field X published_name
Author Single-value reference field X author
Image Single-value image field X image
Image Caption Single-value text field X image_caption
Article Content Single-value large-text field X article_content
Topic Single-value reference field X topic

This is what your OCEGettingStartedArticle content type should look like:

This image shows the definition for the content type ‘OCEGettingStartedArticlePage’. It includes these data fields: Published Date, Author, Image, Image Caption, Article Content, and Topic.

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

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

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

After adding the content types to the repository, you can open the OCEGettingStartedRepository 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.

Step 2: Build the Blog in Oracle JET

To consume our Oracle Content Management content in an Oracle JET application, we can use the Oracle JET blog sample, which is available as an open-source repository on GitHub.

Note: Remember that using the Oracle JET sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own Oracle JET application, such as one scaffolded by Oracle JET CLI.

To build the blog in Oracle JET:

  1. Clone the sample repository and install dependencies
  2. Configure the Oracle JET application
  3. Work with the Oracle Content Management Content SDK
  4. Use the Content SDK to Fetch Content

Clone the Sample Repository and Install Dependencies

The Oracle JET blog 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-jet-blog-sample.git
    cd oce-jet-blog-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 Oracle JET Application

In this Oracle JET blog sample, you need to configure a few pieces of information so that your Oracle Content Management Content SDK (and any other requests) can target the correct instance URL and API version with the correct channel token. These values are used in src/js/scripts/server-config-utils.js to instantiate a new delivery client.

Open src/config/content.json in a text editor. You’ll see the following information:

{
      "serverUrl": "https://samples.mycontentdemo.com",
      "apiVersion": "v1.1",
      "channelToken": "47c9fb78774d4485bc7090bf7b955632"
    }

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 OCEGettingStartedChannel. The channel token is in the src/config/content.json file.

Note: We recommend that you store these values as environment variables in your hosting provider or in a local .env file. Revealing your instance URL or channel token to the public can potentially lead to distributed denial-of-service (DDoS) attacks. This risk is mitigated by ensuring that cross-origin resource sharing (CORS) for your instance is configured properly.

Work with the Oracle Content Management Content SDK

Oracle Content Management offers an SDK to help discover and use content in your applications. The SDK is published as an NPM module, and the project is hosted on GitHub.

Learn more about the SDK here.

The SDK has been registered as a runtime dependency of this project in the package.json file.

Use the Content SDK to Fetch Content

We can now leverage the Content SDK to fetch content so that we can render it in our Oracle JET application.

To use the Content SDK in your application, add it to the src/js/path_mapping.json file:

"contentsdk": {
      "cdn": "3rdparty",
      "cwd": "node_modules/@oracle/content-management-sdk/dist",
      "debug": {
        "src": "content.umd.js",
        "path": "libs/content/content.js",
        "cdnPath": "@oracle/content-management-sdk/dist/content.umd.js"
      },
      "release": {
        "src": "content.umd.js",
        "path": "libs/content/content.js",
        "cdnPath": "@oracle/content-management-sdk/dist/content.umd.js"
      }
    },

A reference to the ContentSDK is also added to the “paths” in the src/js/main.js:

requirejs.config(
      {
        ....
        paths:
        {
          ....
          contentsdk: 'libs/contentsdk/content',
          ....
        },
        ....
      },
    );

The Content SDK is then used in the JavaScript file server-config-utils.js in the src/js/scripts folder as follows:

define(['jquery', 'contentsdk'], function ($, contentSDK) {
    }

The Content SDK uses a Client object to specify the endpoint. You can make all requests using that client object. The DeliveryClient is created in the in the src/js/scripts/server-config-utils.js file using server configuration specified in src/config/content.json.

contentSDK.createDeliveryClient(serverConfig);

The src/js/scripts/services.js file contains functions to get all of the data for this Oracle JET blog application. Each function takes a Content SDK client as a parameter.

The Content SDK client is then passed to the relevant functions in src/js/scripts/services.js to get the required data.

The home page, in src/js/ViewModels/TopicsList.js, loads one content item based on its name, using queryItems. This uses a query that looks for content items of type ‘OCEGettingStartedHomePage’ that have the name ‘HomePage’. See fetchHomePage() in src/js/scripts/services, which uses this query:

return client.queryItems({
      q: '(type eq "OCEGettingStartedHomePage" AND name eq "HomePage")',
    })

The topic page, in src/js/ViewModels/ArticlesList.js, shows all articles for a given topic. Again, we use queryItems, this time searching for content items of type ‘OCEGettingStartedArticle’ that reference the topic whose identifier was passed to the page as a query parameter. See fetchArticles() in src/js/scripts/services, which uses this query:

return client.queryItems({
      q: `(type eq "OCEGettingStartedArticle" AND fields.topic eq "${topicId}")`,
      orderBy: 'fields.published_date:desc',
    })

The individual article page, in src/js/ViewModels/ArticleDetails.js, shows a single article, but the page includes content from Author, which is a separate content type. To fetch one content item plus any content items it references, use getItem with the expand parameter set to ‘all’. See fetchArticle() in src/js/scripts/services, which uses this query:

return client.getItem({
      id: articleId,
      expand: 'fields.author',
      fields: 'fields.author',
    })

Now that we have our data queries, we can render the responses in our Oracle JET components.

Oracle JET Components

The Oracle JET components in this application contain the markup to define the views and JavaScript to populate the data in the views.

The following sections provide an overview of how Oracle JET is rendering our data in each of our components:

Root Component

The main entry point to this Oracle JET application is the src/js/main.js file. This file imports the src/js/appController.js file, which defines the different routes for our application.

In our site, we want to provide three routes:

Both the topic page and the individual article page take an argument provided by Oracle Content Management in its URL.

Open the file src/js/appController.js and see how the routes are defined:

router.configure({
      topics:
        { label: 'topics', value: 'TopicsList', isDefault: true },
    
        'articles/{topicId}':
        { label: 'article', value: 'ArticlesList' },
    
        'article/{articleId}/{topicId}/{topicName}':
        { label: 'article', value: 'ArticleDetails' },
      });

TopicsList Component

As we saw previously, the home page consists of a topics list composed of individual topics.

Open the TopicsList component, located at src/js/viewModels/TopicsList.js. Note the invocation of fetchHomePage(), which is defined as follows in src/js/scripts/services.js:

fetchHomePage(client) {
      return client.queryItems({
        q: '(type eq "OCEGettingStartedHomePage" AND name eq "HomePage")',
      }).then((topLevelItem) => {
        const returnVal = {
          logoID: topLevelItem.items[0].fields.company_logo.id,
          title: topLevelItem.items[0].fields.company_name,
          topics: topLevelItem.items[0].fields.topics,
          aboutUrl: topLevelItem.items[0].fields.about_url,
          contactUrl: topLevelItem.items[0].fields.contact_url,
        };
        return returnVal;
      }).catch((error) => this.logError('Fetching home page data failed', error));
    },

Once the home page details are obtained, we call getRenditionURL() to get the URL for the company logo, which is defined as follows in src/js/scripts/services.js:

getRenditionURL(client, identifier) {
      const url = client.getRenditionURL({
        id: identifier,
      });
      return Promise.resolve(url);
    },

Back in our TopicsList component, we retrieve what is necessary for rendering the home page:

services.fetchHomePage(client)
      .then((topLevelItem) => {
        services.getRenditionURL(client, topLevelItem.logoID)
          .then((url) => {
            // list items
            self.topics = topLevelItem.topics;
            this.dataProvider = new ArrayDataProvider(self.topics, { keyAttributes: 'id' });
    
            // company title and logo thumbnail
            self.companyName(topLevelItem.title);
            utils.getImageUrl(url)
              .then((formattedUrl) => self.companyThumbnailUrl(formattedUrl));
    
            // contact us and about us URLs
            self.aboutUrl(topLevelItem.aboutUrl);
            self.contactUrl(topLevelItem.contactUrl);
    
            self.loading(false);
          })
          .catch((error) => {
            self.error(true);
            console.error(error);
          });
      })
      .catch((error) => {
        self.error(true);
        console.error(error);
      });

TopicListItem Component

The TopicListItem component represents an individual topic in the list.

Open the TopicListItem component, located at src/js/viewModels/TopicListItem.js. Note the invocation of the fetchTopic() method, defined as follows In src/js/scripts/services.js:

fetchTopic(client, topicId) {
      return client.getItem({
        id: topicId,
      }).then((topic) => topic)
        .catch((error) => this.logError('Fetching topic failed', error));
    },

Once the topic has been obtained, we call getMediumRenditionURL() to get the URL for the topic’s thumbnail, which is defined as follows in src/js/scripts/services.js:

getMediumRenditionURL(client, identifier) {
      return client.getItem({
        id: identifier,
      }).then((asset) => {
        const object = asset.fields.renditions.filter((item) => item.name === 'Medium')[0];
        const format = object.formats.filter((item) => item.format === 'jpg')[0];
        const self = format.links.filter((item) => item.rel === 'self')[0];
        const url = self.href;
        return url;
      }).catch((error) => this.logError('Fetching medium rendition URL failed', error));
    },

Back in our TopicListItem component, we retrieve what is necessary for rendering each topic item.

services.fetchTopic(client, topicId)
      .then((topic) => {
        self.title(topic.name);
        self.description(topic.description);
    
        services.getMediumRenditionURL(client, topic.fields.thumbnail.id)
          .then((thumbnailUrl) => {
            utils.getImageUrl(thumbnailUrl)
              .then((formattedUrl) => self.url(formattedUrl));
          })
          .catch((error) => console.error(error));
      })
      .catch((error) => console.error(error));

ArticlesList Component

The Topic page displays a list of articles for a specified topic ID.

Open the ArticlesList component, located at src/js/viewModels/ArticlesList.js. Note the invocation of the fetchTopic() method, like in the topic list item. This is called to get the topic name to display in the breadcrumbs:

services.fetchTopic(client, self.topicId)
      .then((topic) => {
        self.topicName(topic.name);
      });

The articles are obtained by calling the fetchArticles() method, defined as follows in src/js/scripts/services.js:

fetchArticles(client, topicId) {
      return client.queryItems({
        q: `(type eq "OCEGettingStartedArticle" AND fields.topic eq "${topicId}")`,
        orderBy: 'fields.published_date:desc',
      }).then((articles) => articles.items)
        .catch((error) => this.logError('Fetching articles failed', error));
    },

Back in our ArticlesList component, we retrieve what is necessary for rendering the list of articles.

services.fetchArticles(client, self.topicId)
      .then((retrievedArticles) => {
        self.articles = retrievedArticles;
        this.dataProvider = new ArrayDataProvider(retrievedArticles, { keyAttributes: 'id' });
        self.loading(false);
      })
      .catch((error) => {
        self.error(true);
        console.error(error);
      });

ArticleListItem Component

The ArticleListItem component represents an individual article in the list.

Open the ArticleListItem component, located at src/js/viewModels/ArticleListItem.js. Like the Topic List Item component, this component also uses the getMediumRenditionUrl() method to retrieve the URL for the article thumbnail:

services.getMediumRenditionURL(client, article.fields.image.id)
      .then((url) => {
        utils.getImageUrl(url)
          .then((formattedUrl) => self.articleUrl(formattedUrl));
      })
      .catch((error) => console.error(error));

ArticleDetail Component

Finally, we need to render each individual article page.

Open the ArticleDetail component, located at src/js/viewModels/ArticleDetails.js. Note the invocation of the fetchArticle() method, defined as follows in src/js/scripts/services.js:

fetchArticle(client, articleId) {
      return client.getItem({
        id: articleId,
        expand: 'fields.author',
        fields: 'fields.author',
      }).then((article) => article)
        .catch((error) => this.logError('Fetching article failed', error));
    },

Back in our ArticleDetail component, we retrieve what is necessary for rendering the article. In the process, we also invoke getRenditionURL() to get the image for the article, and we also invoke getMediumRenditionURL() to get the medium rendition of the user’s avatar:

services.fetchArticle(client, articleId)
      .then((article) => {
        self.articleName(article.name);
        self.authorName(article.fields.author.name);
        self.formattedDate(`Posted on ${utils.dateToMDY(article.fields.published_date.value)}`);
        self.articleImageCaption(article.fields.image_caption);
    
        let content = article.fields.article_content;
        self.articleContentConfig({
          // ensure there is no script injection attack in the article content
          // eslint-disable-next-line no-undef
          view: HtmlUtils.stringToNodeArray(filterXSS(content, articleDetailsXssOptions)),
          data: {},
        });
    
        // get the article image URL
        services.getRenditionURL(client, article.fields.image.id)
          .then((renditionUrl) => {
            utils.getImageUrl(renditionUrl)
              .then((formattedUrl) => self.articleImageUrl(formattedUrl));
    
            // Get the authors avatar image
            services.getMediumRenditionURL(
              client, article.fields.author.fields.avatar.id
            )
              .then((thumbnailUrl) => {
                utils.getImageUrl(thumbnailUrl)
                  .then((formattedUrl) => {
                    self.authorAvatarUrl(formattedUrl);
                    self.loading(false);
                  });
              });
          });
      })
      .catch((error) => {
        self.error(true);
        console.error(error);
      });

As you can see, the Oracle Content Management Content SDK can help to reduce the number of requests you need to manage by wrapping queries. In addition, helper functions in Oracle JET can conduct the data processing you need for rendering in components.

Oracle JET Themes

The Oracle JET blog sample application makes use of a theme to color the application. The theme is located in src/themes/contentblog.

When you start the application, the theme must be specified for it to be used in the application.

Note: This Oracle JET demo application uses CSS variables in its stylesheets. If CSS variables are not supported in the web browser the application is running in, the styling may appear different because styles are defaulted.

Step 3: Prepare Your Application for Deployment

Now that we’ve built our Oracle JET blog site, we need to see it in a local development server so we can debug any issues and preview the application before it goes live.

Prepare your application for deployment in two steps:

  1. Spin up a local development server
  2. Generate a minified client bundle

Spin Up a Local Development Server

First build the application using

npm run build

You can then start a development server locally by running the following command:

npm run start

This will execute the following command, which will build and run the application using the ‘oceblog’ theme:

ojet serve --theme=contentblog

Then, open your browser to http://localhost:3000 to see your site in action.

If you have tests available, you can run them using the following command:

npm test

If you have linting configured, you can run a linter using the following command:

npm run lint

Generate a Minified Client Bundle

Now we need to generate a client bundle that packages our production-ready application according to our bundler configuration.

To generate a client bundle, run the following command:

npm build

This will execute the following command, which will build the application using the ‘oceblog’ theme:

ojet build --theme=contentblog