node package manager
It’s your turn. Help us improve JavaScript. Take the 2017 JavaScript Ecosystem Survey »

@adobe/target-node-client

Adobe Marketing Cloud Client

The Adobe Marketing Cloud Client lets customers execute requests against the Adobe edge network and retrieve personalized content that can be used to enhance the user experience.

Behind the scenes, the Marketing Cloud Client wraps two Adobe Marketing Cloud solutions:

  • The Marketing Cloud Identity Service (MCID), also known as the Visitor API
  • Adobe Target

Super Simple to Use

The Marketing Cloud Client has been designed to be the simplest way to interact with the Adobe Target delivery API.

const MarketingCloudClient = require("@adobe/target-node-client");
 
const marketingCloudClient = MarketingCloudClient.create({
  config: {
    client: "acmeclient",
    organizationId: "1234567890@AdobeOrg",
    timeout: 5000
  }
});
 
marketingCloudClient.getOffer({
  payload: {
    mbox : "some-mbox"
  }
})
.then(offer => console.log('Offer', offer))
.catch(error => console.error('Error', error));

Table of Contents


Target Only

The Marketing Cloud Client can be used to retrieve personalized content from Target without being forced to use the MCID.

const MarketingCloudClient = require("@adobe/target-node-client");
 
const marketingCloudClient = MarketingCloudClient.create({
  config: {
    client: "acmeclient",
    organizationId: "1234567890@AdobeOrg",
  }
});
 
marketingCloudClient.getOffer({
  payload: {
    mbox : "server-side-mbox"
  }
})
.then(offer => console.log('Offer', offer))
.catch(error => console.error('Error', error));

By default, the Marketing Cloud Client generates a new session ID for every Target call, which might not always be the desired behavior. To ensure that Target properly tracks the user session, you should ensure that the Target cookie is sent to the browser when Target content is retrieved and the Target cookie value is passed to getOffer() as a request is processed.

In an Express application, this could look something like this:

const express = require("express");
const cookieParser = require("cookie-parser");
const MarketingCloudClient = require("@adobe/target-node-client");
const CONFIG = {
  client: "acmeclient",
  organizationId: "1234567890@AdobeOrg"
};
 
const marketingCloudClient = MarketingCloudClient.create({config: CONFIG});
const app = express();
 
app.use(cookieParser());
 
function saveCookie(res, cookie) {
  if (!cookie) {
    return;
  }
 
  res.cookie(cookie.name, cookie.value, {maxAge: cookie.maxAge * 1000});
}
 
function sendSuccessResponse(res, offer) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  saveCookie(res, offer.targetCookie);
 
  res.status(200).send(offer);
}
 
function sendErrorResponse(res, error) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  res.status(500).send(error);
}
 
app.get("/abtest", function (req, res) {
  const targetCookieName = encodeURIComponent(MarketingCloudClient.getTargetCookieName());
  const targetCookie = req.cookies[targetCookieName];
  const payload = {"mbox" : "server-side-mbox"};
  const request = Object.assign({payload}, {targetCookie});
 
  console.log("Request", request);
 
  marketingCloudClient.getOffer(request)
  .then(offer => {
    sendSuccessResponse(res, offer);
  })
  .catch(error => {
    sendErrorResponse(res, error);
  });
});
 
app.listen(3000, function () {
  console.log("Listening on port 3000 and watching!");
});

Full sample: https://github.com/Adobe-Marketing-Cloud/target-node-client-samples/tree/master/target-only


MCID Integration

Although using the Marketing Cloud Client for fetching content from Target can be powerful, the added value of using MCID for user tracking outweighs using Target only. MCID allows leveraging all the goodies found in the Adobe Experience Cloud, such as audience sharing, analytics, etc. Using Target and MCID in an Express application is pretty straightforward. MCID has a client-side part, so we'll have to use a simple template that references the MCID JavaScript library.

Here is the Express application:

const express = require("express");
const cookieParser = require("cookie-parser");
const MarketingCloudClient = require("@adobe/target-node-client");
const CONFIG = {
  client: "acmeclient",
  organizationId: "1234567890@AdobeOrg"
};
const TEMPLATE = `
<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Marketing Cloud Client NodeJS SDK Sample</title>
  <script src="VisitorAPI.js"></script>
  <script>
    Visitor.getInstance("${organizationId}", {serverState: ${visitorState}});
  </script>
</head>
<body>
  <p>${content}</p>
</body>
</html>
`;
const marketingCloudClient = MarketingCloudClient.create({config: CONFIG});
const app = express();
 
app.use(cookieParser());
// We assume that VisitorAPI.js is stored in "public" folder
app.use(express.static(__dirname + "/public"));
 
function saveCookie(res, cookie) {
  if (!cookie) {
    return;
  }
 
  res.cookie(cookie.name, cookie.value, {maxAge: cookie.maxAge * 1000});
}
 
function sendSuccessResponse(res, offer) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  const result = TEMPLATE
  .replace("${organizationId}", CONFIG.organizationId)
  .replace("${visitorState}", JSON.stringify(offer.visitorState))
  .replace("${content}", offer.content);
 
  saveCookie(res, offer.targetCookie);
 
  res.status(200).send(result);
}
 
function sendErrorResponse(res, error) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  res.status(500).send(error);
}
 
app.get("/abtest", function (req, res) {
  const visitorCookieName = encodeURIComponent(MarketingCloudClient.getVisitorCookieName(CONFIG.organizationId));
  const visitorCookie = req.cookies[visitorCookieName];
  const targetCookieName = encodeURIComponent(MarketingCloudClient.getTargetCookieName());
  const targetCookie = req.cookies[targetCookieName];
  const payload = {"mbox" : "server-side-mbox"};
  const request = Object.assign({payload}, {targetCookie}, {visitorCookie});
 
  console.log("Request", request);
 
  marketingCloudClient.getOffer(request)
  .then(offer => {
    sendSuccessResponse(res, offer);
  })
  .catch(error => {
    sendErrorResponse(res, error);
  });
});
 
app.listen(3000, function () {
  console.log("Listening on port 3000 and watching!");
});

The biggest benefit of using the MCID integration is that it allows you to share Audience Manager segments with Target. Because this is a server-side integration for first-time visitors, you might not have any Audience Manager related data.

Full sample: https://github.com/Adobe-Marketing-Cloud/target-node-client-samples/tree/master/mcid-integration


MCID with Customer IDs Integration

Sometimes when you have logged details, you could be more specific and pass the logged details via customerIds. The customerIds object is similar to the MCID functionality described here: https://marketing.adobe.com/resources/help/en_US/mcvid/mcvid-authenticated-state.html.

Here is the Express application that shows customerIds in action:

const express = require("express");
const cookieParser = require("cookie-parser");
const MarketingCloudClient = require("@adobe/target-node-client");
const CONFIG = {
  client: "acmeclient",
  organizationId: "1234567890@AdobeOrg"
};
const TEMPLATE = `
<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Marketing Cloud Client NodeJS SDK Sample</title>
  <script src="VisitorAPI.js"></script>
  <script>
    Visitor.getInstance("${organizationId}", {serverState: ${visitorState}});
  </script>
</head>
<body>
  <p>${content}</p>
</body>
</html>
`;
const marketingCloudClient = MarketingCloudClient.create({config: CONFIG});
const app = express();
 
app.use(cookieParser());
// We assume that VisitorAPI.js is stored in "public" folder
app.use(express.static(__dirname + "/public"));
 
function saveCookie(res, cookie) {
  if (!cookie) {
    return;
  }
 
  res.cookie(cookie.name, cookie.value, {maxAge: cookie.maxAge * 1000});
}
 
function sendSuccessResponse(res, offer) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  const result = TEMPLATE
  .replace("${organizationId}", CONFIG.organizationId)
  .replace("${visitorState}", JSON.stringify(offer.visitorState))
  .replace("${content}", offer.content);
 
  saveCookie(res, offer.targetCookie);
 
  res.status(200).send(result);
}
 
function sendErrorResponse(res, error) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  res.status(500).send(error);
}
 
app.get("/abtest", function (req, res) {
  const visitorCookieName = encodeURIComponent(MarketingCloudClient.getVisitorCookieName(CONFIG.organizationId));
  const visitorCookie = req.cookies[visitorCookieName];
  const targetCookieName = encodeURIComponent(MarketingCloudClient.getTargetCookieName());
  const targetCookie = req.cookies[targetCookieName];
  const customerIds = {
    "userid": {
      "id": "67312378756723456",
      "authState": MarketingCloudClient.AuthState.AUTHENTICATED
    }
  };
  const payload = {
    "mbox" : 
    "server-side-mbox"
  };
  const request = Object.assign({customerIds}, {payload}, {targetCookie}, {visitorCookie});
 
  console.log("Request", request);
 
  marketingCloudClient.getOffer(request)
  .then(offer => {
    sendSuccessResponse(res, offer);
  })
  .catch(error => {
    sendErrorResponse(res, error);
  });
});
 
app.listen(3000, function () {
  console.log("Listening on port 3000 and watching!");
});

Full sample: https://github.com/Adobe-Marketing-Cloud/target-node-client-samples/tree/master/mcid-customer-ids-integration


MCID and Analytics Integration

To get the most out of the Marketing Cloud Client and to use the powerful analytics capabilities provided by Adobe Analytics, you can use the MCID, Analytics, and Target combo.

Here is a simple Express application that demonstrates how you can use all three solutions in a single application:

const express = require("express");
const cookieParser = require("cookie-parser");
const MarketingCloudClient = require("@adobe/target-node-client");
const CONFIG = {
  client: "acmeclient",
  organizationId: "1234567890@AdobeOrg"
};
const TEMPLATE = `
<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Marketing Cloud Client NodeJS SDK Sample</title>
  <script src="VisitorAPI.js"></script>
  <script>
    Visitor.getInstance("${organizationId}", {serverState: ${visitorState}});
  </script>
</head>
<body>
  <p>${content}</p>
  <script src="AppMeasurement.js"></script>
  <script>var s_code=s.t();if(s_code)document.write(s_code);</script>
</body>
</html>
`;
const marketingCloudClient = MarketingCloudClient.create({config: CONFIG});
const app = express();
 
app.use(cookieParser());
// We assume that VisitorAPI.js and AppMeasurement.js is stored in "public" folder
app.use(express.static(__dirname + "/public"));
 
function saveCookie(res, cookie) {
  if (!cookie) {
    return;
  }
 
  res.cookie(cookie.name, cookie.value, {maxAge: cookie.maxAge * 1000});
}
 
function sendSuccessResponse(res, offer) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  const result = TEMPLATE
  .replace("${organizationId}", CONFIG.organizationId)
  .replace("${visitorState}", JSON.stringify(offer.visitorState))
  .replace("${content}", offer.content);
 
  saveCookie(res, offer.targetCookie);
 
  res.status(200).send(result);
}
 
function sendErrorResponse(res, error) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  res.status(500).send(error);
}
 
app.get("/abtest", function (req, res) {
  const visitorCookieName = encodeURIComponent(MarketingCloudClient.getVisitorCookieName(CONFIG.organizationId));
  const visitorCookie = req.cookies[visitorCookieName];
  const targetCookieName = encodeURIComponent(MarketingCloudClient.getTargetCookieName());
  const targetCookie = req.cookies[targetCookieName];
  const payload = {"mbox" : "server-side-mbox"};
  const request = Object.assign({payload}, {targetCookie}, {visitorCookie});
 
  console.log("Request", request);
 
  marketingCloudClient.getOffer(request)
  .then(offer => {
    sendSuccessResponse(res, offer);
  })
  .catch(error => {
    sendErrorResponse(res, error);
  });
});
 
app.listen(3000, function () {
  console.log("Listening on port 3000 and watching!");
});

Using MCID, Analytics, and Target lets you:

  • Use segments from Audience Manager
  • Customize the user experience based on the content retrieved from Target
  • Ensure that all events and success metrics are collected in Analytics
  • Use Analytics' powerful queries and benefit from awesome visualizations

Full sample: https://github.com/Adobe-Marketing-Cloud/target-node-client-samples/tree/master/mcid-analytics-integration


MCID, Analytics, and at.js Integration

Most of the time the Marketing Cloud Client will be used in a NodeJS application, such as Express, Hapi, Koa, etc. However, with the recent proliferation of frameworks that allow server-side rendering (such as Facebook React or Angular 4.x), there are use cases where server-side should be aware and work in tandem with client-side libraries. In Target's case the client-side library is at.js.

The integration between server-side and client-side is also known as "hybrid" testing mode. The biggest challenge when trying to integrate server-side and client-side is to ensure that both server-side and client-side Target calls are hitting the same Target edge cluster. Otherwise you might end up with different user profiles being created by server-side and client-side calls.

To mitigate this situation, Target uses the so-called location hint cookie. To be able to use the location hint cookie you must add the following JavaScript to your HTML page before at.js or make sure that this code is executed before at.js, if you are using a tag manager such as Adobe Dynamic Tag Manager (DTM).

window.targetGlobalSettings = {
  overrideMboxEdgeServer: true
};

To see the the Target location hint cookie and at.js integration in action, here is a simple Express application:

const express = require("express");
const cookieParser = require("cookie-parser");
const MarketingCloudClient = require("@adobe/target-node-client");
const CONFIG = {
  client: "acmeclient",
  organizationId: "1234567890@AdobeOrg"
};
const TEMPLATE = `
<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Marketing Cloud Client NodeJS SDK Sample</title>
  <script src="VisitorAPI.js"></script>
  <script>
    Visitor.getInstance("${organizationId}", {serverState: ${visitorState}});
  </script>
  <script>
    window.targetGlobalSettings = {
      overrideMboxEdgeServer: true
    };
  </script>
  <script src="at.js"></script>
</head>
<body>
  <p>${content}</p>
  <script src="AppMeasurement.js"></script>
  <script>var s_code=s.t();if(s_code)document.write(s_code);</script>
</body>
</html>
`;
const marketingCloudClient = MarketingCloudClient.create({config: CONFIG});
const app = express();
 
app.use(cookieParser());
// We assume that VisitorAPI.js, at.js and AppMeasurement.js is stored in "public" folder
app.use(express.static(__dirname + "/public"));
 
function saveCookie(res, cookie) {
  if (!cookie) {
    return;
  }
 
  res.cookie(cookie.name, cookie.value, {maxAge: cookie.maxAge * 1000});
}
 
function sendSuccessResponse(res, offer) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  const result = TEMPLATE
  .replace("${organizationId}", CONFIG.organizationId)
  .replace("${visitorState}", JSON.stringify(offer.visitorState))
  .replace("${content}", offer.content);
 
  saveCookie(res, offer.targetCookie);
  saveCookie(res, offer.targetLocationHintCookie);
 
  res.status(200).send(result);
}
 
function sendErrorResponse(res, error) {
  res.set({
    "Content-Type": "text/html",
    "Expires": new Date().toUTCString()
  });
 
  res.status(500).send(error);
}
 
app.get("/abtest", function (req, res) {
  const visitorCookieName = encodeURIComponent(MarketingCloudClient.getVisitorCookieName(CONFIG.organizationId));
  const visitorCookie = req.cookies[visitorCookieName];
  const targetCookieName = encodeURIComponent(MarketingCloudClient.getTargetCookieName());
  const targetCookie = req.cookies[targetCookieName];
  const targetLocationHintCookieName = encodeURIComponent(MarketingCloudClient.getTargetLocationHintCookieName());
  const targetLocationHintCookie = req.cookies[targetLocationHintCookieName];
  const payload = {"mbox" : "server-side-mbox"};
  const request = Object.assign({payload}, {targetCookie}, {visitorCookie}, {targetLocationHintCookie});
 
  console.log("Request", request);
 
  marketingCloudClient.getOffer(request)
  .then(offer => {
    sendSuccessResponse(res, offer);
  })
  .catch(error => {
    sendErrorResponse(res, error);
  });
});
 
app.listen(3000, function () {
  console.log("Listening on port 3000 and watching!");
});

Using at.js integration allows use cases where a Target experience is started on the server-side and is continued on the client-side by at.js, also known as "hybrid" testing. The downside of this approach is that you might see some performance degradations when a NodeJS application that uses the Marketing Cloud Client is not geo distributed as Target edge clusters.

Full sample: https://github.com/Adobe-Marketing-Cloud/target-node-client-samples/tree/master/mcid-analytics-atjs-integration


Troubleshooting

The Marketing Cloud Client is a glorified HTTP/HTTPS client, so to understand what is happening on the wire, you can provide a logger object. The logger objects is expected to have a log() method that receives a list of parameters. The default logger has a noop log() implementation. To be able to inspect the HTTP request and response, you can provide a custom logger.

Here is an example that shows a logger that logs everything to console:

const fs = require("fs");
const express = require("express");
const cookieParser = require("cookie-parser");
const MarketingCloudClient = require("../lib/index");
 
const CONFIG = {
  client: "acmeclient",
  organizationId: "1234567890@AdobeOrg",
};
 
const logger = getLogger();
const marketingCloudClient = createMarketingCloudClient(logger, CONFIG);
 
function getLogger() {
  return {
    log: function(...arr) {
      console.log(...arr);
    }
  };
}
 
function createMarketingCloudClient(logger, config) {
  const options = Object.assign({logger}, {config});
 
  return MarketingCloudClient.create(options);
}
 
marketingCloudClient.getOffer({
  payload: {
    mbox : "some-mbox"
  }
})
.then(offer => console.log('Offer', offer))
.catch(error => console.error('Error', error));

If you want to use a more robust logger, you can always create a logger that delegates to winston, bunyan, or any other well-known NodeJS logging library.


Marketing Cloud Client API

MarketingCloudClient.create(options: Object): MarketingCloudClient creates an instance of the Marketing Cloud Client.

The options object has the following structure:

Name Type Required Default Description
config Object Yes None General config
logger Object No NOOP Logger to be used

The config object should have the following structure:

Name Type Required Default Description
client String Yes None Target client
organizationId String Yes None Organization ID
timeout Number No None Target request timeout in milliseconds
secure Boolean No true Target request over HTTP or HTTPS

MarketingCloudClient.getVisitorCookieName(organizationId: string): string is used to retrieve the MCID cookie name.

MarketingCloudClient.getTargetCookieName(): string is used to retrieve the Target cookie name.

MarketingCloudClient.getTargetLocationHintCookieName(): string is used to retrieve the Target location hint cookie name.

MarketingCloudClient.getOffer(request: Object): Promise is used to fetch an offer from Target.

The request object has the following structure:

Name Type Required Default Description
payload Object Yes None Server-Side Delivery API payload
targetCookie String No None Target cookie
targetLocationHintCookie String No None Target location hint cookie
visitorCookie String No None Visitor cookie

To learn more about the Target Server-Side Delivery API, see http://developers.adobetarget.com/api/#server-side-delivery

The promise returned by MarketingCloudClient.getOffer(...) wraps an offer.

The offer object has the following structure:

Name Type Description
targetCookie Object Target cookie
targetLocationHintCookie Object Target location hint cookie
visitorState Object Object that should be passed to Visitor API getInstance()
content String or Object Personalized content, can be string or object

The cookie object used for passing data back to the browser has the following structure:

Name Type Description
name String Cookie name
value Any Cookie value, the value will converted to string
maxAge Number The maxAge option is a convenience option for setting expires relative to the current time in seconds

back to top