Duda Analytics: Site-Wide Scripts | OpsBlu Docs

Duda Analytics: Site-Wide Scripts

Implement analytics on Duda websites. Covers site-wide and page-level script injection, DudaOne widget data layers, multi-site analytics management,...

Analytics Architecture on Duda

Duda is a SaaS website builder focused on agencies and multi-site management. Analytics tracking integrates through three mechanisms:

  • Site-wide HTML/JS injection in Duda's site settings adds scripts to the head or body of every page. This is the primary method for GTM and GA4 installation
  • Page-level code injection through the page settings panel adds scripts to individual pages for page-specific tracking
  • Custom widgets built with Duda's Widget Builder can include their own JavaScript with access to page context and widget data, enabling component-level tracking
  • Duda's native analytics provides built-in traffic reports (page views, visitors, referral sources) that run independently of any external analytics tool

Duda renders pages server-side and serves them through its CDN. Pages are standard HTML with JavaScript hydration for interactive elements. Unlike SPA frameworks, Duda page navigations are full page loads, so standard analytics page view tracking works without virtual page view workarounds.

For agencies managing multiple Duda sites, the platform supports site templates with pre-configured analytics scripts. Set up GTM in the template once, and every site created from that template inherits the tracking configuration.


Installing Tracking Scripts

Add tracking scripts through Duda's site settings:

  1. Open the site in the Duda editor
  2. Navigate to Site Settings > Head HTML or Body End HTML
  3. Paste your tracking snippet

For GTM, add the head snippet to Head HTML:

<!-- GTM Head - Duda Site Settings > Head HTML -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>

Add the noscript fallback to Body End HTML:

<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>

Page-Level Scripts

For page-specific tracking (landing page pixels, event-specific scripts):

  1. Select the page in the editor's page panel
  2. Open Page Settings > SEO & Social > Custom Code
  3. Add scripts to the head or body section

Page-level scripts load only on that specific page, making them useful for conversion tracking on thank-you pages or form confirmation pages.

Via Duda API (Multi-Site Management)

Agencies managing many Duda sites can inject scripts programmatically through the Duda API:

// Add GTM to a Duda site via API
const response = await fetch(
  `https://api.duda.co/api/sites/multiscreen/${siteName}/inject-code`,
  {
    method: 'POST',
    headers: {
      'Authorization': 'Basic ' + btoa(apiUser + ':' + apiPass),
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      head_html: '<script>/* GTM snippet */</script>',
      body_end_html: '<noscript>/* GTM noscript */</noscript>'
    })
  }
);

This enables bulk analytics deployment across hundreds of client sites from a single script.


Data Layer Setup

Duda pages expose metadata through the page DOM and Duda's JavaScript environment. Build a data layer by reading page properties:

<!-- Site Settings > Head HTML (after GTM script) -->
<script>
  window.dataLayer = window.dataLayer || [];

  // Duda exposes page data through DOM meta tags and data attributes
  var pageTitle = document.title;
  var pageUrl = window.location.pathname;
  var pageLang = document.documentElement.lang || 'en';

  dataLayer.push({
    'page_title': pageTitle,
    'page_path': pageUrl,
    'page_language': pageLang,
    'site_platform': 'duda'
  });
</script>

Form Submission Tracking

Duda forms use a built-in form system. Track submissions by listening for the form's success callback:

<!-- Site Settings > Body End HTML -->
<script>
  // Listen for Duda form submissions
  document.addEventListener('submit', function(e) {
    var form = e.target;
    if (form.classList.contains('dm-form') || form.closest('.dm-form')) {
      window.dataLayer = window.dataLayer || [];
      dataLayer.push({
        'event': 'form_submit',
        'form_id': form.id || 'duda_form',
        'form_action': form.action || window.location.pathname
      });
    }
  });

  // Alternative: Listen for Duda's AJAX form success
  var originalFetch = window.fetch;
  window.fetch = function() {
    return originalFetch.apply(this, arguments).then(function(response) {
      if (arguments[0] && String(arguments[0]).includes('/form/')) {
        window.dataLayer = window.dataLayer || [];
        dataLayer.push({ 'event': 'duda_form_success' });
      }
      return response;
    });
  };
</script>

Ecommerce Tracking

Duda's built-in ecommerce (Duda Ecommerce) supports online stores with product pages, cart, and checkout. Track ecommerce events by hooking into the store's DOM and JavaScript events:

<!-- Site Settings > Body End HTML -->
<script>
  // Track add-to-cart clicks
  document.addEventListener('click', function(e) {
    var addToCartBtn = e.target.closest('[data-action="add-to-cart"], .add-to-cart-btn');
    if (addToCartBtn) {
      var productEl = addToCartBtn.closest('[data-product-id]');
      if (productEl) {
        window.dataLayer = window.dataLayer || [];
        dataLayer.push({ ecommerce: null });
        dataLayer.push({
          'event': 'add_to_cart',
          'ecommerce': {
            'items': [{
              'item_id': productEl.dataset.productId || '',
              'item_name': productEl.querySelector('.product-title')?.textContent?.trim() || '',
              'price': parseFloat(productEl.querySelector('.product-price')?.textContent?.replace(/[^0-9.]/g, '')) || 0
            }]
          }
        });
      }
    }
  });
</script>

For purchase tracking on the order confirmation page, use a page-level script on the thank-you page that reads order data from the URL parameters or page content.


Multi-Site Analytics Strategy

Duda's agency model means a single team often manages analytics for dozens or hundreds of sites. Strategies for scale:

  • Template-based GTM: Create a Duda site template with GTM pre-configured. All sites created from the template inherit the container. Use GTM's lookup table variables to load site-specific GA4 Measurement IDs based on the hostname
  • Single GTM container: Use one GTM container across all client sites with hostname-based triggers and variables. This centralizes tag management but requires careful trigger scoping
  • Per-client containers: Create separate GTM containers for each client. Deploy via the Duda API to each site. This provides isolation but increases management overhead
  • Duda API bulk operations: Use the Sites API to audit which sites have analytics installed and which are missing scripts
// GTM Lookup Table variable for multi-site GA4 IDs
// Variable name: GA4 Measurement ID
// Input: {{Page Hostname}}
// Lookup table:
// client1.com → G-CLIENT1XX
// client2.com → G-CLIENT2XX
// Default → G-DEFAULTXX

Personalization and Dynamic Content

Duda supports content personalization based on visitor attributes (location, device, time of day, visit count). Track which personalization rule fired:

<script>
  // Duda sets personalization data on the page
  // Track the active rule for analytics segmentation
  window.addEventListener('load', function() {
    var personalizedElements = document.querySelectorAll('[data-personalization-rule]');
    personalizedElements.forEach(function(el) {
      if (el.offsetParent !== null) { // Element is visible
        window.dataLayer = window.dataLayer || [];
        dataLayer.push({
          'event': 'personalization_shown',
          'personalization_rule': el.dataset.personalizationRule,
          'personalization_type': el.dataset.personalizationType || 'unknown'
        });
      }
    });
  });
</script>

Common Errors

Error Cause Fix
Scripts not loading after publish Changes made in editor but site not republished Click Publish in the Duda editor to push code changes to the live site
GTM fires but GA4 shows no data GA4 Measurement ID wrong or tag paused in GTM Verify the Measurement ID in GTM and check tag status is not paused
Form submissions not tracked Duda forms use AJAX submission, not traditional form post Listen for DOM changes or intercept fetch calls to the form endpoint
Duplicate page views Both Duda's native analytics and GA4 count views This is expected -- they are independent systems. Only fix if GA4 fires twice
Scripts removed after template update Site was regenerated from an updated template without custom code Re-inject scripts via API or add them to the template's default code
Multi-site scripts inconsistent Manual script injection varies across sites Use the Duda API to audit and standardize scripts across all sites
Ecommerce data missing product details DOM selectors changed after a Duda platform update Inspect the live page to update selectors; use data-* attributes when available
Slow page load from third-party scripts Too many analytics and marketing pixels Audit total script weight with Chrome DevTools; consolidate through GTM
Scripts in editor preview fire events Duda's preview mode runs injected scripts Check for duda_preview URL parameter or editor referrer before tracking
Cross-domain tracking broken Client site uses Duda subdomain for some pages Configure GA4 linker to include both the custom domain and the Duda subdomain

Performance Considerations

  • CDN delivery: Duda serves all pages through its CDN with automatic caching. Injected scripts are included in the cached HTML, adding no extra round-trips
  • Script placement: Use Body End HTML for analytics scripts that do not need to fire before page render. Only the GTM head snippet needs to be in Head HTML
  • Duda's native analytics: Runs independently and cannot be disabled. Its tracking script is lightweight (~5KB) and does not significantly impact page performance
  • Image optimization: Duda automatically resizes and compresses images. Use Duda's built-in image component rather than custom HTML images to benefit from the optimization pipeline
  • Widget JavaScript: Custom widgets with heavy JavaScript impact page load. Keep analytics code in site-wide injection rather than embedding it in multiple widgets
  • Lazy loading: Duda lazy-loads images and widgets below the fold by default. Verify that analytics tracking for below-fold content uses scroll-based triggers rather than page load events