Build a Blog in JavaScript with Headless Oracle Content Management
Introduction
Nowadays it’s easy to build complex websites using the latest JavaScript frameworks, like Angular, React, and Vue.js. However, using those frameworks is not mandatory, and we can also build websites with pure JavaScript. In addition, if we combine the power of a content management system (CMS) with pure JavaScript websites, the output is pretty competitive. Fortunately, Oracle Content Management, with its rich headless CMS capabilities, has a graceful solution.
In this tutorial we’ll build a simple blog in JavaScript by leveraging Oracle Content Management as a headless CMS, as well as its software development kit (SDK) for content delivery in JavaScript. This JavaScript sample is available on GitHub.
The tutorial consists of three steps:
- Prepare Oracle Content Management
- Build the Blog in JavaScript
- 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
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.
To take a look at what we’re building, here’s the end state of our tutorial, a basic JavaScript blog that consumes content from Oracle Content Management:
https://headless.mycontentdemo.com/samples/oce-javascript-blog-sample
This is what the home page will look like at the end of this tutorial:
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:
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:
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:
- 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 ‘OCEGettingStartedChannel’ 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 ‘OCEGettingStartedRepository’ for the purpose of this tutorial.
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.
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 OCEGettingStarted_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 OCEGettingStartedRepository and click the Import Content button in the top action bar.
Upload OCEGettingStarted_data.zip from your local computer to the Documents folder.
Once it’s uploaded, select OCEGettingStarted_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 OCEGettingStartedRepository 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, OCEGettingStartedChannel.
Before publishing, you need to validate all the assets. First add OCEGettingStartedChannel 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 blog in Javascript.
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.
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 four content types, each with its own set of fields:
- OCEGettingStartedHomePage
- OCEGettingStartedTopic
- OCEGettingStartedAuthor
- OCEGettingStartedArticle
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:
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:
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:
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:
Once you’ve created your content types, you can add these content types to the repository that you created earlier, OCEGettingStartedRepository:
- Log in to the Oracle Content Management web interface as an administrator.
- Navigate to OCEGettingStartedRepository.
- Edit the repository and, under Asset Types, specify all four newly created content types.
- Click the Save button to save the changes.
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.
Step 2: Build the Blog in JavaScript
To consume our Oracle Content Management content in JavaScript, we can use the JavaScript blog sample, which is available as an open-source repository on GitHub.
Note: Remember that using the JavaScript sample is optional, and we use it in this tutorial to get you started quickly.
To build the blog in JavaScript:
- Clone the sample repository and install dependencies
- Configure the JavaScript application
- Work with the Oracle Content Management Content SDK
- Use the Content SDK to Fetch Content
Clone the Sample Repository and Install Dependencies
The JavaScript 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-javascript-blog-sample.git
cd oce-javascript-blog-sample
You can either modify the files in the starter directory or skip the steps after installing dependencies by using the contents of the completed directory.
Now that you have your code base, you need to download dependencies for the application. Run the following command from either the starter or completed directory, whichever you have chosen:
npm install
If you’re in the starter folder, you can proceed with configuring your JavaScript application.
If you’re in the completed folder, to see the completed code base, you can skip to prepare your application for deployment.
Configure the JavaScript Application
In this JavaScript 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/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.
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 Oracle Content Management Content SDK to fetch content so that we can render it in our JavaScript application.
To import the Oracle Content Management Content SDK, specify the following code in the src/config/app-config.js file:
.config({
requirejsbaseUrl: 'lib',
paths: {
jquery: 'jquery',
contentsdk: 'contentsdk',
polyfill: 'polyfill',
serverUtils: 'server-config-utils',
services: 'services',
xss: 'xss',
,
}shim: {
xss: {
exports: 'filterXSS',
,
},
}; })
And use it in the JavaScript file server-config-utils.js in the src/scripts folder as follows:
define(['jquery', 'contentsdk'], ($, contentsdk) => {
}
The Oracle Content Management Content SDK uses a DeliveryClient object to specify the endpoint. You can make all requests using that client object. The DeliveryClient is created in the in the src/scripts/server-config-utils.js file using server configuration specified in src/config/content.json.
.createDeliveryClient(serverConfig); contentsdk
This client is then passed into the methods to obtain the data from the Oracle Content Management server.
The home page, in src/scripts/topics_ui.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/scripts/services.js:
return client.queryItems({
q: '(type eq "OCEGettingStartedHomePage" AND name eq "HomePage")',
})
The topic page, in src/scripts/articles_list.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/scripts/services.js:
return client.queryItems({
q: `(type eq "OCEGettingStartedArticle" AND fields.topic eq "${topicId}")`, // @starter "q": ,
orderBy: 'fields.published_date:desc',
})
The individual article page, in src/scripts/article_ui.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/scripts/services.js:
return client.getItem({
id: articleId,
expand: 'fields.author',
})
Now that we have our data queries, we can render the responses in our JavaScript pages.
JavaScript Files
The next few sections provide an overview of how JavaScript renders our data in each of the JavaScript files.
topics_ui.js File
As we saw previously, the home page consists of a topics list composed of individual topics.
Open the topics_ui.js file, located at src/scripts. Note the invocation of the fetchHomePage() method, which is defined as follows in src/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));
}), }
Back in our src/scripts/topics_ui.js file, we retrieve what’s necessary for rendering the home page:
.fetchHomePage(client)
services.then((topLevelItem) => {
$('#spinner').hide();
populateHeaderTitle(topLevelItem.title);
populateHeaderImage(client, topLevelItem.logoID);
populateHeaderUrls(topLevelItem.aboutUrl, topLevelItem.contactUrl);
const container = $('#topics');
const topicIdentifiers = topLevelItem.topics.map(
=> topic.id,
(topic) ;
)populateTopicListing(client, topicIdentifiers, container);
}).catch((error) => {
$('#spinner').hide();
console.log(error); // Error getting top level elements
displayError();
; })
The topic item, on the other hand, represents an individual topic in the list.
Note the invocation of the fetchTopic() method, defined as follows in src/scripts/services.js:
fetchTopic(client, topicId) {
return client.getItem({
id: topicId,
expand: 'fields.thumbnail',
}).then((topic) => topic)
.catch((error) => this.logError('Fetching topic failed', error));
, }
Back in our src/scripts/topics_ui.js file, we retrieve what’s necessary for rendering each topic item.
.fetchTopic(client, id)
services.then((topic) => {
// assign a click event on the topic container
.click(() => {
topicContainerwindow.location.href = `./articles.html?topicName=${encodeURIComponent(
.name,
topic}&topicId=${encodeURIComponent(topic.id)}`;
);
})appendTopicTitle(topicContainer, topic.name);
appendTopicThumbnail(
,
client,
topicContainer.fields.thumbnail.id,
topic;
)appendTopicDetail(topicContainer, topic.description);
}).catch((error) => console.error(error));
articles_list_ui.js File
As for our list of articles on each individual topic page, we need to retrieve the associated list of articles.
Open the articles_list_ui.js file, located in the src/scripts folder. Note the invocation of the fetchArticles() method, defined as follows in src/scripts/services.js:
fetchArticles(client, topicId) {
return client.queryItems({
q: `(type eq "OCEGettingStartedArticle" AND fields.topic eq "${topicId}")`, // @starter "q": ,
orderBy: 'fields.published_date:desc',
}).then((articles) => articles.items)
.catch((error) => this.logError('Fetching articles failed', error));
, }
Back in our src/scripts/articles_list_ui.js file, we retrieve what’s necessary for rendering the list of articles.
.fetchArticles(client, topicId)
services.then((articles) => {
$('#spinner').hide();
// populate breadcrumb
$('#breadcrumb').append(
`<ul><li><a href="index.html">Home</a></li><li>${topicName}</li></ul>`,
;
)
const container = $('#articles');
.forEach((article) => {
articlescreateArticleListItem(
,
client,
container,
article,
topicName,
topicId;
);
})
}).catch((error) => {
$('#spinner').hide();
console.error(error);
; })
article_ui.js File and Image Renditions
Finally, we need to render each individual article page.
Open the article_ui.js file, located in the src/scripts folder. Note the invocation of the fetchArticle() method, defined as follows in src/scripts/services.js:
fetchArticle(client, articleId) {
return client.getItem({
id: articleId,
expand: 'fields.author',
}).then((article) => article)
.catch((error) => this.logError('Fetching article failed', error));
, }
Back in our src/scripts/article_ui.js file, we retrieve what’s necessary for rendering the article.
.fetchArticle(client, articleID)
services.then((article) => {
$('#spinner').hide();
populateTitle(article.name, topicName, topicId);
populateAuthor(
,
client.fields.author,
article.fields.published_date,
article;
)populateImage(
,
client.fields.image.id,
article.fields.image_caption,
article;
)populateContent(article.fields.article_content);
}).catch((error) => {
$('#spinner').hide();
console.error(error);
; })
In the process, we also invoke getRenditionURL():
.getRenditionURL(client, articleImageIdentifier)
services.then((url) => {
.getImageUrl(url)
utils.then((formattedUrl) => {
.attr('src', formattedUrl);
imgElement;
})
}).catch((error) => console.error(error));
The getRenditionURL() method is defined as follows in src/scripts/services.js:
getRenditionURL(client, identifier) {
const url = client.getRenditionURL({
id: identifier,
;
})return Promise.resolve(url);
, }
Finally, we invoke getMediumRenditionURL() to get the thumbnail rendition of the author’s image:
.getMediumRenditionURL(client, imageIdentifier)
services.then((url) => {
.getImageUrl(url)
utils.then((formattedUrl) => {
.attr('src', formattedUrl);
imgElement;
})
}).catch((error) => console.error(error));
The getMediumRenditionURL() method is defined as follows in src/scripts/services.js:
getMediumRenditionURL(client, identifier) {
return client.getItem({
id: identifier,
expand: 'fields.renditions',
}).then((asset) => {
const object = asset.fields.renditions.filter(
=> item.name === 'Medium',
(item) 0];
)[const format = object.formats.filter(
=> item.format === 'jpg',
(item) 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));
}), }
As you can see, the Oracle Content Management Content SDK can help reduce the number of requests you need to manage by wrapping queries.
Step 3: Prepare Your Application for Deployment
Now that we’ve built our JavaScript 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.
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
Then, open your browser to http://localhost:8881/oce-javascript-blog-sample/index.html to see your site in action.
If you have linting configured, you can run a linter using the following command:
npm run lint
Build a Blog in JavaScript with Headless Oracle Content Management
F38410-03
July 2021
Copyright © 2021, Oracle and/or its affiliates.
Primary Author: Oracle Corporation