# Tracker Integration Guide

Learn how to integrate CiteFlow tracking into your website.

## Installation

### Basic Setup

Add this script to your website's `<head>` section:

```html
<script 
  src="https://cdn.citeflow.ai/tracker.js" 
  data-site-id="YOUR_SITE_ID"
  async
></script>
```

### Next.js Integration

In your `app/layout.tsx`:

```tsx
export default function RootLayout({ children }) {
  return (
    <html>
      <head>
        <script 
          src="https://cdn.citeflow.ai/tracker.js" 
          data-site-id="YOUR_SITE_ID"
          async
        />
      </head>
      <body>{children}</body>
    </html>
  )
}
```

## Event Types

CiteFlow tracks three types of events:

### 1. Pageview
Automatically tracked when a user visits a page.

### 2. Session Start
Automatically tracked when a new session begins.

### 3. Engagement
Automatically tracked when a user spends time on a page.

## AI Source Detection

CiteFlow automatically detects traffic from these AI platforms:

### AI Crawlers (Website Crawling)
| Platform | Bot Name |
|----------|----------|
| OpenAI | GPTBot, ChatGPT-User |
| Anthropic | ClaudeBot, Claude-Web |
| Perplexity | PerplexityBot |
| Google | Google-Extended, Gemini, Googlebot |
| Microsoft | Bingbot, Copilot |
| Meta | FacebookBot |
| Apple | Applebot |
| Amazon | Amazonbot |
| Common Crawl | CCBot |
| ByteDance | Bytespider |
| Cohere | Cohere |
| xAI | Grok |
| And many more... |

### AI User Traffic (From AI Interfaces)
When users click links from these AI chat interfaces:
| Platform | Website |
|----------|---------|
| ChatGPT | chat.openai.com, chatgpt.com |
| Claude | claude.ai |
| Perplexity | perplexity.ai |
| Gemini | gemini.google.com |
| Copilot | copilot.microsoft.com |

## Cloudflare Worker Integration

For real-time AI bot tracking, deploy this Cloudflare Worker:

```javascript
export default {
  async fetch(request, env, ctx) {
    const userAgent = request.headers.get("user-agent") || "";
    const referer = request.headers.get("referer") || "";

    // Comprehensive AI detection (crawlers + user traffic)
    const aiPatterns = [
      // OpenAI: GPTBot, ChatGPT-User, o1/o3/o4 models
      "gptbot", "chatgpt", "operator", "openai",
      // Anthropic: ClaudeBot, Claude-Web
      "claudebot", "claude-web", "anthropic",
      // Perplexity
      "perplexity",
      // Google: Google-Extended, Gemini, Googlebot
      "google-extended", "gemini", "googlebot",
      // Microsoft: Bingbot, Copilot
      "bingbot", "copilot", "microsoft",
      // Meta, Apple, Amazon
      "facebook", "applebot", "amazonbot",
      // Other AI & search
      "cohere", "ccbot", "bytespider", "diffbot",
      "duckduckbot", "yandexbot", "baiduspider",
      // Code assistants
      "codesearchbot", "cursorbot", "sourcegraph",
      // Emerging AI
      "claude-3", "claude-4", "grok", "mistral",
      "llama", "qwen", "deepseek", "yi",
    ];

    const isAIBot = aiPatterns.some(pattern =>
      userAgent.toLowerCase().includes(pattern)
    );

    // Also check if user came from AI interface
    const aiReferrers = [
      "chat.openai.com", "chatgpt.com", "claude.ai",
      "perplexity.ai", "gemini.google.com", "copilot.microsoft.com"
    ];
    const fromAIInterface = aiReferrers.some(ref => referer.includes(ref));

    if (isAIBot || fromAIInterface) {
      ctx.waitUntil(
        fetch("https://api.citeflow.ai/bot", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            siteId: env.CITEFLOW_SITE_ID,
            url: request.url,
            userAgent: userAgent,
            referer: referer,
            source: fromAIInterface ? "ai_interface" : "crawler",
            timestamp: new Date().toISOString()
          })
        })
      );
    }

    return fetch(request);
  }
}
```

### Deploy to Cloudflare

1. Go to Cloudflare Dashboard → Workers
2. Create a new Worker
3. Paste the code above
4. Set `CITEFLOW_SITE_ID` in environment variables
5. Add the Worker to your site's routes

## Privacy Considerations

### Data Collected
- Page URL
- Referrer (for AI source detection)
- Session ID (anonymized)
- Timestamp

### Data NOT Collected
- Personal information
- IP addresses (only hashed for session)
- Cookies for tracking

### GDPR Compliance
The tracker is designed to be privacy-friendly:
- No personal data collected
- No cross-site tracking
- No cookies required for basic functionality

## Advanced Configuration

### Custom Endpoint

```html
<script 
  src="https://cdn.citeflow.ai/tracker.js" 
  data-site-id="YOUR_SITE_ID"
  data-endpoint="https://your-domain.com/api/tracker"
  async
></script>
```

### Disable Auto-Tracking

```javascript
window.citeflow = {
  siteId: "YOUR_SITE_ID",
  autoTrack: false
};

// Manually track events
citeflow.track("pageview");
```

## Troubleshooting

### No events appearing
1. Check browser console for errors
2. Verify site ID is correct
3. Check network tab for failed requests
4. Disable ad blockers for testing

### AI source not detected
1. Ensure referrer header is present
2. Check if the AI platform is in our supported list
3. Verify the URL pattern matches

---

Next: [Dashboard Guide](./dashboard-guide.md)
