# How to Track AI Chatbot Traffic in Google Analytics (GA4)

> Canonical source: [How to Track AI Chatbot Traffic in Google Analytics (GA4)](https://ai.answer.cloud/pages/how-to-track-ai-chatbot-traffic-in-google-analytics-ga4/)

Learn how to identify and track visits from AI chatbots and crawlers in Google Analytics 4 by setting up a custom dimension and adding a user agent detection script. This helps distinguish bot traffic from genuine users for more accurate analytics.

Tracking AI chatbots and search engine crawlers in Google Analytics 4 (GA4) ensures better data accuracy by separating bot traffic from real user activity. Follow the steps below to set up bot detection and reporting in GA4.

## Step 1: Create a Custom Dimension in GA4

1. Go to **Admin** in your GA4 property.
2. Select **Custom definitions**.
3. Click **Create custom dimension**.
4. Configure the dimension as follows:
   - **Name**: `is_bot`
   - **Scope**: `Event`
   - **Event parameter**: `is_bot` (Type `is_bot` manually; it may not appear in the dropdown.)
5. Save the custom dimension.

## Step 2: Add User Agent Detection Script
Embed the following JavaScript snippet on your website, before the closing `</head>` tag or within your tag manager. This script checks the visitor's user agent string and identifies known bots, including popular AI and search engine bots.

html
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
// --- Build a regex and check UA ---
(function() {
    const ua = navigator.userAgent || "";

    // Combined regex from your KNOWN_BOTS list
    const botRegex = /(gptbot|oai-searchbot|claude|anthropic|perplexitybot|googlebot|bingbot|duckduckbot|baiduspider|yandex|facebookexternalhit|meta-externalagent|twitterbot|linkedinbot|ahrefsbot|semrushbot|mj12bot|\b(bot|spider|crawler)\b)/i;

    const match = ua.match(botRegex);
    if (match) {
      window.__isBot = true;
      window.__botName = match[0]; // raw match, good enough for reporting
    } else {
      window.__isBot = false;
      window.__botName = null;
    }
})();

// --- GA4 setup ---
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('js', new Date());

// Send bot info with all pageviews
gtag('config', 'G-XXXXXXXXXX', {
    page_location: location.href,
    page_title: document.title,
    is_bot: window.__isBot ? 'true' : 'false',
    bot_name: window.__botName || 'none'
});
</script>


- Replace `G-XXXXXXXXXX` with your actual Google Analytics 4 Measurement ID.

## Step 3: Analyze Bot Traffic in GA4

After completing the above steps:
- The `is_bot` custom dimension will be available in your GA4 reports.
- Use this dimension to segment and filter bot vs. human traffic in your analytics dashboards.
- Optionally, add `bot_name` as a custom dimension to identify specific bots accessing your site.

---