Initializing CMP with the Stub Script and cmpapi.js - createIT
Get a free advice now!

    Pick the topic
    Developer OutsourcingWeb developingApp developingDigital MarketingeCommerce systemseEntertainment systems

    Thank you for your message. It has been sent.

    Initializing CMP with the Stub Script and cmpapi.js

    November 29, 2023
    Last update: April 4, 2024
    7 min read
    26
    0
    0
    Initializing CMP with the Stub Script and cmpapi.js

    Challenge: Ensuring compliant user consent management

    Solution: Utilizing the CMP stub script and cmpapi.js for accurate consent signal capturing

    The Interactive Advertising Bureau (IAB) Transparency and Consent Framework (TCF) has become a pivotal standard in the digital advertising industry, ensuring user privacy and consent management across websites and applications. The release of TCF v2.2 has further solidified its position, introducing significant updates and improvements. This guide aims to walk developers through the initial setup and configuration of a Consent Management Platform (CMP) in alignment with TCF v2.2.

    Understanding CMP and IAB TCF 2.2

    The TCF v2.2 update

    Enhanced clarity in purpose descriptions

    The IAB’s Transparency and Consent Framework (TCF) version 2.2 brings a significant update in clarity with revised naming and descriptions of data processing purposes. This ensures that users are provided clear and understandable information, empowering them to make well-informed decisions regarding their personal data.

    Code fragments with notes

    Introduction of retention periods

    A major addition in TCF 2.2 is the introduction of retention periods for all data processing purposes. This development underscores the importance of data minimization and adhering to privacy best practices, ensuring that user data is not stored for longer than necessary.

    Code fragments

    Changes in legitimate interest

    The framework has modified the use of legitimate interest as a legal basis for data processing, specifically removing it for purposes 3 to 6. This change highlights a shift towards obtaining explicit user consent for these particular data processing activities.

    Granular control with data categories

    TCF 2.2 enhances user control by associating specific data categories with each processing purpose. This addition aims to increase transparency and provide users with a better understanding of how their data is being utilized.

    Support for legitimate interest claims

    The update introduces legitimate interest claim URLs, offering users additional resources to understand a vendor’s basis for data processing. This feature plays a crucial role in aiding users to make informed decisions about their data.

    Localized policy URLs

    To cater to a global audience, TCF 2.2 includes support for localized policy URLs, ensuring that privacy information is accessible in various languages. This enhances user accessibility and comprehension across different regions.

    Code fragments

    Disclosure of vendor numbers

    In the spirit of transparency, CMPs are now required to disclose the number of vendors/partners that will process user data, adding an extra layer of clarity to the consent process. This move is designed to help users grasp the extent of their consent, potentially influencing their decisions regarding data sharing.

    gray and orange buttons and text

    Greater specificity in vendor data processing

    Vendors are now obliged to provide additional specifics about their data processing practices, including detailed information on the purposes of processing and any potential data sharing. This change enhances vendor accountability and ensures a higher degree of transparency regarding their data processing activities.

    Technical advancements

    On the technical front, the update deprecates the __tcfapi command “getTCData” in favor of more robust and comprehensive API commands. This transition reflects a commitment to providing enhanced functionality and better alignment with the updated framework.

    Robust vendor compliance

    Lastly, TCF 2.2 introduces a more stringent vendor compliance program, ensuring that all parties in the digital advertising ecosystem adhere to TCF standards and respect user choices. This leads to greater accountability and trust within the industry.

    Facilitating user consent

    In your role as a Consent Management Platform (CMP), you play a crucial part in gathering, storing, and sharing user consent preferences in line with the IAB’s Transparency and Consent Framework (TCF). Your actions ensure that user data is handled transparently and in accordance with their choices.

    Collecting user consent

    Your first responsibility is to collect user consent in a manner that complies fully with TCF Technical Specifications and Policy. This means providing clear and transparent information about the data processing activities the user is consenting to, and ensuring they can easily accept or reject specific types of data processing. Aim to create a user-friendly experience that encourages engagement and understanding, steering clear of any coercive tactics.

    Generating an encoded TC String

    Next, you’ll need to generate an encoded TC String, a Base64 string that encapsulates the user’s consent preferences. This string should include details about the CMP, the user’s consent choices, the vendors and purposes consented to, and other pertinent information. Ensure that the TC String is both accurate and promptly updated whenever the user changes their consent preferences.

    Sharing the TC String with Vendors

    Finally, share the TC String with vendors and other entities in the advertising ecosystem, utilizing available APIs. This is a vital step to ensure that the user’s consent preferences are respected throughout the ad delivery process.

    Setting up the stub script for CMP initialization

    Ensuring early consent signal capturing

    The stub script is integral to the Consent Management Platform (CMP), acting as a preliminary placeholder to capture consent signals even before the full CMP is loaded. Placing this script in the head of your HTML ensures it runs promptly, maintaining compliance and user trust.

    import * as cmpstub from '@iabtechlabtcf/stub';
    cmpstub();

    Integrating and configuring cmpapi.js

    Establishing communication with vendors

    The cmpapi.js script is crucial for creating an API bridge between the CMP and vendors, ensuring that the user’s consent preferences are accurately communicated and respected.

    import { CmpApi } from '@iabtechlabtcf/cmpapi';
    const cmpApi = new CmpApi(CMP_ID, CMP_VERSION, true);

    Configuring and initializing the CMP API

    Include and configure cmpapi.js in your project, ensuring it’s properly initialized with the necessary parameters like CMP ID and version. This setup guarantees that the script can communicate correctly with your CMP and that consent values are accurately set and retrieved.

    Webpack configuration for static IAB Tech Lab TCF library

    Leveraging Webpack for efficient compilation

    Webpack is utilized here to compile and bundle the IAB Tech Lab TCF library, making it ready for deployment. This configuration ensures that all necessary files and dependencies are included and processed correctly.

    "scripts": {
      "build": "webpack --mode production",
      "watch": "webpack --watch --mode development"
    },
    "dependencies": {
      "@iabtechlabtcf/cmpapi": "^1.5.9",
      "@iabtechlabtcf/core": "^1.5.9",
      "@iabtechlabtcf/stub": "^1.5.9"
    },
    "devDependencies": {
      "@babel/core": "^7.22.17",
      "@babel/preset-env": "^7.22.15",
      "babel-loader": "^9.1.3",
      "css-loader": "^6.8.1",
      "html-webpack-plugin": "^5.5.3",
      "style-loader": "^3.3.3",
      "webpack": "^5.88.2",
      "webpack-cli": "^5.1.4"
    }

    Configuring loaders and plugins

    Specify loaders to handle JavaScript and CSS files, and use plugins like the HtmlWebpackPlugin to manage HTML files. This ensures that all assets are processed and bundled correctly.

    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: './src/index.js', // Your source JS file
      output: {
          filename: 'bundle.js',
          path: __dirname + '/dist',
      },
      module: {
        rules: [
          // JavaScript Loader
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env']
              }
            }
          },
          // CSS Loader
          {
            test: /\.css$/,
            use: ['style-loader', 'css-loader'],
          },
        ]
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: './src/index.html',
        }),
      ],
    };

    Integrating with Klaro and IAB Tech Lab libraries

    The code integrates Klaro for consent management, alongside IAB Tech Lab libraries for handling TCF-specific logic. This combination ensures compliance with industry standards while providing a user-friendly consent interface.

    import * as Klaro from './../klaro/dist/klaro.js';
    import { TCModel, TCString, GVL } from '@iabtechlabtcf/core';

    Setting up constants and initial configurations

    Constants are defined for various configuration values, and initial setups for the GVL and TCModel are performed to prepare for user consent processing.

    const GVL_BASE_URL = 'https://www.example.com/tcf/';
    const GVL_LATEST_FILENAME = 'vendor-list.json?v=22';
    const CMP_ID = 999;
    const CMP_VERSION = 1500;
    const KLARO_DATA_PREFIXES = {
      've': 'vendorConsents',
      'veli': 'vendorLiConsents',
      'pu': 'purposeConsents',
      'spfu': 'specialFeatureOptins'
    };
    
    GVL.baseUrl = GVL_BASE_URL;
    GVL.latestFilename = GVL_LATEST_FILENAME;
    const tcModel = new TCModel(new GVL("LATEST"));
    tcModel.isServiceSpecific = true;

    Handling user consent and communicating with the CMP API

    The code listens for DOM content to be loaded, and then interacts with Klaro to manage user consents, translating them into the TCF format and updating the CMP API accordingly.

    document.addEventListener('DOMContentLoaded', function() {
      if (!Klaro) return;
      
      const manager = Klaro.getManager(klaroConfig);
      const klaroData = { consents: manager.loadConsents() };
      ctSetupTCModel(ctConstructMyData(klaroData));
      
      manager.watch({
        update(_, eventName, klaroData) {
          if (eventName === 'saveConsents') {
            const myData = ctConstructMyData(klaroData);
            ctSetupTCModel(myData);
          }
        }
      });
    });

    Generating and transmitting the TC String

    With the user’s preferences now captured in the TC Model, a TC String is generated. This string is a compact, encoded representation of the user’s consent preferences.

    const encodedTCString = TCString.encode(tcModel);
    cmpApi.update(encodedTCString, true);

    This TC String is then transmitted to vendors and other parties in the advertising ecosystem via the CMP API, ensuring that the user’s choices are respected throughout the entire ad delivery process.

    Webpack compilation result

    Output File:

    The bundled JavaScript file, specified in the Webpack configuration’s output section, will be named bundle.js and located in the dist directory of your project.

    output: {
      filename: 'bundle.js',
      path: __dirname + '/dist',
    }

    This file will include:

    – Your source JavaScript code (e.g., CMP logic, consent handling).

    – The cmpapi.js script and other IAB Tech Lab TCF libraries.

    – Any additional dependencies or modules imported in your source code.

    – The contents of custom.css, as it’s imported and processed by Webpack.

    Running Webpack commands

    You can run the following npm scripts defined in your package.json to compile your project:

    Production build:

    npm run build

    This command runs Webpack in production mode, optimizing the output for production deployment.

    Development build and watch:

    npm run watch

    This command runs Webpack in development mode and watches for any changes in your source files, recompiling the bundle as necessary. This is useful during development to see changes in real-time.

    Including the bundled file in your web application

    Once Webpack has compiled your code and generated the bundle.js file, you need to include it in your web application.

    Enqueue the script in your HTML file: Include a script tag in your HTML file to load the bundled JavaScript file. This should be placed near the top of the head section to ensure early initialization.

    <script src="path/to/your/dist/bundle.js"></script>

    Meeting TCF 2.2 requirements before the deadline

    The online privacy landscape is continuously evolving, requiring publishers and businesses to stay vigilant and compliant with the latest standards. The Transparency and Consent Framework (TCF) 2.2, introduced on May 16, 2023, marks a significant step in this direction, enhancing user experiences and data management practices.

    Understanding the challenges that come with adapting to new standards, IAB Europe has extended the deadline for implementing TCF 2.2 to November 20, 2023. This extension provides publishers with additional time to align their operations with the new requirements and ensure a seamless transition.

    Mastering CMP and IAB TCF: a developer’s guide

    Through these integrations and logic implementations, the CMP accurately represents user consents and communicates them to the CMP API, ensuring that user preferences are respected and that the system operates in full compliance with the IAB TCF standards.

    This article is the 1 part of the series “Mastering CMP and IAB TCF: A Developer’s Guide”. Stay tuned for more in-depth discussions and guides on implementing and optimizing your Consent Management Platform in accordance with the IAB’s Transparency and Consent Framework.

    If you are looking for talented developers, do not hesitate to contact us.

    Purchase the most popular GDPR WordPress plugin tailored to Google Consent Mode v2. Remember to use only certified solutions. You can also find our GDPR & CCPA WordPress plugin on Codecanyon

    Support – Tips and Tricks
    All tips in one place, and the database keeps growing. Stay up to date and optimize your work!

    Contact us