# Google Tag Manager

> Add Databuddy analytics through Google Tag Manager


import { Card, Cards } from "@/components/docs";

Load Databuddy through a GTM Custom HTML tag and send application events from your data layer.

> TL;DR: In GTM, create a Custom HTML tag with an inline loader that appends `https://cdn.databuddy.cc/databuddy.js` and sets `data-client-id`. Enable optional flags such as `data-track-attributes` or `data-track-errors`. Page views and sessions are automatic. Choose a page or consent-granted trigger that matches your privacy configuration, then preview and publish.

## Basic Setup

### Step 1: Create Databuddy Tag

1. In GTM, click **Add a new tag**
2. Choose **Custom HTML** as the tag type
3. Add the Databuddy script:

This loader sets the tracker attributes before loading the script and signals when it is ready:

```html
<script>
  (function () {
    var el = document.createElement("script");
    el.src = "https://cdn.databuddy.cc/databuddy.js";
    el.async = true;
    el.crossOrigin = "anonymous";
    el.setAttribute("data-client-id", "{{Databuddy Client ID}}");
    el.setAttribute("data-track-attributes", "true");
    el.setAttribute("data-track-errors", "true");
    el.onload = function () {
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ event: 'databuddy_ready' });
    };
    el.onerror = function () {
      console.warn('Databuddy script failed to load');
    };
    document.head.appendChild(el);
  })();
</script>
```

4. Name your tag "Databuddy - Analytics Script"

### Step 2: Create Variables

Create a **Constant** variable for your Client ID:

1. Go to **Variables** > **User-Defined Variables**
2. Click **New** > **Constant**
3. Name: "Databuddy Client ID"
4. Value: Your actual Client ID from Databuddy dashboard

### Step 3: Set Trigger

1. In your Databuddy tag, click **Triggering**
2. Choose **All Pages**, or your consent manager’s granted trigger when prior consent is required
3. Under **Advanced Settings > Tag firing options**, choose **Once per page**
4. Save the tag

### Step 4: Publish

1. Click **Submit** to create a version
2. Add version name and description
3. Click **Publish**

## Advanced Configuration

Reuse the loader above for each configuration:

- **Environments:** make `Databuddy Client ID` a Lookup Table variable keyed by `Page Hostname`. Map every hostname where the tag can fire to its registered site's Client ID, including staging or preview hosts used for testing. Add a trigger condition that permits only mapped hostnames; do not fire the tag on an unmatched host with an empty or unresolved Client ID.
- **Internal traffic:** add a trigger condition or exception using your internal-traffic variable.
- **Optional tracking:** change the `data-*` attributes before `appendChild()`. See the [configuration reference](/docs/sdk/configuration).

Keep the `onload` callback so tags waiting for `databuddy_ready` can fire. Use the loader once per page; automatic pageview tracking already handles SPA navigation.

## Event Tracking Setup

### Custom Event Tags

The loader above emits `databuddy_ready` after the script finishes loading. For startup events, use a Custom Event trigger named `databuddy_ready`. For purchase and other application events, dispatch them after readiness or buffer them in your application until then. The examples below do not queue early events. GTM tag sequencing alone does not wait for an asynchronously injected script.

Create tags for specific events:

**E-commerce Purchase Tag:**

Create Data Layer Variables for the values you need (e.g. `Transaction ID`, `Purchase Revenue`, `Currency`, `Items Count`), then fire this tag on your purchase event trigger:

```html
<script>
  if (window.databuddy) {
    databuddy.track('purchase', {
      transaction_id: '{{Transaction ID}}',
      value: {{Purchase Revenue}},
      currency: '{{Currency}}',
      item_count: {{Items Count}}
    });
  }
</script>
```

**Form Submission Tag:**

```html
<script>
  if (window.databuddy) {
    databuddy.track('form_submit', {
      form_id: '{{Form ID}}',
      form_name: '{{Form Name}}',
      form_location: '{{Page Path}}'
    });
  }
</script>
```

### Data Layer Integration

Send GTM data layer events to Databuddy:

```html
<script>
  if (window.databuddy) {
    databuddy.track('{{Event}}', {
      category: '{{Event Category}}',
      action: '{{Event Action}}',
      label: '{{Event Label}}',
      value: {{Event Value}},
      custom_parameter: '{{Custom Parameter}}'
    });
  }
</script>
```

## Triggers Configuration

The analytics script records pageviews automatically, including SPA navigation. Use the **All Pages** trigger only to load the script; do not add a second pageview tag.

### Scroll Tracking

Databuddy's built-in tracking already covers scroll depth, so you do not need a separate GTM scroll depth tag.

### Click Tracking

Track specific button clicks:

1. **Trigger Type**: Click - All Elements
2. **Conditions**: Click Classes contains "track-button"
3. **Tag**: Custom HTML with click tracking

```html
<script>
  if (window.databuddy) {
    databuddy.track('button_click', {
      button_text: '{{Click Text}}',
      button_classes: '{{Click Classes}}',
      page_path: '{{Page Path}}'
    });
  }
</script>
```

## E-commerce Integration

### Enhanced E-commerce Setup

Track the complete customer journey. Create Data Layer Variables for the product values your site pushes to the data layer, and fire each tag on the matching data layer event trigger.

**Product View Tag:**

```html
<script>
  if (window.databuddy) {
    databuddy.track('product_view', {
      product_id: '{{Product ID}}',
      product_name: '{{Product Name}}',
      product_category: '{{Product Category}}',
      product_price: {{Product Price}},
      currency: '{{Currency}}'
    });
  }
</script>
```

**Add to Cart Tag:**

```html
<script>
  if (window.databuddy) {
    databuddy.track('add_to_cart', {
      product_id: '{{Product ID}}',
      product_name: '{{Product Name}}',
      quantity: {{Quantity}},
      value: {{Item Revenue}},
      currency: '{{Currency}}'
    });
  }
</script>
```

**Begin Checkout Tag:**

```html
<script>
  if (window.databuddy) {
    databuddy.track('begin_checkout', {
      value: {{Cart Value}},
      currency: '{{Currency}}',
      item_count: {{Items Count}}
    });
  }
</script>
```

## User Privacy and Consent

Google's consent settings do not automatically gate Databuddy. If your deployment requires consent, configure the loader tag's **additional consent checks** and trigger it only after your consent manager grants analytics consent. Connect that trigger to the manager's actual consent event; its name varies by implementation.

On withdrawal, call `window.databuddyOptOut()` and prevent the tag from loading again. On a later grant, `window.databuddyOptIn()` clears that local opt-out; it does not override Do Not Track or Global Privacy Control. Test both a fresh browser session and withdrawal after collection has started.

See [Google's consent overview](https://developers.google.com/tag-platform/security/concepts/consent-mode) and the [Databuddy privacy guide](/docs/compliance/gdpr-compliance-guide).

## Debugging and Testing

### Debug Mode Setup

Enable debug mode for testing:

```html
<script>
  var isDebugMode = '{{Debug Mode}}' === 'true';

  if (window.databuddy && isDebugMode) {
    console.log('Databuddy Debug Mode Enabled');
    databuddy.track('debug_event', {
      page: '{{Page Path}}',
      timestamp: new Date().toISOString()
    });
  }
</script>
```

### Preview Mode Testing

1. Click **Preview** in GTM
2. Visit your website in the debug session
3. Verify Databuddy tags are firing correctly
4. Check browser console for any errors
5. Confirm events in Databuddy dashboard

### Variable Testing

Create test variables for debugging:

**Debug Info Variable:**

```javascript
function() {
  return {
    page_path: '{{Page Path}}',
    page_title: '{{Page Title}}',
    user_agent: navigator.userAgent,
    timestamp: new Date().toISOString()
  };
}
```

## Best Practices

The loader is asynchronous and reports load failures in the browser console. A failed load does not emit `databuddy_ready`.

### Tag Organization

1. **Naming Convention**: Use clear, descriptive names
2. **Folders**: Organize tags by vendor or purpose
3. **Notes**: Add descriptions explaining each tag's purpose
4. **Triggers**: Name triggers clearly (e.g., "Databuddy - All Pages")

### Version Management

1. **Descriptive Names**: Use meaningful version names
2. **Notes**: Document changes in each version
3. **Testing**: Always test in preview before publishing
4. **Rollback Plan**: Know how to revert if issues arise

## Migration from Google Analytics

### Replacing GA4 with Databuddy

1. **Pause GA4 tags** (don't delete immediately)
2. **Create Databuddy tags** with equivalent functionality
3. **Test thoroughly** in preview mode
4. **Gradual rollout** using percentage-based triggers
5. **Monitor data** for consistency

### Data Mapping

Map GA4 events to Databuddy equivalents:

| GA4 Event   | Databuddy Event | Notes                           |
| ----------- | --------------- | ------------------------------- |
| page_view   | screen_view     | Automatic |
| purchase    | purchase        | Enhanced with privacy features  |
| add_to_cart | add_to_cart     | Same structure                  |
| scroll      | scroll_depth    | Covered by built-in tracking    |

## Troubleshooting

### Common Issues

**Tag Not Firing:**

- Check trigger conditions
- Verify variable values in preview mode
- Ensure GTM code is properly installed

**Events Not Tracking:**

- Verify Databuddy script loads successfully
- Check browser console for errors
- Confirm Client ID is correct

**Performance Issues:**

- Ensure scripts load asynchronously
- Check for blocking JavaScript errors
- Monitor Core Web Vitals impact

### Debug Checklist

1. ✅ GTM container code installed correctly
2. ✅ Databuddy tag fires on correct triggers
3. ✅ Client ID variable contains correct value
4. ✅ No JavaScript errors in console
5. ✅ Events appear in Databuddy dashboard
6. ✅ Privacy settings respected

## Related Integrations

<Cards>
  <Card title="Shopify" href="/docs/Integrations/shopify">
    Complete e-commerce tracking with purchase analytics.
  </Card>
  <Card title="Next.js" href="/docs/Integrations/nextjs">
    App Router and Pages Router setup for Next.js apps.
  </Card>
  <Card title="WordPress" href="/docs/Integrations/wordpress">
    Plugin or manual setup for WordPress sites.
  </Card>
</Cards>

Need help with your GTM integration? Contact us at [support@databuddy.cc](mailto:support@databuddy.cc).
