Integrate Kameleoon with Contentful

Written by Julie Trenque

Updated on 02/08/2024

3 min

Intermediate

Manage your integrations

Analytics

Automation

CDP

CMP

CMS/CRM

Data Warehouses

Developers

Was this content useful?

Contentful is a headless CMS, a composable content platform that meets the unique demands of digital content and all the teams that produce and work with it. 

Built with an API-first architecture, Contentful orchestrates content from multiple sources and publishes it to any digital channel. It ensures content is discoverable and reusable, provides tailored interfaces, and incorporates governance through role-based access management and workflows.

The Contentful Integration allows Contentful users to run experiments (including feature experiments) on content directly from Contentful and use Kameleoon’s powerful analytics solution to analyze the performance of those experiments.

Key benefits

  • Bringing experimentation capabilities to Contentful for users in charge of managing the website content through Contentful CMS
  • Keep Contentful as the single source of truth for your content
  • Run advanced no-code experiments on structured content (copy, components, layouts and pages) managed in Contentful
  • Reduce the amount of manual work needed and get the best of both world: managing variants of an experiment (including feature experiments) in Contentful, benefiting from Kameleoon powerful experimentation engine and analytics capabilities
  • Marketers don’t have to be dependent on developers to lead experimentation
  • No flicker: benefiting from server side instant bucketing by serving variations with no latency

Considerations

Keep these things in mind when using this integration:

  • This integration can be used with feature experiments only.
  • You need to have the Feature Experimentation solution enabled on your Kameleoon account.

Prerequisites

To configure this  integration, you need the following information from Kameleoon:

  • Login credentials: Your Kameleoon login credentials are the email address and password combination that allows you to access your Kameleoon account. This integration is using the OAuth authentication to log in your Kameleoon account.
  • Sitecode: To know the project that will be used with this integration, you need to provide the Sitecode of your project. See the dedicated Kameleoon documentation to know where you can find your Sitecode. 

Terminology

Let’s start by explaining some of the most used terms of this document. 

What is an entry?

A piece of content, based on a content type. Entries are comprised of different fields. Think of them as the drawing you create with your content type stencil. 

What is a content type?

A content type works like a stencil that defines the structure of an entry. Each content type comprises fields that denote the kind of content that will be included in the entry. Content types are created in spaces. When a content type is created and activated, editors are able to create individual entries using it.

What is a field?

Fields are what content types are comprised of. They are defined by you. Common field types include short text field, media field, and reference field. 

  • Short text field: Short texts are relatively small tokens of text, often used for titles and names.
  • Media field: These include images, videos, PDFs and similar files.
  • Reference field: Contentful uses reference fields to create relationships between content types. A basic example of using a reference field is to link a blog post to its author.

What is a Kameleoon Container?

When you install the Kameleoon integration from Contentful’s marketplace, behind the scenes, it will automatically create a new content type called Kameleoon Container

Kameleoon Container is a special kind of content type that allows users to define the content of their variations (associating each variation with a specific entry).

This content type will be listed in the Content model page as soon as you finish installing the Kameleoon app.

Installation

  1. Go to your Contentful account.
  2. Go to Apps → Marketplace and search for Kameleoon.
  1. Install the Kameleoon app and authorize access.
  1. Configure the Kameleoon app with the project you want it to use.
    • Select the sitecode of your project.
    • Click on the Install button at the top right corner.
  1. The Kameleoon app is now fully installed and ready to be used.

Usage

Step 1 – Create a feature experiment in Kameleoon

To create a new feature experiment:

  1. Go to your Kameleoon account and go to the feature flag dashboard.
  2. Create a new feature flag:
    1. Click New feature flag.
    2. Enter the name, project and feature key and click Validate.
  3. Configure your feature flag to be a feature experiment:
    1. Add an Experiment Delivery Rule by clicking Add a rule Experiment.
    2. You can configure this rule the way you want to.

Step 2 – Create a Kameleoon Container entry in Contentful

  1. Go to your Contentful account and go to the Content page (you can use the navigation menu at the top of the page).
  1. Click on Add Entry and select Kameleoon Container.
  1. Configure your Kameleoon Container entry:
  • Enter an Entry Name.
  • Select an experiment in the Kameleoon experiments dropdown. The variations associated with the experiment you selected will be automatically displayed, along with the percentage of allocated traffic.
  • For each variation, click on Create entry and link to create a new entry and use it as your variation content, or click on Link an existing entry if you want to use an existing entry as the variation’s content.

Step 3 – Get ready to publish your content

Your Kameleoon Container will be ready to be published when you will have the four steps marked as checked:

Here’s how you can validate each step:

  1. Select experiment – You can validate this step by selecting one experiment in the Kameleoon experiments dropdown.
  2. Add content – You can validate this step by associating an entry for each variation.
  3. Publish variations – This step will be marked as check when all the entries associated with the variations will be published.
  4. Start experiment – To validate this step: go to your Kameleoon account and use the manual toggle to  turn the feature flag ON in the production environment.

Integration with your front-end

Kameleoon Container is a new content type that is introduced into the Contentful response. It is a container that points to two or more actual values that we’d like to test. You now need to integrate your front-end with Kameleoon and the Kameleoon Container. At this point, we need the help of a developer to change how your front-end works to accept and programmatically handle the Kameleoon Container entries.

Programmatically handling the Kameleoon Container is something you only need to do once. Then, the code used to handle the Kameleoon Container can be reused every time you receive a Kameleoon Container entry from Contentful. 

From here, we need to take a more technical dive into the setup of the client and how it integrates with Kameleoon. It is beneficial for developers to get acquainted with the content we outlined above before moving onto the technical guide below.

The goals of the setup are:

  • Enabling server side experimentation without pushing new code per experiment
  • Separating concerns: controlling content in Contentful and experiments in Kameleoon
  • Speed: server side selection of variations for fast delivery and to avoid the flicker effect

How the Kameleoon App changes the Contentful API response

As mentioned above, the Kameleoon app creates a new content type: the Kameleoon Container. 

The Kameleoon Container is simply a content type that nests the possible values for the experiment and holds metadata about the Kameleoon experiment and the variation names.

Using Kameleoon to pick the right variation

We are going to create a pseudo-backend which takes the Contentful API response and uses our NodeJS SDK to determine which variation to show to the user.

Let’s start by looking at the Kameleoon Container JSON response returned by Contentful. Notice that the content type exposes several fields related to the Kameleoon experiment: a featureKey and a meta with variation keys.

{
    "metadata":{
       "tags":[
   ]
 },
    ……
    "fields":{
       "entryName":{
          "en-US":"Black Friday - CTA"
       },
       "experimentName":{
          "en-US":"Black Friday - CTA - Experiment"
       },
       "experimentId":{
          "en-US":"229925"
       },
       "featureKey":{
          "en-US":"contentful_black_friday_cta"
       },
       "siteCode":{
          "en-US":"kqfwz0rys3"
       },
       "meta":{
          "en-US":{
             "off":"5IF12vtaKcFJXtj8ljaDVr",
             "variation_1":"2UrVZemBoltsxHKcqRgjKk",
             "variation_2":"73GxfiNActyOZvP9Hn3sEC"
          }
       },
       "variations":{
          "en-US":[
             {
                "sys":{
                   "type":"Link",
                   "linkType":"Entry",
                   "id":"5IF12vtaKcFJXtj8ljaDVr"
                }
             },
             {
                "sys":{
                   "type":"Link",
                   "linkType":"Entry",
                   "id":"2UrVZemBoltsxHKcqRgjKk"
                }
             },
             {
                "sys":{
                   "type":"Link",
                   "linkType":"Entry",
                   "id":"73GxfiNActyOZvP9Hn3sEC"
                }
             }
          ]
       }
    }
 }

Before we can choose which entry to pick out of our Kameleoon Container, we need to see how to get the right variation from Kameleoon. Below is an example with the hardcoded feature key “contentful_black_friday_cta” in the Kameleoon method “getFeatureFlagVariationKey”, which gets a variation for the user.

import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';

 const client = new KameleoonClient({
   siteCode: 'a8st4f59bj',
   credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
   configuration: { domain: 'www.example.com' },
 });
 async function init(): Promise {
   await client.initialize();

 // -- Get visitor code using server request and response
   const visitorCode = client.getVisitorCode({
     request: req,
     response: res,
   });

 // -- Get visitor feature flag variation key
   const variationKey = client.getFeatureFlagVariationKey(
     visitorCode,
     'contentful_black_friday_cta',
   );
 }
 init();

In the code above, the method “getFeatureFlagVariationKey” determines if the user (or visitor) should see one of the variations or the original content. The value corresponds to one of the variations we can get from the Kameleoon Container meta field.

"meta":{
          "en-US":{
             "off":"5IF12vtaKcFJXtj8ljaDVr",
             "variation_1":"2UrVZemBoltsxHKcqRgjKk",
             "variation_2":"73GxfiNActyOZvP9Hn3sEC"
          }
       }

Now we will update our code to include pulling automatically the Kameleoon Container itself and using its values to populate the Kameleoon experiment, so that you don’t need to do it every time you create and run a new experiment.

Note that this is a one time setup that will work for all subsequent experiments that you create.

import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
 import sdk from 'contentful-sdk';

  const client = new KameleoonClient({
    siteCode: 'a8st4f59bj', // Your Kameleoon project sitecode
    credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' }, // Your Kameleoon API credentials 
    configuration: { domain: 'www.example.com' },
  });

  async function init(): Promise {
    await client.initialize();
  // -- Get visitor code using server request and response
    const visitorCode = client.getVisitorCode({
      request: req,
      response: res,
    });

 // We are using the id of the Kameleoon Container from the JSON sample above
   // In a real-world implementation, the ID would be set dynamically through, e.g. a slug.
    const kameleoonContainerEntry = await sdk.getEntry('5XJ5TWDvAzPh7QgWN4ysaV');

 // We get the feature key from the Kameleoon Container entry
    const featureKey = kameleoonContainerEntry.featureKey;

 // We get the key of the variation that we have to display
    const variationKey = client.getFeatureFlagVariationKey(
      visitorCode,
      featureKey,

    );

 // We get the Contentful entry associated with the variation using the variation Key
    const variationEntry = kameleoonContainerEntry.meta[variationKey];
 }
  init();

From here, you should be able to make minimal changes to your display logic in order to show the correct entry.

Using Kameleoon to target a segment of users

If you need to target a specific segment of users, this can be done directly in Kameleoon. You can read this documentation that explains how to create segments of users and include / exclude them from your experiment.

  • In this article :