How to Deliver Targeted Content Using Amplience and Dynamic Yield

John Williams
December 2, 2020
10 mins
EngineeringGuidesEcommerce

Originally published December 2020. Updated November 2026 to add the A/B testing guide, the standard Dynamic Yield integration, fixes to the code and current Amplience product names.

To use Dynamic Yield with Amplience, Dynamic Yield decides which experience each visitor gets and Amplience CMS delivers the content for it. Many teams can now use the standard affinity integration and tag content inside Amplience. For custom builds, this guide shows the server-side pattern for A/B tests and audience targeting.

Key takeaways

  1. Dynamic Yield by Mastercard makes the decision. Amplience CMS stores and delivers the content.

  2. The standard affinity integration lets content teams tag content for Dynamic Yield segments inside Amplience, with no code.

  3. For a custom build, the Dynamic Yield Experience APIs and the Amplience Content Delivery API work together on the server side.

  4. Content IDs work for a quick A/B test. Delivery keys and slots are easier for business users to manage.

  5. The same patterns work with React, Vue or a GraphQL layer.

Is there a quicker way to connect Amplience and Dynamic Yield?

Yes. The Dynamic Yield affinity integration lets content teams tag content with Dynamic Yield affinity values, such as brand, lifecycle stage or category interest, directly in the Amplience content form. Dynamic Yield uses those tags to decide which segment sees which content.

Amplience and Dynamic Yield sync tagged content automatically, and it goes live within 5 to 10 minutes of publishing. Teams can preview what each segment will see inside Amplience before anything publishes. Dynamic Yield, part of Mastercard, has been named a Gartner Magic Quadrant leader for personalization for eight years in a row.

For most personalization work, that’s the place to start. Read more on the Amplience and Dynamic Yield partner page, or see how AI-driven personalization fits the bigger picture.

The rest of this guide is for developers who want full control in a headless build. It uses the Dynamic Yield Experience APIs on the server side, so personalization doesn’t depend on JavaScript running in the browser.

What will you build in this guide?

The guide builds on the Dynamic Yield pet shop tutorial, a Node Express app. You’ll replace its homepage banner with content from Amplience CMS, then:

  1. Run an A/B test between banners, using Amplience content IDs.

  2. Target banners to dog lovers and cat lovers, using Amplience delivery keys.

  3. Do the same targeting with an Amplience slot, which is easier for business users to manage.

How do you set up the banner content in Amplience CMS?

Start with a content type for the homepage banner. The pet shop tutorial expects this JSON shape, so the Amplience content should match it:

1{
2  "image": "../image_url",
3  "title": "banner title",
4  "subtitle": "banner subtitle",
5  "cta": "Call to action text",
6  "link": "link for cta"
7}

Amplience CMS models every content type with JSON Schema, so matching the shape is simple:

  1. In Amplience CMS, choose Content type schemas from the Development menu and click Create schema.

  2. Choose Code from scratch and click Get started.

  3. Give the schema the ID http://example.amplience.com/DY-Banner and click Create schema.

  4. Replace the boilerplate with the schema below. Each property name must match the pet shop JSON.

1{
2    "$schema": "http://json-schema.org/draft-07/schema#",
3    "$id": "http://example.amplience.com/DY-Banner",
4
5    "title": "dynamic yield banner",
6    "description": "example banner for dynamic yield",
7
8    "allOf": [
9        {
10            "$ref": "http://bigcontent.io/cms/schema/v1/core#/definitions/content"
11        }
12    ],
13
14    "type": "object",
15    "properties": {
16        "image": {
17            "title": "banner image",
18            "allOf": [
19                { "$ref": "http://bigcontent.io/cms/schema/v1/core#/definitions/image-link" }
20            ]
21        },
22        "title": {
23            "title": "banner title",
24            "description": "main title for the banner",
25            "type": "string",
26            "minLength": 0,
27            "maxLength": 100
28        },
29        "subtitle": {
30            "title": "subtitle",
31            "description": "secondary title for the banner",
32            "type": "string",
33            "minLength": 0,
34            "maxLength": 200
35        },
36        "cta": {
37            "title": "cta",
38            "description": "call to action text",
39            "type": "string",
40            "minLength": 0,
41            "maxLength": 100
42        },
43        "link": {
44            "title": "link",
45            "description": "link for cta",
46            "type": "string",
47            "minLength": 0,
48            "maxLength": 300
49        }
50    },
51    "propertyOrder": []
52}

The image property lets business users pick an image from Amplience DAM instead of typing a URL, and Amplience Dynamic Media serves it. Later, the code turns the image object into a URL so it matches the pet shop format.

  1. Choose Save and register as content type from the Save menu. Name it Dynamic Yield Banner Example, add an icon and assign it to the repository where business users will create the banners.

Now create three banners: a generic pet lovers banner, a dog lovers banner and a cat lovers banner.

  1. In that repository, click Create content and choose Dynamic Yield Banner Example.

  2. Pick an image and fill in the fields.

  3. Click Save and name it dog gift promotion.

  4. Choose Publish from the menu at the top right.

  5. Repeat for cat gift promotion and pet gift promotion.

To check a banner is live, open the content properties pane with the i icon and select the Content Delivery 2 URL. The JSON looks something like this:

1{"content":
2{"_meta":{"name":"dog gift promotion",
3"schema":"http://example.amplience.com/DY-Banner","deliveryId":"a8795733-7356-4785-9d20-38d9fe4d98c7"},
4"image":{"_meta":{"schema":"http://bigcontent.io/cms/schema/v1/core#/definitions/image-link"},
5    "id":"c89445d4-4350-408f-9c12-8b66943e2885","name":"hannah-lim-U6nlG0Y5sfs-unsplash",
6    "endpoint":"jwdemo",
7    "defaultHost":"i1.adis.ws"},
8"title":"The Usual doggy Suspects",
9"subtitle":"gifts for all dogs",
10"link":"/category/dogs",
11"cta":"pamper your pooch"}}

How do you set up Dynamic Yield for Amplience content?

Dynamic Yield needs a template that holds the identifier of an Amplience content item. Use this template JSON. The title field is optional and only helps business users recognize each variation:

1{
2  "amplienceID": "${Amplience_ID}",
3  "title": "${title}"
4}
  1. In Dynamic Yield, go to Assets > Templates and click Add New.

  2. Name the template Amplience content and choose the template type Custom API Campaign.

  3. Click Next, switch to the JSON tab and paste in the template.

Then set up the A/B test:

  1. Go to API Campaigns and click Add New > Custom.

  2. Name the campaign Amplience Banner.

  3. Name the experience Default Experience, leave targeting as All users and click Next.

  4. Click New Variation, choose the Amplience content template and paste in the content ID of the pet gift promotion. To find it in Amplience CMS, open the menu on the content item, choose Get content ID and copy it.

  5. Add a second variation with the content ID of the dog gift promotion.

  6. Check that A/B test is selected with a 50% split and Click Through Rate as the primary metric, then save.

How do you set up the development environment?

  1. Follow the pet shop tutorial instructions to set up the app, or use one you’ve built before.

  2. In the app’s folder, install the Amplience Content Delivery SDK:

1npm install dc-delivery-sdk-js

How do you connect the APIs for an A/B test?

The server-side code does three things: ask Dynamic Yield which variation to show, fetch that content from Amplience, and reshape it for the pet shop templates.

In the base folder of the app, create a file called amplienceAPI.js. Set your hub name, which you’ll find under Settings > Properties in Amplience CMS:

1// Set up the Amplience SDK with your hub name
2const { ContentClient } = require('dc-delivery-sdk-js');
3const client = new ContentClient({
4    hubName: 'your-hub-name'
5});
6
7// Retrieve content using its content ID
8async function getContentItemById(contentId) {
9    let variant = null;
10    try {
11        const response = await client.getContentItemById(contentId);
12        variant = response.body;
13        // Build a Dynamic Media image URL from the image object
14        variant.image = response.body.image.url().build();
15    } catch (error) {
16        console.log('Amplience content not found', error);
17    }
18    return variant;
19}
20
21module.exports = {
22    getContentItemById
23};

The function returns null when content can’t be found, so the page falls back to the default banner instead of an empty one. You can add Dynamic Media parameters to the image URL, such as size or format, at the same point.

Then open routes/homepage.js, require the new module and change getPageContent to call the Amplience Banner campaign:

1const DYAPI = require('./../DYAPI');
2const AmplienceAPI = require('./../amplienceAPI');
3
4// Later in the file
5async function getPageContent(req) {
6    req.dyContext.page.type = 'HOMEPAGE';
7    const apiResponse = await DYAPI.choose(req.userId, req.sessionId, req.dyContext, ['Amplience Banner']);
8    const amplienceResponse = await AmplienceAPI.getContentItemById(apiResponse['Amplience Banner']?.amplienceID);
9    const content = {
10        heroBanner: amplienceResponse || defaultHeroBanner,
11        recommendations: defaultRecommendations,
12    };
13    if (req.originalUrl.includes('SALE')) {
14        content.overlay = defaultOverlay;
15    }
16    return content;
17}

Run npm start and open

1http://localhost:3000

You’ll see one of the two banners. Dynamic Yield keeps each visitor on the same variation while the test runs, so open a new private window to see the other.

How do you target content with delivery keys?

Content IDs are machine-generated and hard to read. A delivery key is a name a business user gives a content item in Amplience CMS, which the live Content Delivery API can use to fetch it. A simple naming convention can then link Amplience content to Dynamic Yield campaigns.

First, create two audiences in Dynamic Yield: visitors who added dog products to cart in the last month, and visitors who added cat products. Set the condition to Products added to cart and the category to Dogs, then Cats.

Next, create a targeted campaign:

  1. Create a new custom API campaign and name it HP Banner.

  2. Change the selector name to HP-Banner. The code uses it, and it can’t contain spaces.

  3. Create an experience for all users with a variation from the Amplience content template. Name it pet promo and set Amplience_ID to pet-promo. Save the experience as Default.

  4. Add a new experience above it called dog lovers. Under Who, choose the audience that added dog products to cart, add a variation called dog promo with Amplience_ID set to dog-promo, and save.

  5. Add a cat lovers experience in the same way, with Amplience_ID set to cat-promo.

Now give the banners delivery keys in Amplience CMS. The key is the campaign selector and the Amplience_ID joined by a hyphen:

  • HP-Banner-pet-promo

  • HP-Banner-dog-promo

  • HP-Banner-cat-promo

Open the menu on each banner in your repository, choose Delivery key, enter its key and save. Publish each banner again so the key goes live.

Add a function to amplienceAPI.js that fetches content by delivery key:

1// Retrieve content using its delivery key
2async function getContentItemByKey(deliveryKey) {
3    let variant = null;
4    try {
5        const response = await client.getContentItemByKey(deliveryKey);
6        variant = response.body;
7        // Build a Dynamic Media image URL from the image object
8        variant.image = response.body.image.url().build();
9    } catch (error) {
10        console.log('Amplience content not found', error);
11    }
12    return variant;
13}
14
15module.exports = {
16    getContentItemById,
17    getContentItemByKey
18};

Then update getPageContent in routes/homepage.js to call the HP-Banner campaign and build the key from its response:

1async function getPageContent(req) {
2    req.dyContext.page.type = 'HOMEPAGE';
3    const apiResponse = await DYAPI.choose(req.userId, req.sessionId, req.dyContext, ['HP-Banner']);
4    const amplienceKey = 'HP-Banner-' + apiResponse['HP-Banner']?.amplienceID;
5    const amplienceResponse = await AmplienceAPI.getContentItemByKey(amplienceKey);
6    const content = {
7        heroBanner: amplienceResponse || defaultHeroBanner,
8        recommendations: defaultRecommendations,
9    };
10    if (req.originalUrl.includes('SALE')) {
11        content.overlay = defaultOverlay;
12    }
13    return content;
14}

Open

1http://localhost:3000

and you’ll see the pet lovers banner. Add a cat product to your basket, go back to the homepage, and the cat lovers banner appears. Try the same with a dog product in a new private window.

How do you target content with slots?

Naming conventions are easy to understand but easy to get wrong. A slot is a cleaner option. In Amplience CMS, a slot is a special content item that represents an area of your site, such as the homepage banner, and it’s defined with JSON Schema like any other content.

This slot holds a list of experiences, each pairing a Dynamic Yield target with a banner:

1{
2  "experiences": [
3    { "content": "…", "target": "dog-promo" },
4    { "content": "…", "target": "cat-promo" },
5    { "content": "…", "target": "pet-promo" }
6  ]
7}

The Dynamic Yield campaign and the banners stay as they are. To create the slot type:

  1. In Amplience CMS, choose Content type schemas from the Development menu and click Create schema.

  2. Choose Code from scratch and give the schema the ID https://example.amplience.com/dy-slot.

  3. Set the validation level to Slot and click Create schema.

  4. Replace the properties section with the code below.

1    "properties": {
2        "experiences": {
3            "title": "Dynamic Yield Targeted Experience",
4            "description": "description",
5            "type": "array",
6            "minItems": 1,
7            "maxItems": 10,
8            "items": {
9                "title": "Dynamic Yield Targeted Experience",
10                "type": "object",
11                "properties": {
12                    "target": {
13                        "title": "target",
14                        "description": "The target name passed from dynamic yield",
15                        "type": "string",
16                        "minLength": 0,
17                        "maxLength": 250
18                    },
19                    "content": {
20                        "title": "content",
21                        "allOf": [
22                            { "$ref": "http://bigcontent.io/cms/schema/v1/core#/definitions/content-link" },
23                            {
24                                "properties": {
25                                    "contentType": {
26                                        "enum": [
27                                            "http://example.amplience.com/DY-Banner"
28                                        ]
29                                    }
30                                }
31                            }
32                        ]
33                    }
34                },
35                "propertyOrder": ["target", "content"]
36            }
37        }
38    }

The schema defines an experiences array. Each item has a target, the value Dynamic Yield sends, and a content link that only accepts banners built on the DY-Banner schema.

  1. Save and register it as a content type called Dynamic Yield Slot Example, and assign it to your slot repository.

Now set up the slot:

  1. In the slot repository, click Create content and choose Dynamic Yield Slot Example.

  2. Enter dog-promo as the target and add the dog gift promotion as the content.

  3. Click Add Dynamic Yield Targeted Experience, enter cat-promo and add the cat gift promotion.

  4. Add a third with pet-promo and the pet gift promotion.

  5. Click Save, then set the slot’s delivery key to hp-banner.

Add a function to amplienceAPI.js that fetches the slot by its key and picks the banner for the Dynamic Yield target:

1// Retrieve a slot by delivery key and pick the content for a Dynamic Yield target
2async function getContentFromSlotByKeyAndTarget(deliveryKey, target) {
3    let variant = null;
4    try {
5        const response = await client.getContentItemByKey(deliveryKey);
6        const experience = response.body.experiences.find(item => item.target === target);
7        if (experience) {
8            variant = experience.content;
9            // Build a Dynamic Media image URL from the image object
10            variant.image = variant.image.url().build();
11        }
12    } catch (error) {
13        console.log('Amplience content not found', error);
14    }
15    return variant;
16}
17
18module.exports = {
19    getContentItemById,
20    getContentItemByKey,
21    getContentFromSlotByKeyAndTarget
22};

Then change getPageContent to pass the slot key and the target from Dynamic Yield. You no longer need the amplienceKey line:

1async function getPageContent(req) {
2    req.dyContext.page.type = 'HOMEPAGE';
3    const apiResponse = await DYAPI.choose(req.userId, req.sessionId, req.dyContext, ['HP-Banner']);
4    const amplienceResponse = await AmplienceAPI.getContentFromSlotByKeyAndTarget('hp-banner', apiResponse['HP-Banner']?.amplienceID);
5    const content = {
6        heroBanner: amplienceResponse || defaultHeroBanner,
7        recommendations: defaultRecommendations,
8    };
9    if (req.originalUrl.includes('SALE')) {
10        content.overlay = defaultOverlay;
11    }
12    return content;
13}

Test it the same way as before. The calls here run one after the other to keep the example simple, and in production you can make the Amplience and Dynamic Yield requests in parallel.

Where should you go from here?

You now have three ways to combine Amplience CMS and Dynamic Yield on the server side: content IDs for a quick A/B test, delivery keys for readable targeting, and slots for setups business users can manage. Any of them can also run behind React, Vue or a GraphQL layer.

If your team would rather tag content than write code, the Dynamic Yield affinity integration brings targeting into the Amplience content form. To talk through the right setup for your stack, get in touch with Amplience.