Build a Minimal Site in React with Headless Oracle Content Management
Introduction
React is a JavaScript framework widely used to build web applications.
To consume our Oracle Content Management content in a React application, we can use the React minimal sample available as an open-source repository on GitHub.
In this tutorial, we’ll build a simple minimal site in React by leveraging Oracle Content Management as a headless CMS as well as its software development kit (SDK) for content delivery in JavaScript. Oracle Content Management also includes support for GraphQL for all published content and all asset types. This React sample is available on GitHub.
The tutorial consists of three tasks:
- Prepare Oracle Content Management
- Build the minimal site in React
- 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 React 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 React minimal site that consumes content from Oracle Content Management:
https://headless.mycontentdemo.com/samples/oce-react-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:
This is what the people 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, 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, OCEGettingStartedChannel.
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 React.
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 five content types, each with its own set of fields:
- MinimalMain
- MinimalPage
- MinimalSection
- PeoplePage
- Person
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 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:
The fourth content type, PeoplePage, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
announcement | Single-value reference field | announcement | |
people | Multiple-value reference field | people |
The fifth and final content type, Person, is a custom digital asset with the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
fullName | Single-value text field | X | fullName |
title | Single-value text field | title | |
biodata | Single-value large-text field | biodata |
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 five 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 React
To consume our Oracle Content Management content in a server-side rendered React application, we can use the React minimal site sample, which is available as an open-source repository on GitHub.
Note: Remember that using the React sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own React application.
To build the minimal site in React:
- Clone the sample repository and install dependencies
- Configure the React application
- Work with the Oracle Content Management Content SDK
- Use the Content SDK to fetch content
- Use GraphQL to construct the people page
Clone the Sample Repository and Install Dependencies
The React 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-react-minimal-sample.git
cd oce-react-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 React Application
In this React minimal site 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.
This application uses an .env file that is read by Webpack when it bundles the client and server applications. By using webpack.DefinePlugin, any values read from the .env file can be made available to anywhere in the application.
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
API_VERSION=v1.1
CHANNEL_TOKEN=ba0efff9c021422cb134c2fd5daf6015
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.
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 React application.
The Content SDK uses a DeliveryClient object to specify the endpoint. You can make all requests using that client object.
The src/scripts folder contains the code for getting data from Oracle Content Management using the Content SDK.
The src/scripts/server-config-utils.js file imports the Content SDK and then creates a delivery client using the configuration specified in .env.
The following command imports the SDK:
import { createDeliveryClient, createPreviewClient } from '@oracle/content-management-sdk';
The following command creates the delivery client:
return createDeliveryClient(serverconfig);
The src/scripts/services.js file contains functions to get the data for this React minimal application.
The fetchOceMinimalMain() method retrieves the content type MinimalMain with a slug of minimalmain.
export async function fetchOceMinimalMain() {
const data = await getItem('minimalmaingraphql', 'fields.headerlogo,fields.footerlogo,fields.pages');
if (!data.hasError) {
const { fields } = data;
const { headerlogo, footerlogo } = fields;
// Extract the sourceset for the headerImage and footerImage and put it back in the data
.headerRenditionURLs = getSourceSet(headerlogo);
data.footerRenditionURLs = getSourceSet(footerlogo);
data
}return data;
}
Note: The above query is for an asset with slug “minimalmaingraphql” which includes the ‘People’ page of type People Page. To create the minimal site without the ‘People’ page, an asset with slug “minimalmain” in the asset pack can be used instead.
For rendering the images, the services.js provides a helper method to retrieve the sourceset for an asset that is constructed from the renditions for the asset.
function getSourceSet(asset) {
const urls = {};
.srcset = '';
urls.jpgSrcset = '';
urlsif (asset.fields && asset.fields.renditions) {
.fields.renditions.forEach((rendition) => {
assetaddRendition(urls, rendition, 'jpg');
addRendition(urls, rendition, 'webp');
;
})
}// add the native rendition to the srcset as well
.srcset += `${asset.fields.native.links[0].href} ${asset.fields.metadata.width}w`;
urls.native = asset.fields.native.links[0].href;
urls.width = asset.fields.metadata.width;
urls.height = asset.fields.metadata.height;
urlsreturn urls;
}
The fetchPage() method retrieves the content type MinimalPage using the slug value for the page obtained from the previous query.
export async function fetchPage(pageslug) {
// Get the page details
const page = await getItem(pageslug, 'fields.sections');
return page;
}
The getRenditionURLs() method retrieves the rendition urls for any image that may be defined in a section using the id for that image. This call is done client side.
export function getRenditionURLs(identifier) {
const client = getClient();
return client.getItem({
id: identifier,
expand: 'fields.renditions',
.then((asset) => getSourceSet(asset))
}).catch((error) => logError('Fetching Rendition URLs failed', error));
}
Use GraphQL to Construct the People Page
We use the Apollo Client in package.json to integrate GraphQL into React and the fetchPeople method in src/scripts/services-graphql.js to make the GraphQL call to the content server.
For more information on how to include GraphQL support in Oracle Content Management, try out the Use GraphQL with React and Oracle Content Management tutorial.
Now that we have our data query, we can render the responses in our React components.
Client-Side Versus Server-Side Rendering
With client-side rendering (CSR), the client is responsible for building and rendering the content of a web page using JavaScript. With server-side rendering (SSR), the page is built on the server, and a web page is returned to the client.
When the web page is requested from the server in client-side rendering, the HTML document returned contains skeleton HTML and no actual content. It contains a reference to a JavaScript bundle, which the client then requests from the server. On receiving this bundle, the client executes the JavaScript and populates the web page. Until the client has finished executing the JavaScript, all the user sees is a blank web page. One downside of client-side rendered applications is that when some web crawlers index the site, there is no actual content to index.
With server-side rendering (SSR), the page is built on the server, and a web page is returned to the client. The advantage of this is that web crawlers can index the content on the web page.
React Minimal Site Application Flow
The flow of the React minimal site application is as follows:
- The client makes a request to the server for a given route.
- The Express server receives the request.
- The Express server then performs the following tasks:
- It determines which components will be rendered for the given route, and calls the component’s fetchInitialData function to get all of the data for that component.
- It creates a string of all the content to render. (Each component will be asked to render to produce its HTML markup.)
- It creates an HTML document that contains the folowing items:
- The string of content to render
- A link to a style sheet, if applicable
- A script tag containing the client-bundle.js that the client will need
- The data obtained from all the components, serialized as JSON
- The server then returns the HTML to the client.
- The client receives the HTML and renders it. The user will see a fully formed web page.
- The JavaScript in the HTML will store the data in the web browser window on the client.
- The client requests the client-bundle.js file from the server.
After receiving it, the client runs the JavaScript in the bundle.
- It “hydrates” the HTML, adding in any client-side JavaScript such as event listeners.
- Each component being rendered sees if their data is stored on the window. If it is, that data is used; otherwise, the component gets the data it needs by making requests to the Oracle Content Management server via the Content SDK.
- If the HTML document contained a style sheet, the client requests the style sheet.
Viewing the source of the web page, you’ll see all the content in the HTML, indicating that the page was rendered on the server.
Note: This sample application gets the data in the root components and then passes the data down to any child component that needs it. An alternative is to use a state-management tool such as Redux, which puts the data in a store, and any component can request the data from that store.
Server-Side Express Server and Rendering
The server application makes use of an Express server to receive the request, generate a React application instance, generate the HTML page, and return the response.
The Express server file is located at src/server/server.js.
The Express server accepts all requests and then uses React’s react-router-dom matchPath() to get the component that will render for the specified route. This in turn would call that component’s fetchInitialData method to get that component’s data, returning a promise. The promise is executed and a context object is created to contain the data. A renderer is then called to generate the HTML page before returning the HTML content to the client.
.get('*', (req, res) => {
server// matchRoutes will return all the components which will be rendered as per the request route.
// call "fetchInitialData" on each of those components (if the component has such a method),
// and build up an array of pending network calls for all the data required for the components
// which will be rendered.
const promises = matchRoutes(Routes, req.path).map(({ route }) => (
.fetchInitialData ? route.fetchInitialData(req) : null));
route
// Execute all promises at the same time to get all the data, once its all been obtained
// render the HTML to the client by delgating to the "renderer" method
Promise.all(promises).then((data) => {
// this context object gets passed into the renderer, which in turn passes it
// to the StaticRouter. The StaticRouter passes it to any component which is called
// as the "staticContext" prop.
const context = { data };
// get the content to return to the client
const content = renderer(req, context);
// if the route requested was not found, the content object will have its "notFound"
// property set, therefore we need to change the response code to a 404, not found
if (context.notFound) {
.status(404);
res
}
if (context.url) {
// If a redirect was set using a Redirect component do that
.redirect(301, context.url);
reselse {
} // send the response
.send(content);
res
};
}); })
The renderer is located at src/server/renderer.jsx and it uses React’s react-dom/server renderToString() to get a string of all the content being rendered.
// generate the HTML content for this application
const content = renderToString(
<StaticRouter context={context} location={req.path} basename={process.env.BASE_URL}>
<div>{renderRoutes(Routes)}</div>
</StaticRouter>,
; )
The context object passed to the renderer is passed to the server-side router, StaticRouter. During server-side rendering, any component is able to get the data from the component’s props.
this.props.staticContext.data
The renderer returns the HTML markup which contains the React content, the serialized data and a reference to the JavaScript bundle to run on the client.
<body>
<div id="root">${content}</div>
<script>
window.INITIAL_DATA = ${serialize(context.data)}
</script>
<script src="${clientBundleFile}"></script>
</body>
When the client receives the HTML, the data will be made available in the window and the client will request the client bundle from the server.
Client-Side Rendering
The client-side rendering code is located in src/client/main.js. This code goes through all the HTML of the web page, adding in any client-side JavaScript code.
This process is called hydrating.
.hydrate(
ReactDOM<BrowserRouter basename={process.env.BASE_URL}>
<div>{renderRoutes(Routes)}</div>
</BrowserRouter>,
document.querySelector('#root'),
; )
React Components
React uses a technology known as JSX, which is an HTML-like syntax extension to JavaScript, to render content. Even though you can write pure JavaScript to render data from Oracle Content Management, we strongly recommend that you use JSX.
The minimal site application breaks down each page into a number of smaller components.
The next few sections comprise an overview of how React renders our application in each of our components:
- IS_BROWSER variable
- Routes file
- App component
- Page component
- Header and Footer components
- Section component
- People component
- Person component
- Error component
IS_BROWSER Variable
Webpack is used to bundle the client and server code. There’s a configuration file instructing Webpack on how to create each bundle.
Open the configuration file for the client bundle, webpack.client.config.js. At the bottom of the file, a variable is set to indicate that the application is running in a browser.
new webpack.DefinePlugin({
'process.env.IS_BROWSER': true,
, })
Open the configuration file for the server bundle, webpack.server.config.js. At the bottom of the file, the same variable is set to indicate that the application is not running in a browser. The IS_BROWSER variable can be accessed from anywhere in the React application code to determine if the application is rendering on the server or in the client.
Routes File
In our site, we provide only two routes. The ‘/page/people’ is routed to the People Component. All other requests are directed to the Page component.
All pages have a header, containing the company logo and links, and a footer, containing a logo and social media icons.
The src/pages/Routes.js file defines the routes for the application. Here we’re using the ES6 spread operator for the App, Page references. This is because the imports for these items are objects containing the component and its fetchInitialData function (if it has one), rather than just the component.
export default [
{...App,
routes: [
{...People,
path: '/page/people',
exact: true,
title: 'People',
,
}
{...Page,
path: '/page/:slug',
exact: true,
title: 'Page',
,
},
],
}; ]
App Component
The App component is the main component of the application. It wraps the routes so every route in the application gets the header and footer.
<div>
<Header pages={data.fields.pages} headerRenditionURLs={data.headerRenditionURLs} />
? (
{isRoot <Redirect to={{ pathname: `/page/${firstPageSlug}` }} />
: (
) renderRoutes(route.routes)
)}<Footer footerRenditionURLs={footerRenditionURLs} />
</div>
The components for individual routes is the Page component located in the pages directory.
Open the App component, located at src/pages/App.jsx. The component imports the API to get the data from the services.js file.
import { fetchOceMinimalMain } from '../scripts/services';
The App component gets the data required and passes them on to the Header, Footer and Page components.
The constructor checks to see if the application is running on the client or the server, using the process.env.IS_BROWSER variable set in the Webpack bundling files. If the component is rendering in the client, the data is obtained from the window.
Note: When a page is navigated to using client-side routing, server-side rendering will not occur. Instead, the content will be rendered using client-side rendering. As a result, the window will not contain any data, and the client will have to make a server call to get it.
If the component is being rendered on the server, the data is obtained from this.props.staticContext; that is, the data passed from the Express Server file. The data, or default values, is then stored on the component’s state.
constructor(props) {
super(props);
let data;
if (process.env.IS_BROWSER) {
= window.INITIAL_DATA;
data // Do not delete the data yet, as the Page component needs to read from it
else {
} const { staticContext } = this.props;
= staticContext.data;
data
}
this.state = {
appData: data,
;
} }
During server-side rendering, fetchInitialData is called to get the data from the server. It returns a promise to the calling code, the Express Server code.
function fetchInitialData() {
return fetchOceMinimalMain();
}
When the component renders (see render() method), it gets all the data from the component’s state and passes them to the Header, Footer components and Page route.
src/pages/App.jsx exports an object containing the fetchInitialData function and the component.
export default {
,
fetchInitialDatacomponent: App,
; }
Page Component
The Page component is responsible for rendering all the sections defined for a page.
Open the Page component, located at src/pages/Page.jsx.
fetchInitialData is called during server-side rendering to get the data from the server.
function fetchInitialData() {
const pageslug = req.path.split('/').pop();
return fetchPage(pageslug);
}
componentDidUpdate checks if the location pathname has changed indicating a navigation change, and then fetches data accordingly.
componentDidUpdate() {
const { pageSlug } = this.state;
const { location } = this.props;
const { pathname } = location;
const newSlug = pathname.split('/').pop();
if (pageSlug !== newSlug) {
this.fetchData(newSlug);
} }
In the render() method, you can see that the data to render is obtained from the component’s state. This data has a list of sections so the Page components render() method iterates thru’ the list and calls the Section component for each section in the list.
Like the App component, the Page component exports an object containing the fetchInitialData function and the component.
export default {
,
fetchInitialDatacomponent: Page,
; }
Header and Footer Components
The Header component, located at src/components/Header.jsx, and the Footer component, located at src/components/Footer.jsx, simply use data passed to them from the App component. They don’t get any additional data from the server.
Section Component
The Section component, located at src/components/Section.jsx, is used by Page component and is used to render any content items of the type MinimalSection.
This component has data passed to it from the Page component and if the section data has an image, it makes a client side call to get the rendition urls for the image from the server.
useEffect(() => {
if (!image || section.RenditionURLs) return;
getRenditionURLs(image.id).then((urls) => {
setRenditionURLs(urls);
, console.error);
}, [section]); }
People Component
The People component is responsible for rendering the People Page and is located at src/pages/People.jsx.
For more information on how to include GraphQL Support in Oracle Content Management, check out this tutorial.
Person Component
The Person component, located at src/components/Person.jsx, is used by People component and is used to render any content items of the type Person.
This component has data passed to it from the People component and does not need to make any additional calls to the server.
Error Component
The Error component, located at src/components/Error.jsx, is used by the Page and App components. If there were any errors during the call to the server, it will render them.
Task 3: Prepare Your Application for Deployment
Now that we’ve built our React minimal site 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 the application for deployment in three steps:
- Build the application using Webpack
- Run the application using Node
- Use scripts to build and run the application in development and production
Build the Application Using Webpack
Webpack is used to bundle the application. It creates two JavaScript bundles: server-bundle.js, which is run on the server, and client-bundle.js, which is downloaded and run on the client.
The React minimal site application has three Webpack configuration files:
- webpack.base.config.js is merged in with both the client and server Webpack configurations.
- webpack.client.config.js bundles the code for the client.
- webpack.server.config.js bundles the code for the server.
To build the client bundle, you must specify the client Webpack configuration:
webpack --config webpack.client.config.js
To build the server bundle, you must specify the server Webpack configuration:
webpack --config webpack.server.config.js
Run the Application Using Node
Once the bundles have been created, you can start the server by running the following command:
node server.js
Use Scripts to Build and Run the Application in Development and Production
The package.json file located at the root of the project contains scripts that make it easier to build the bundles and run the application.
Development
You can use the dev script during development:
npm run dev
This script builds the client and server bundles and starts the application in a local server. Webpack will watch for code changes and recreate the client and server bundles if required.
Production
For production, the build script would be used to build the client and server bundles:
npm run build
When the script completes, the application can be run using the following command:
npm run start
Conclusion
In this tutorial, we created a minimal site in React, which can be found on GitHub. This site uses Oracle Content Management as a headless CMS. After setting up and configuring Oracle Content Management with a channel of published content for the minimal site tutorial, we installed and ran the React site to fetch the required content and build the site.
For more information on React, go to the React website.
Learn about important Oracle Content Management concepts in the documentation.
If you want to use GraphQL with React, check out this tutorial.
To find out how to integrate Video Plus assets in Oracle Content Management with React, see this tutorial.
You can find more samples like this on the Oracle Content Management Samples page in the Oracle Help Center.
Build a Minimal Site in React with Headless Oracle Content Management
F38764-05
December 2022
Copyright © 2021, 2022, Oracle and/or its affiliates.
Primary Author: Oracle Corporation