Build a Minimal Site in Next.js with Headless Oracle Content Management

Introduction

Next.js is an open-source React front-end development web framework that enables functionality such as server-side rendering and generating static websites for React based web applications.

To consume our Oracle Content Management content in a Next.js application, we can use the Next.js minimal sample available as an open-source repository on GitHub.

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

The tutorial consists of three tasks:

  1. Prepare Oracle Content Management
  2. Build the minimal site in Next.js
  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 Next.js 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 Next.js minimal site that consumes content from Oracle Content Management:

https://headless.mycontentdemo.com/samples/oce-nextjs-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 Next.js 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 Next.js 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. Import the Oracle Content Management Samples Asset Pack

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 task 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, OCEGettingStartedChannel.

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

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

To consume our Oracle Content Management content in a server-side rendered Next.js application, we can use the Next.js minimal site sample, which is available as an open-source repository on GitHub.

Note: Remember that using the Next.js sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own Next.js application.

To build the minimal site in Next.js:

  1. Clone the sample repository and install dependencies
  2. Configure the Next.js 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 Next.js 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-nextjs-minimal-sample.git
    cd oce-nextjs-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 Next.js Application

In this Next.js 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 scripts/server-config-utils.js to instantiate a new delivery client.

This application uses an .env.local file which is read by Next.js and made available to the code inside the application with process.env.

Open the .env.local 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 Next.js application.

The Content SDK uses a DeliveryClient object to specify the endpoint. You can make all requests using that client object.

The scripts folder contains the code for getting data from Oracle Content Management using the Content SDK.

The scripts/server-config-utils.js file imports the Content SDK and then creates a delivery client using the configuration specified in .env.local.

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 scripts/services.js file contains functions to get the data for this Next.js minimal application.

The fetchOceMinimalMain() method retrieves the content type MinimalMain with a slug of minimalmain.

export async function fetchOceMinimalMain() {
      const data = await getItem('minimalmain', '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
        data.headerRenditionURLs = getSourceSet(headerlogo);
        data.footerRenditionURLs = getSourceSet(footerlogo);
      }
      return data;
    }

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 = {};
      urls.srcset = '';
      urls.jpgSrcset = '';
      if (asset.fields && asset.fields.renditions) {
        asset.fields.renditions.forEach((rendition) => {
          addRendition(urls, rendition, 'jpg');
          addRendition(urls, rendition, 'webp');
        });
      }
      // add the native rendition to the srcset as well
      urls.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;
      return urls;
    }

The fetchPage() method retrieves the content type MinimalPage using the slug value for the page.

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.

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));
    }

Now that we have our data queries, we can render the responses in our Next.js components.

Next.js Components

Next.js is based on React and 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 Next.js renders our application in each of our components:

Pages Folder

In our site, we provide one route - /page. Requests are directed to the Main component defined in the pages/page/[[..slug]].jsx file. The root path request is redirected to /page by specifying a redirect in next.config.js.

  async redirects() {
        return [
          {
            source: '/',
            destination: '/page/',
            permanent: true,
          },
        ]
      }

All pages have a header, containing the company logo and links, and a footer, containing a logo and social media icons. Pages are accessed via static URLs and get all the data needed before passing any relevant data to any child components.

Next.js will treat any page in the pages directory as a route for the application.

Main Component

All the pages are rendered by the Main component, located at pages/page/[[..slug]].jsx. Catch all routes in Next.js are made optional by including the parameter in double brackets ([[…slug]]). The root page which defaults to the first page in the pages list doesn’t have the parameter passed to it and hence we define the slug param to be optional.

The component imports the API to get data from the services.js file.

import { fetchOceMinimalMain, fetchPage, getRenditionURLs } from '../scripts/services';

The URLs for the pages are dynamic URLs containing the page slug as a path, example URL paths are

When Next.js uses static site generation for pages with dynamic URLs it calls getStaticPaths() to get all the paths for that page.

export async function getStaticPaths() {
      const appData = await fetchOceMinimalMain();
      const { fields } = appData;
    
      // Generate the paths we want to pre-render based on posts
      const paths = fields.pages.map((page) => ({
        params: { slug: [page.slug] },
      }));
      // Also add the path for the root /
      paths.push({
        params: { slug: [] },
      });
      return {
        paths,
        fallback: false,
      };
    }

The getStaticProps() function is used to get the data for a single instance of the Page. The page slug is obtained from the parameter passed into the method. The page slug is then used to get all the data required for this page.

export async function getStaticProps(context) {
      // fetch the minimal main data
      const appData = await fetchOceMinimalMain();
      // find the slug param from the context. If its null, default to the first page slug
      const { params } = context;
      let { slug } = params;
      if (slug == null) {
        slug = appData.fields.pages[0].slug;
      }
      // fetch the page corresponding to the slug
      const pageData = await fetchPage(slug);
      const { headerRenditionURLs, footerRenditionURLs, fields } = appData;
      const { sections } = pageData.fields;
    
      // for each section in the page, if a image is present, get the corresponding rendition urls
      // and insert it back into the section
      const promises = [];
      sections.forEach((section) => {
        // add a promise to the total list of promises to get any section rendition urls
        if (section.fields.image) {
          promises.push(
            getRenditionURLs(section.fields.image.id)
              .then((renditionURLs) => {
                // eslint-disable-next-line no-param-reassign
                section.renditionURLs = renditionURLs;
              }),
          );
        }
      });
    
      // execute all the promises and return all the data
      await Promise.all(promises);
      return {
        props: {
          headerRenditionURLs,
          footerRenditionURLs,
          pages: fields.pages,
          pageData,
        },
      };
    }

Page Component

The Page component is responsible for rendering all the sections defined for a page. Open the Page component, located at components/Page.jsx. It simply uses the data passed to it from the Main component. It does not get any additional data from the server. It uses the Section component to render the section data.

Page.propTypes = {
      pageData: PropTypes.shape().isRequired,
    };

The Header component, located at components/Header.jsx, and the Footer component, located at components/Footer.jsx, simply use data passed to them from the Main component. They do not get any additional data from the server.

Section Component

The Section component, located at 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.

Error Component

The Error component, located at components/Error.jsx, is used by the Page and the Main 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 Next.js 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 the application for deployment in two steps:

  1. Spin up a local development server
  2. Use scripts to build and run the application in development and production

Spin Up a Local Development Server

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

npm run dev

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

Note: This will not pre-render the pages. In order to pre-render the pages, see the next section.

Use Scripts to Build and Run the Application in Development and Production

For production, the build script would be used to statically generate the site.

npm run build

The start script is used to start a Node.js server serving the statically generated pages.

npm run start