How we accelerate, bootstrap and launch new promotions using Contentful

Sumit Duggal
Engineering the Skies: Qantas Tech Blog
10 min readSep 20, 2023

Leverage Headless CMS platforms like Contentful to elevate the developer experience and achieve content delivery with exceptional flexibility in today’s fast-paced landscape marked by tight deadlines and rapid turnarounds.

This article will highlight how we can use Headless CMS such as Contentful to empower developers to build product by decoupling the content from the UI. This approach enhances the product flow and facilitates the parallelisation of the development process.

Table of contents:

  • Explain Contentful to a developer
  • How is Contentful integrated in our development pipeline
  • How we deliver campaigns/promotions quickly with Compose
  • How to write type safe code with Contentful

Explain Contentful to a developer

Contentful is a headless CMS and content platform that is both cloud-native and highly extensible. Headless CMS means Contentful facilitates separating content updates and creating without considering end user UI/devices as part of the process — it could be a simple static web page, fully featured JavaScript framework site or a mobile app. It is a platform agnostic, api driven and multiple environment supporting tool that is designed in a modular way to connect with 3rd party services to increase productivity.

From Contentful’s website it explains:

Build captivating experiences that stand out with the intelligent composable content platform

How is Contentful API structured?

To facilitate versatile app development, the Contentful team has adeptly divided interactions with their product into two distinct categories:

  1. Management
  2. Delivery

As the names intuitively imply, the Management aspect revolves around content oversight and seamless synchronisation with their native cloud platform. This encompasses all essential CRUD functions: creation, retrieval, updating, and deletion. This category can be further subdivided into two vital subcategories:

  • Content Management API: This API enables both content creation and modification. It can be accessed through the following link: Content Management API.
  • Content Preview API: This API, on the other hand, facilitates read-only access, offering users the ability to preview content in draft or development mode. For more information, please visit: Content Preview API.

On the contrary, the Delivery category is tailored to ensure seamless production-readiness. This involves deployment to Content Delivery Networks (CDNs) distributed globally, supported by cutting-edge caching mechanisms. The overarching goal is to expedite content delivery to end-users from the nearest source, ensuring optimal performance. Furthermore, the system performs cache purging when new content is published. For premium members, advanced caching strategies are available for configuration.

The Delivery category can be further dissected into the subsequent subcategories:

  • Content Delivery API: Primarily a read-only API, it serves data in its published state. This API is indispensable for production environments due to its performance enhancements and safeguarding against unintended changes.
  • Image API: Another read-only API, it facilitates on-the-fly image retrieval and manipulation. This encompasses functionalities like resizing, cropping, and other image adjustments.

By categorically organising their interactions into these distinct modules, Contentful has empowered developers to create applications with enhanced flexibility and efficiency.

How is Contentful integrated in our development pipeline?

Leveraging Contentful within our content delivery platform introduces the capability to streamline and expedite the development and approval processes concurrently, thereby accelerating campaign delivery.

Let’s list the steps for a simple copy change example with the help of Contentful’s CMS.

Step 1: Identifying changes and securing approvals

By integrating Contentful into the pipeline, we can seamlessly share the draft copy changes (with a reasonable assurance of the copy’s structure) with developers.

This enables bootstrapping the implementation of logic and modifications essential to the workflow.

Step 2: Implementing code changes and facilitating reviews

During this phase, developers can commence making draft changes within Contentful which accelerates previewing promotions quicker and rapid iteration. They can seamlessly integrate and preview these changes either locally or within a non-production environment. Furthermore, these changes can undergo the rigor of code reviews and QA testing, allowing progression while awaiting final copy approval.

This parallel approach empowers us to implement structural and UI alterations with a high degree of confidence.

Step 3: Deploying copy changes on campaign day

Contentful’s integration provides us with the flexibility to deploy code changes to production environment with more confidence. Whether it involves a new page, a different layout, or content-only modifications, the assurance of unpublished content safeguarding against accidental releases is invaluable.

Contentful’s cloud app seamlessly schedules content change publication with preset dates and times. Consequently, we can proceed with deployment with the knowledge that our changes will be presented in their published state through the Content Delivery API as scheduled.

This orchestration of Contentful’s CDN integration within our app not only simplifies complexity but also outsources content publication and runtime retrieval, effectively decoupling UI rendering logic from the content itself whether it’s text, images, or videos. This strategic separation optimises our development process while enhancing overall efficiency.

How we deliver campaigns/promotions quickly with Compose?

At Qantas Insurance, we handle multiple promotional campaigns ranging from Home Insurance, Health Insurance to Car Insurance. We recognised that there are patterns emerging across our web apps, these pages share a consistent layout, with minor differentiations primarily in terms of content updates.

To enhance this process, we sought out a solution and discovered the potential of Compose within the Contentful ecosystem.

While Contentful’s foundational approach revolves around a modular, headless CMS, Compose provide simplified way to manage structured content more adeptly for web pages.

Compose is an app from Contentful, which takes a page-centric approach to content creation and editing. https://www.contentful.com/developers/docs/compose/what-is-compose/

Compose reduces the need for constant navigation through intricately nested references, consolidating them into a unified editing interface.

Utilising Compose app offers several advantages, including:

  • Reduced nesting of content types.
  • No mandatory predefined content types or naming conventions.
  • Flexibility for unique slug names/patterns based on page type.
  • Elimination of superfluous mandatory fields, streamlining the startup process.
  • A dedicated section for SEO metadata.
  • Customisable page editor for tab arrangement and adjustments.

Process to create new template page

When we have a new templated page to launch we usually start with the following process

Pattern identification and design

Our journey starts by collaborating with designers to pinpoint recurring patterns. This includes crafting layouts for distinct categories such as Product Landing Pages, Product Information Pages, Insurance Homepages, and more.

Example of a Basic Templated Page with Placeholder Copy

Code and dreate new layout page on compose

Subsequently, we proceed to establish a new content model/page type using the existing Contentful app (https://app.contentful.com). This encapsulates page-specific content and configurations, for instance slugs and SEO metadata. For clarity, prefixing the content model with the convention Page: aids in swift identification among the list of content types.

Creating a New Content Model for Page Type

Once the page type structure is established, it’s designated as a Page type within Compose (https://compose.contentful.com/spaces/{{spaceId}}/settings/page-types)

Assigning Page Type in Compose Settings

Following this, the page can be crafted within Compose itself by clicking the Create Page button in https://compose.contentful.com/spaces/{{spaceId}}

For creating a page template capable of fetching page-specific information, we can leverage the Contentful JavaScript SDK. It provides both the management (preview) and delivery API capabilities, distinguished by unique environment, access token, and space IDs.

Here’s a sample code snippet demonstrating the retrieval of unique page-specific content:

const getPage = async <T>(params: GetPageParams): Promise<Entry<T> | null> => {
const query = {
limit: 1,
include: 10,
'fields.slug': params.slug,
content_type: params.pageContentType,
};

const {
items: [page],
} = await getClient().getEntries<T>(query);
return page || null;
};

And this can be integrated into a helper function or a server side hook to fetch and pass data down to the templated page component as show below with NextJs:

export const getServerSideProps = async ({ params, query }) => {
const slug = String(params.slug);
const pageContentType = 'tutorial'; /* <- the id of the new page type */
const page = await getPage({
slug,
pageContentType
})
return {
props: { page },
};
};

These props can be passed down to the Page component and components can be mapped to render as per the content type to make this page as dynamic as possible, as shown below:

const ContentTypeMap = {
'page_help_center_article': HelpCenterArticle,
'component_text': Text,
'component_image': Image,
'component_video': Video,
...
};

const Tutorial = ({ page }: { page: TypePage }) => {
if (!page) {
//getServerSideProps did not find the page
return <ErrorPage statusCode={404} />
}

/* Visualize the data as you see fit, sky is the limit */
return (
<>
{/* We reuse the existing code for title and seo metadata rendering in the header */}
<PageHead page={page} />
<div>
<div>
<span>
Tutorial
</span>
{
// example code
page.fields.map(entry => ContentTypeMap(entry))
}
</div>
</>
)
}

export default Tutorial

In this way, when we need to create a new page based on the Tutorial Template all we have to do is, create a new Page: Tutorial Template page and input the dynamic content, such as SEO metadata, slug and content and we will be able to view this unpublished page locally or in preview environment with minimal or no code alterations.

Publish the new page to production environment

After all Quality assurance and testing finally we are ready to release our awesome tutorial page. This follows the typical way we schedule a Contentful page release, by going to the unpublished page and clicking on its Publish button followed by clicking Set Schedule option.

How to schedule a Page release in Contentful
  • Open Compose.
  • Navigate to the required space.
  • In the “Pages” tab, go to the required page and click on it to open the page editor.
  • In the “Set Schedule” window, select either the Publish or Unpublish radio button depending on your desired action.
  • Select the required date, time and timezone.
  • Click Next. The “Set Schedule — Reference Tree” page is displayed.

We can also use another amazing product from Contentful aptly named Launch, which can be accessed at https://launch.contentful.com and can be used to create a release schedule for multiple unpublished pages at the same time under a single release, this is quite useful when we have a big campaign which spans across whole suite of page and categories.

How to write type safe code with Contentful?

Contentful simplifies the process of integrating CMS content into our client app. The team maintains several official libraries, and there are many community-supported modules available for languages such as JavaScript, TypeScript, Python, Java, Ruby, PHP, and more. These libraries make it easier for developers to interact with Contentful’s various APIs in their preferred language.

Since Qantas Insurance frontend is powered by JavaScript, we can use Contentful’s npm library (https://github.com/contentful/contentful.js) to query content on demand. To enhance the developer experience and make it more typesafe, we can use Contentful’s management library (https://github.com/contentful/contentful-management.js) to query Content Models and create typescript typings.

At Qantas Insurance, we use contentful-typescript-codegen to generate typeScript typings from our Contentful environment.

To generate the required typings, you need the following:

  • The dotenv package (to insert environment variables at runtime)
  • A personal access token (to connect with Contentful using the contentful-management library)
  • contentful-typescript-codegen
  • and a npm script

To generate a personal access token, visit CMA Tokens page and follow the instructions to generate token.

Next, we need to install the npm package as shown below:

yarn add --dev contentful-typescript-codegen
# or npm
npm i --dev contentful-typescript-codegen

Add an NPM script to automate the process of generating typings:

{
// ...
"scripts": {
"contentful-typescript-codegen": "contentful-typescript-codegen --output output/path/contentful.d.ts"
}
}

Finally, create a getContentfulEnvironment.js or getContentfulEnvironment.ts file in the root directory of your project. This is required by contentful-typescript-codegen to connect to your Contentful environment. Code example below:

require('dotenv').config();
const contentfulManagement = require("contentful-management")

module.exports = function() {
const contentfulClient = contentfulManagement.createClient({
accessToken: process.env.CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN,
})

return contentfulClient
.getSpace(process.env.CONTENTFUL_SPACE_ID)
.then(space => space.getEnvironment(process.env.CONTENTFUL_ENVIRONMENT))
}

When you trigger the npm script npm run contentful-typescript-codegen, it will output the typings file at the declared path. The file will look something like this:

interface IBlogPostFields {
/** Title */
title: string
/** Body */
body: Document
/** Author link */
author: IAuthor
/** Image */
image: Asset
/** Published? */
published: boolean | null
/** Tags */
tags: string[]
/** Blog CTA variant */
ctaVariant: "new-cta" | "old-cta"
}
/**
* A blog post.
*/
export interface IBlogPost extends Entry<IBlogPostFields> {}

The script may display an error, such as 403, if the personal access token is missing from the environment variables.

Conclusion

Contentful is a modular, platform agnostic tool that introduces flexibility, increases collaboration between different stakeholders, enable rapid iteration and provides customisation when compiled with type safety and content structuring tools such as Compose helps to reduce time to market significantly by decoupling content from UI, optimise content delivery with global CDN and advanced caching strategy.

However, these advantages are not without trade-offs. The integration of new tools into the development ecosystem brings forth its own set of considerations.

This includes the need for adaptation to a fresh toolchain, the potential for increased development overhead, and the investment in navigating the learning curve associated with novel tools. Weighing these factors is vital to ensure a well-informed decision when opting for such an approach.

Information has been prepared for information purposes only and does not constitute advice.

--

--