MediaMath Data Layer Setup | OpsBlu Docs

MediaMath Data Layer Setup

Configure data layer structure for MediaMath pixel tracking and dynamic retargeting.

Data Layer Overview

A properly structured data layer enables dynamic MediaMath pixel firing with accurate product, conversion, and audience data. This is essential for programmatic campaigns, dynamic retargeting, and conversion optimization through TerminalOne.

Base Data Layer Structure

Initialize Before Pixels

Place this code before MediaMath pixel implementation:

window.mediamath = window.mediamath || {};
window.mediamath.dataLayer = window.mediamath.dataLayer || {
  page: {},
  user: {},
  product: {},
  transaction: {}
};

Page-Level Data

Set on all pages:

window.mediamath.dataLayer.page = {
  type: 'homepage', // homepage, product, category, cart, checkout, confirmation
  category: 'electronics',
  url: window.location.href,
  referrer: document.referrer
};

E-commerce Data Layer

Product Detail Page

window.mediamath.dataLayer.product = {
  id: 'SKU_12345',
  name: 'Blue Widget',
  category: 'widgets',
  subcategory: 'blue_widgets',
  price: 49.99,
  currency: 'USD',
  availability: 'in_stock',
  brand: 'WidgetCo',
  image: 'https://example.com/images/product.jpg',
  url: 'https://example.com/products/blue-widget'
};

// Fire MediaMath product view pixel
fireMediaMathProductPixel(window.mediamath.dataLayer.product);

Shopping Cart

window.mediamath.dataLayer.cart = {
  items: [
    {
      id: 'SKU_12345',
      name: 'Blue Widget',
      price: 49.99,
      quantity: 2,
      category: 'widgets'
    },
    {
      id: 'SKU_67890',
      name: 'Red Widget',
      price: 59.99,
      quantity: 1,
      category: 'widgets'
    }
  ],
  subtotal: 159.97,
  tax: 12.00,
  shipping: 5.00,
  total: 176.97,
  currency: 'USD'
};

Purchase / Conversion

window.mediamath.dataLayer.transaction = {
  id: 'ORDER_12345',
  affiliation: 'Online Store',
  revenue: 176.97,
  tax: 12.00,
  shipping: 5.00,
  currency: 'USD',
  items: [
    {
      id: 'SKU_12345',
      name: 'Blue Widget',
      category: 'widgets',
      price: 49.99,
      quantity: 2
    },
    {
      id: 'SKU_67890',
      name: 'Red Widget',
      category: 'widgets',
      price: 59.99,
      quantity: 1
    }
  ]
};

// Fire MediaMath conversion pixel
fireMediaMathConversionPixel(window.mediamath.dataLayer.transaction);

Lead Generation Data Layer

Form Start

window.mediamath.dataLayer.form = {
  event: 'form_start',
  name: 'contact_form',
  type: 'lead_generation',
  location: 'homepage',
  timestamp: new Date().toISOString()
};

Form Submit

window.mediamath.dataLayer.form = {
  event: 'form_submit',
  name: 'contact_form',
  type: 'lead_generation',
  leadValue: 50.00,
  category: 'sales_inquiry',
  timestamp: new Date().toISOString()
};

// Fire MediaMath lead pixel
fireMediaMathLeadPixel(window.mediamath.dataLayer.form);

User Data Layer

User Properties

window.mediamath.dataLayer.user = {
  id: 'USER_12345',
  status: 'logged_in', // logged_in, logged_out, new_visitor
  segment: 'high_value', // high_value, medium_value, low_value
  lifetimeValue: 499.95,
  orderCount: 3,
  lastPurchaseDate: '2024-01-15'
};

Audience Segmentation

window.mediamath.dataLayer.audience = {
  segment: 'cart_abandoner',
  productInterest: ['widgets', 'gadgets'],
  priceRange: '50-100',
  previousVisits: 5,
  daysSinceLastVisit: 3
};

Dynamic Retargeting Data Layer

Product Feed Format

window.mediamath.dataLayer.productFeed = {
  products: [
    {
      id: 'SKU_12345',
      name: 'Blue Widget',
      description: 'A high-quality blue widget',
      category: 'widgets > blue',
      price: 49.99,
      salePrice: 39.99,
      currency: 'USD',
      availability: 'in_stock',
      brand: 'WidgetCo',
      imageUrl: 'https://example.com/images/product.jpg',
      productUrl: 'https://example.com/products/blue-widget',
      condition: 'new'
    }
  ]
};

Helper Functions

Fire MediaMath Pixel with Data Layer

function fireMediaMathPixel(pixelId, dataLayerObject) {
  var mtm = document.createElement('script');
  mtm.type = 'text/javascript';
  mtm.async = true;

  // Extract values from data layer
  var v1 = dataLayerObject.v1 || '';
  var v2 = dataLayerObject.v2 || '';
  var v3 = dataLayerObject.v3 || '';
  var s1 = dataLayerObject.s1 || '';
  var s2 = dataLayerObject.s2 || '';
  var s3 = dataLayerObject.s3 || '';

  var pixelUrl = 'https://pixel.mathtag.com/event/js?' +
    'mt_id=' + encodeURIComponent('ADVERTISER_ID') +
    '&mt_adid=' + encodeURIComponent(pixelId) +
    '&mt_exem=' +
    '&mt_excl=' +
    '&v1=' + encodeURIComponent(v1) +
    '&v2=' + encodeURIComponent(v2) +
    '&v3=' + encodeURIComponent(v3) +
    '&s1=' + encodeURIComponent(s1) +
    '&s2=' + encodeURIComponent(s2) +
    '&s3=' + encodeURIComponent(s3);

  mtm.src = pixelUrl;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(mtm, s);
}

Product View Pixel

function fireMediaMathProductPixel(product) {
  fireMediaMathPixel('PRODUCT_VIEW_PIXEL_ID', {
    v1: product.id,
    v2: product.price,
    v3: product.category,
    s1: product.name,
    s2: product.image,
    s3: product.url
  });
}

Conversion Pixel

function fireMediaMathConversionPixel(transaction) {
  fireMediaMathPixel('CONVERSION_PIXEL_ID', {
    v1: transaction.revenue,
    v2: transaction.id,
    v3: transaction.currency,
    s1: '',
    s2: '',
    s3: ''
  });
}

Lead Pixel

function fireMediaMathLeadPixel(form) {
  fireMediaMathPixel('LEAD_PIXEL_ID', {
    v1: form.leadValue,
    v2: form.name,
    v3: form.category,
    s1: '',
    s2: '',
    s3: ''
  });
}

GTM Data Layer Integration

Google Tag Manager Variables

Create these Data Layer Variables in GTM:

  • MM - Product ID: mediamath.dataLayer.product.id
  • MM - Product Price: mediamath.dataLayer.product.price
  • MM - Product Category: mediamath.dataLayer.product.category
  • MM - Product Name: mediamath.dataLayer.product.name
  • MM - Product Image: mediamath.dataLayer.product.image
  • MM - Product URL: mediamath.dataLayer.product.url
  • MM - Transaction Value: mediamath.dataLayer.transaction.revenue
  • MM - Transaction ID: mediamath.dataLayer.transaction.id
  • MM - Currency: mediamath.dataLayer.transaction.currency

Use in MediaMath Tags

<script type="text/javascript">
  (function() {
    var mtm = document.createElement('script');
    mtm.type = 'text/javascript';
    mtm.async = true;
    mtm.src = 'https://pixel.mathtag.com/event/js?' +
      'mt_id={{MM Advertiser ID}}' +
      '&mt_adid={{MM Pixel ID}}' +
      '&mt_exem=' +
      '&mt_excl=' +
      '&v1={{MM - Product ID}}' +
      '&v2={{MM - Product Price}}' +
      '&v3={{MM - Product Category}}' +
      '&s1={{MM - Product Name}}' +
      '&s2={{MM - Product Image}}' +
      '&s3={{MM - Product URL}}';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(mtm, s);
  })();
</script>

Server-Side Data Layer

Node.js Example

const express = require('express');
const app = express();

// Middleware to build data layer
app.use((req, res, next) => {
  res.locals.mediamathDataLayer = {
    page: {
      type: req.path === '/' ? 'homepage' : 'other',
      url: req.protocol + '://' + req.get('host') + req.originalUrl
    },
    user: {
      id: req.session?.userId || null,
      status: req.session?.userId ? 'logged_in' : 'logged_out'
    }
  };
  next();
});

// Product page
app.get('/products/:id', async (req, res) => {
  const product = await getProduct(req.params.id);

  res.locals.mediamathDataLayer.product = {
    id: product.sku,
    name: product.name,
    price: product.price,
    category: product.category
  };

  res.render('product', {
    product: product,
    dataLayer: res.locals.mediamathDataLayer
  });
});

Render in Template

<script>
  window.mediamath = window.mediamath || {};
  window.mediamath.dataLayer = {{{json dataLayer}}};
</script>

Testing Data Layer

Console Validation

// Check data layer structure
console.log('MediaMath Data Layer:', window.mediamath.dataLayer);

// Validate product data
function validateProductData(product) {
  const required = ['id', 'name', 'price', 'category'];
  const missing = required.filter(field => !product[field]);

  if (missing.length > 0) {
    console.error('Missing required fields:', missing);
    return false;
  }

  console.log('✓ Product data valid');
  return true;
}

// Run validation
if (window.mediamath.dataLayer.product) {
  validateProductData(window.mediamath.dataLayer.product);
}

GTM Preview Mode

  1. Enable GTM Preview mode
  2. Navigate through site
  3. Check "Data Layer" tab
  4. Verify mediamath.dataLayer object
  5. Confirm variables populate correctly

Best Practices

  • Initialize data layer before any MediaMath pixels load
  • Use consistent naming conventions (camelCase)
  • Validate required fields before pixel fires
  • Clear data layer between page transitions in SPAs:
// Clear product data on page change
window.mediamath.dataLayer.product = {};
  • Encode special characters in data layer values
  • Document data layer schema for developers
  • Implement server-side data layer for SSR applications
  • Use GTM variables for centralized data layer access
  • Test data layer in staging before production
  • Monitor data quality with server-side validation