AgentShield

Marketing Pixel

No-code AI agent detection for marketing teams using Google Tag Manager

Overview

The AgentShield Marketing Pixel is a no-code solution for detecting AI agents and bots on your website. Perfect for marketing teams, it integrates seamlessly with Google Tag Manager (GTM) and other tag management systems.

Why Use the Marketing Pixel?

For Marketing Teams

  • No coding required - Install through GTM interface
  • Quick deployment - Live in minutes, not days
  • Easy configuration - Visual interface for settings
  • A/B testing ready - Test different responses

Analytics Integration

  • Google Analytics 4 - Automatic event tracking
  • Custom dimensions - Rich agent detection data
  • Audience building - Segment real users from bots
  • Conversion tracking - Accurate conversion metrics

Bot Protection

  • Ad fraud prevention - Block fake ad clicks
  • Form spam protection - Stop automated submissions
  • Content scraping - Protect your content
  • Inventory protection - Hide pricing from competitors

Installation Methods

GTM Installation

Step 1: Import the Template

  1. Log into Google Tag Manager
  2. Navigate to TemplatesTag Templates
  3. Click Search Gallery
  4. Search for "AgentShield"
  5. Click Add to Workspace
  6. Click Add to confirm

If the template isn't in the gallery yet, you can import it manually from our GitHub repository. Download the template.tpl file and import it using GTM's template import feature.

Manual Template Import (Alternative)

If you can't find the template in the gallery:

  1. Visit our GitHub repository
  2. Download the template.tpl file
  3. In GTM, go to TemplatesTag TemplatesNew
  4. Click the menu → Import
  5. Select the downloaded template.tpl file
  6. Click Save

Step 2: Create the Tag

  1. Go to TagsNew
  2. Click Tag Configuration
  3. Select AgentShield Pixel from Custom templates
  4. Configure:
    • API Key: Enter your AgentShield API key
    • Detection Action: Choose response type
    • Confidence Threshold: Set sensitivity (0.7 recommended)

Step 3: Set Triggers

  1. Click Triggering
  2. For Single Page Applications (SPAs):
    • Create a History Change trigger (for React, Vue, Angular)
    • Go to Triggers → New → Trigger Configuration
    • Select History Change as trigger type
    • Name it "All History Changes"
    • Apply this trigger to your AgentShield tag
  3. For Traditional websites:
    • Select All Pages trigger
  4. Optional: Add custom triggers for specific events:
    • Form submissions
    • Button clicks
    • Scroll depth
    • Time on page

SPA Tracking Note: The AgentShield pixel now automatically detects and tracks SPA navigation events including:

  • History API changes (pushState/replaceState)
  • Browser back/forward navigation (popstate)
  • Hash changes (hashchange)

However, configuring GTM's History Change trigger ensures redundancy and allows you to track additional GTM variables with each navigation.

Step 4: Test & Publish

  1. Click Preview to test in debug mode
  2. Verify the pixel fires correctly
  3. Check detection events in preview
  4. Click Submit to publish
  5. Add version notes and Publish

Configuration in GTM

Basic Settings

API Key: [Your API Key]
Action on Detection: Block/Log/Redirect
Confidence Threshold: 0.7
Debug Mode: Off (On for testing)

Advanced Settings

Custom Endpoint: (leave blank for default)
Session Timeout: 1800000 (30 minutes)
Batch Events: Yes
Batch Size: 20
Send Beacon on Unload: Yes

Direct JavaScript Installation

Perfect for traditional websites, WordPress, Shopify, and any site not using a framework.

Basic Setup

Add this code to your website's <head> or before the closing </body> tag:

<!-- AgentShield Pixel -->
<script
  src="https://kya.vouched.id/pixel.js"
  data-project-id="YOUR_PROJECT_ID"
  data-debug="false">
</script>

Replace YOUR_PROJECT_ID with your actual project ID from your AgentShield dashboard.

What the pixel does automatically:

  • Automatic detection - Identifies AI agents and bots on every pageview
  • SPA tracking - Detects navigation in React, Vue, Angular apps
  • Session persistence - Maintains session across page reloads
  • User identification - Ready for window.AgentShield.identify() calls
  • Debug mode - Set data-debug="true" to see detailed console logs

Configuration Options

The pixel script accepts several data attributes for configuration:

<script
  src="https://kya.vouched.id/pixel.js"
  data-project-id="YOUR_PROJECT_ID">
</script>
AttributeDescriptionDefault
data-project-idYour AgentShield project ID (required)-
data-debugEnable debug console loggingfalse
data-session-timeoutSession timeout in milliseconds1800000 (30 min)
data-respect-dntHonor Do Not Track browser settingtrue
data-enable-fingerprintingEnable browser fingerprintingtrue

Verifying Installation

After adding the pixel script, verify it's working by opening your browser's Developer Tools console:

// Check if AgentShield is loaded
console.log('Pixel loaded:', typeof window.AgentShield !== 'undefined');

// Get initialization info
console.log(window.AgentShield?.getInitInfo());

// Expected output:
// {
//   version: "1.1.0",
//   initialized: true,
//   sessionId: "abc-123...",
//   projectId: "YOUR_PROJECT_ID"
// }

If you see initialized: true, the pixel is working correctly!

Next.js Installation

Important: Content Security Policy (CSP) Configuration

If you have Content Security Policy (CSP) headers configured, you MUST allowlist the AgentShield domain or the pixel will be blocked by your browser.

Common CSP error you'll see if not configured:

Refused to load the script 'https://kya.vouched.id/pixel.js'
because it violates the following Content Security Policy directive

Required CSP Directives:

  • script-src: Must include https://kya.vouched.id (to load the pixel script)
  • connect-src: Must include https://kya.vouched.id (for API calls to send detection data)

Add the AgentShield domain to your existing CSP configuration:

// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          {
            key: 'Content-Security-Policy',
            value: [
              "default-src 'self'",
              "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://kya.vouched.id",
              "connect-src 'self' https://kya.vouched.id",
              // ... your other CSP directives
            ].join('; ')
          }
        ]
      }
    ]
  }
}

Only add https://kya.vouched.id to your existing CSP directives. Don't replace your entire CSP policy with this example.

Method 2: Using Middleware for CSP

Create or update middleware.ts to set CSP headers:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const response = NextResponse.next();

  // Get existing CSP or create new one
  const csp = response.headers.get('Content-Security-Policy') || '';

  // Add AgentShield domains to script-src
  const updatedCsp = csp.includes('script-src')
    ? csp.replace(
        /script-src([^;]*)/,
        'script-src$1 https://kya.vouched.id https://agentshield.io'
      )
    : `${csp}; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://kya.vouched.id https://agentshield.io`;

  response.headers.set('Content-Security-Policy', updatedCsp);

  return response;
}

Method 3: Proxy the Script (Alternative)

If you cannot modify CSP headers, proxy the script through your API:

// app/api/agentshield-pixel/route.ts
export async function GET() {
  const response = await fetch('https://kya.vouched.id/pixel.js');
  const script = await response.text();

  return new Response(script, {
    headers: {
      'Content-Type': 'application/javascript',
      'Cache-Control': 'public, max-age=3600',
    },
  });
}

Then load the script from your domain:

<script src="/api/agentshield-pixel"></script>

Method 4: Self-Host the Script

Download and serve the pixel script from your public directory:

# Download the pixel script
curl https://kya.vouched.id/pixel.js > public/agentshield-pixel.js

Then reference it locally:

<script src="/agentshield-pixel.js"></script>

Self-hosting requires manual updates when new versions are released. We recommend using CSP configuration or proxying for automatic updates.

Adding the Pixel to Your App

Use Next.js's <Script> component with strategy="afterInteractive" for optimal performance.

The pixel script automatically detects and tracks pageviews. No additional configuration needed!

App Router (app/layout.tsx)

import Script from 'next/script';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <Script
          src="https://kya.vouched.id/pixel.js"
          data-project-id="YOUR_PROJECT_ID"
          strategy="afterInteractive"
        />
        {children}
      </body>
    </html>
  );
}

Pages Router (_app.tsx)

import Script from 'next/script';
import type { AppProps } from 'next/app';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Script
        src="https://kya.vouched.id/pixel.js"
        data-project-id="YOUR_PROJECT_ID"
        strategy="afterInteractive"
      />
      <Component {...pageProps} />
    </>
  );
}

Why strategy="afterInteractive"?

  • Loads after the page becomes interactive
  • Doesn't block page rendering
  • Optimal for analytics and tracking scripts

Security Best Practices

Trusted Domain: AgentShield uses https://kya.vouched.id for the pixel and API endpoints.

Only add this domain to your CSP if you have CSP headers configured. Most sites don't need to configure CSP.

Testing Checklist:

  1. ✅ Test in development with data-debug="true" enabled
  2. ✅ Check browser console for initialization message
  3. ✅ Verify no CSP errors in console
  4. ✅ Test in production with debug mode disabled

Adobe Launch Installation

Step 1: Create Data Element

  1. Go to Data ElementsAdd Data Element
  2. Name: "AgentShield API Key"
  3. Extension: Core
  4. Data Element Type: Custom Code
  5. Code:
    return 'YOUR_API_KEY';

Step 2: Create Rule

  1. Go to RulesAdd Rule
  2. Name: "AgentShield Detection"
  3. Events: Add "Page Bottom" or "DOM Ready"
  4. Actions: Add Action
    • Extension: Core
    • Action Type: Custom Code

Step 3: Add Pixel Code

// Load AgentShield pixel
var script = document.createElement('script');
script.src = '${process.env.NEXT_PUBLIC_CDN_URL || "https://agentshield.io"}/pixel.js';
script.onload = function() {
  // Initialize with data element
  window.agentshield('init', _satellite.getVar('AgentShield API Key'));
  window.agentshield('track', 'pageview');
};
document.head.appendChild(script);

Step 4: Publish

  1. Save the rule
  2. Build for Development
  3. Test in staging
  4. Build for Production

Google Analytics 4 Integration

Automatic Event Tracking

The pixel automatically sends events to GA4:

// Events sent to GA4
gtag('event', 'agent_detection', {
  agent_type: 'bot',
  confidence: 0.85,
  action_taken: 'blocked',
  user_agent: 'Mozilla/5.0...',
});

Custom Dimensions Setup

  1. In GA4, go to ConfigureCustom Definitions
  2. Create custom dimensions:
    • agent_detection_score (Number)
    • is_agent (Boolean)
    • agent_type (Text)
    • detection_action (Text)

Audience Creation

  1. Go to ConfigureAudiences
  2. Create "Real Users" audience:
    • Condition: is_agent = false
  3. Create "Detected Bots" audience:
    • Condition: is_agent = true

Conversion Tracking

// Only track conversions for real users
if (!agentshield.isAgent()) {
  gtag('event', 'conversion', {
    send_to: 'AW-XXXXX/XXXXX',
    value: 100.0,
    currency: 'USD',
  });
}

Common Use Cases

E-commerce Protection

// Hide prices from scrapers
agentshield('onDetection', function (result) {
  if (result.isAgent && result.confidence > 0.8) {
    // Hide or modify pricing
    document.querySelectorAll('.price').forEach(function (el) {
      el.textContent = 'Login for pricing';
    });
  }
});

Form Spam Prevention

// Block form submission for detected agents
document.getElementById('form').addEventListener('submit', function (e) {
  if (agentshield.isAgent()) {
    e.preventDefault();
    alert('Please verify you are human');
    // Show CAPTCHA or challenge
  }
});

Content Protection

// Protect premium content
agentshield('onDetection', function (result) {
  if (result.isAgent) {
    // Replace content with placeholder
    document.getElementById('premium-content').innerHTML =
      '<p>This content is available to registered users only.</p>';
  }
});

Ad Fraud Prevention

// Don't load ads for bots
agentshield('ready', function () {
  if (!agentshield.isAgent()) {
    // Load ad scripts only for real users
    loadAdsense();
    loadDisplayAds();
  }
});

Testing Your Installation

Using GTM Preview Mode

  1. Click Preview in GTM
  2. Enter your website URL
  3. Open the Tag Assistant
  4. Verify:
    • AgentShield tag fires on page load
    • Events are being sent
    • No JavaScript errors

Browser Console Testing

// Check if pixel is loaded
console.log(typeof agentshield); // Should be 'function'

// Check detection status
agentshield('getStatus', function (status) {
  console.log('Detection status:', status);
});

// Manually trigger detection
agentshield('detect', function (result) {
  console.log('Detection result:', result);
});

User Agent Testing

Test with different user agents:

# Test with bot user agent
curl -H "User-Agent: Googlebot/2.1" https://yoursite.com

# Test with normal browser
curl -H "User-Agent: Mozilla/5.0..." https://yoursite.com

JavaScript API Reference

The pixel exposes a window.AgentShield object with methods for user identification and session management.

Available Methods

// Identify a user (for user tracking)
window.AgentShield.identify(userId, traits);

// Reset user identification (on logout)
window.AgentShield.reset();

// Get current identified user
window.AgentShield.getUser();

// Get session information
window.AgentShield.getSession();

// Track custom events
window.AgentShield.track(eventName, data);

// Get initialization status (debugging)
window.AgentShield.getInitInfo();

// Grant consent for cookies (GDPR)
window.AgentShield.grantConsent();

Method Details

identify(userId, traits)

Associates a user with the current session. Call this when users log in.

window.AgentShield.identify('user_123', {
  email: 'user@example.com',
  name: 'John Doe',
  plan: 'premium',
});

reset()

Clears user identification. Call this when users log out.

window.AgentShield.reset();

getUser()

Returns the currently identified user or null.

const user = window.AgentShield.getUser();
// Returns: { id: 'user_123' } or null

track(eventName, data)

Track custom events.

window.AgentShield.track('button_click', {
  button: 'signup',
  page: '/pricing',
});

For complete user identification documentation, see the User Identification guide.

Troubleshooting

Pixel Not Loading

  1. Check API key is correct
  2. Verify script tag is in <head>
  3. Check for Content Security Policy blocks
  4. Ensure no ad blockers are interfering

Events Not Tracking

  1. Enable debug mode
  2. Check browser console for errors
  3. Verify triggers in GTM
  4. Test in incognito mode

Detection Not Working

  1. Check confidence threshold
  2. Verify API endpoint is accessible
  3. Review user agent string
  4. Test with known bot user agents

Privacy & Compliance

Always comply with privacy regulations in your jurisdiction. The pixel respects user privacy preferences by default.

GDPR Compliance

// Wait for consent
if (hasUserConsent()) {
  agentshield('init', 'API_KEY');
} else {
  // Delay until consent granted
  onConsentGranted(function () {
    agentshield('init', 'API_KEY');
  });
}
agentshield('init', 'API_KEY', {
  useCookies: false, // Disable cookies
  useLocalStorage: false, // Disable local storage
  sessionOnly: true, // Session data only
});

Best Practices

  1. Start with logging before blocking
  2. Test thoroughly before production
  3. Monitor false positives in analytics
  4. Adjust thresholds based on your traffic
  5. Use custom events for important actions
  6. Respect user privacy and preferences
  7. Keep API keys secure using environment variables

Next Steps

Command Palette

Search for a command to run...