# UTM Parameters Module

The `utm_params` module automatically extracts UTM parameters and other common campaign tracking parameters from the current page URL. These parameters are essential for understanding marketing campaign effectiveness, traffic sources, and attribution.

## Collected Signals

The module collects the following campaign tracking signals when present in the URL:

### Standard UTM Parameters

- **`c_utm_source`**: Identifies the traffic source (e.g., google, facebook, newsletter, email)
- **`c_utm_medium`**: Identifies the marketing medium (e.g., cpc, email, social, banner, affiliate)
- **`c_utm_campaign`**: Identifies the specific campaign name (e.g., summer_sale, product_launch_2024)
- **`c_utm_term`**: Identifies paid search keywords for PPC campaigns
- **`c_utm_content`**: Identifies specific ad content or link variation (useful for A/B testing)

### Ad Platform Click IDs

- **`c_gclid`**: Google Click ID for Google Ads tracking and conversion attribution
- **`c_fbclid`**: Facebook Click ID for Facebook/Instagram Ads tracking
- **`c_msclkid`**: Microsoft Click ID for Microsoft Advertising (Bing Ads) tracking
- **`c_ttclid`**: TikTok Click ID for TikTok Ads tracking
- **`c_twclid`**: Twitter Click ID for Twitter Ads tracking
- **`c_li_fat_id`**: LinkedIn Partner ID for LinkedIn Ads tracking

All signals use the `c_` prefix (campaign) for consistency and are marked as non-hashed since they represent campaign identifiers and click tracking IDs, not personally identifiable information.

## How It Works

The module parses the current page URL (`window.location.href`) and extracts any campaign tracking parameters present in the query string. Only parameters that exist in the URL will be collected as signals.

### Example URLs

**Example 1: Standard UTM Parameters**
```
https://example.com/products?utm_source=google&utm_medium=cpc&utm_campaign=spring_sale
```
Collected signals:
- `c_utm_source`: google
- `c_utm_medium`: cpc
- `c_utm_campaign`: spring_sale

**Example 2: Google Ads with Click ID**
```
https://example.com/landing?gclid=Cj0KCQiA_P6dBhDGARIsAAD4a...&utm_source=google_ads&utm_campaign=brand_keywords
```
Collected signals:
- `c_gclid`: Cj0KCQiA_P6dBhDGARIsAAD4a...
- `c_utm_source`: google_ads
- `c_utm_campaign`: brand_keywords

**Example 3: Facebook Ads with Click ID**
```
https://example.com/?fbclid=IwAR3xGz8N...&utm_source=facebook&utm_medium=social&utm_campaign=retargeting
```
Collected signals:
- `c_fbclid`: IwAR3xGz8N...
- `c_utm_source`: facebook
- `c_utm_medium`: social
- `c_utm_campaign`: retargeting

## Usage

The module is automatically loaded when included in the IdGraph modules configuration:

```typescript
const idGraph = new IdGraph('my-container', {
  modules: ['utm_params'], // Include the utm_params module
  // ... other options
});
```

Or it's included by default when no modules are specified:

```typescript
const idGraph = new IdGraph('my-container', {
  // utm_params is loaded by default along with other modules
});
```

## Privacy Considerations

- **All campaign tracking parameters are NOT hashed** as they represent campaign identifiers and marketing attribution data, not personally identifiable information
- Click IDs (gclid, fbclid, etc.) are tracking identifiers used by ad platforms for conversion attribution
- These parameters help measure marketing ROI and optimize campaigns

## Use Cases

### 1. Campaign Performance Analysis
Track which campaigns drive the most traffic and conversions:

```typescript
const signals = idGraph.getSignals();
const utmSource = signals.find(s => s.name === 'c_utm_source')?.value;
const utmCampaign = signals.find(s => s.name === 'c_utm_campaign')?.value;

console.log(`Traffic from ${utmSource} - Campaign: ${utmCampaign}`);
// Analyze: Which campaigns perform best?
```

### 2. Channel Attribution
Understand which marketing channels are most effective:

```typescript
const signals = idGraph.getSignals();
const utmMedium = signals.find(s => s.name === 'c_utm_medium')?.value;

switch(utmMedium) {
  case 'cpc':
    // Paid search traffic
    break;
  case 'email':
    // Email marketing traffic
    break;
  case 'social':
    // Social media traffic
    break;
  case 'organic':
    // Organic search traffic
    break;
}
```

### 3. A/B Testing Ad Content
Compare performance of different ad variations:

```typescript
const signals = idGraph.getSignals();
const utmContent = signals.find(s => s.name === 'c_utm_content')?.value;

// Track conversions by ad content
if (utmContent === 'ad_variant_a') {
  // Track performance for variant A
} else if (utmContent === 'ad_variant_b') {
  // Track performance for variant B
}
```

### 4. Cross-Platform Tracking
Identify users from different ad platforms:

```typescript
const signals = idGraph.getSignals();
const hasGoogleAds = signals.some(s => s.name === 'c_gclid');
const hasFacebookAds = signals.some(s => s.name === 'c_fbclid');
const hasMicrosoftAds = signals.some(s => s.name === 'c_msclkid');

if (hasGoogleAds) {
  // User came from Google Ads
} else if (hasFacebookAds) {
  // User came from Facebook/Instagram Ads
} else if (hasMicrosoftAds) {
  // User came from Microsoft Advertising
}
```

## UTM Parameter Best Practices

### Naming Conventions

Use consistent, descriptive naming:

```
✅ Good: utm_source=google&utm_medium=cpc&utm_campaign=summer_sale_2024
❌ Bad: utm_source=g&utm_medium=1&utm_campaign=ss24
```

### Common Values by Parameter

**utm_source** (Where is the traffic coming from?)
- `google` - Google (organic or paid)
- `facebook` - Facebook
- `twitter` - Twitter
- `newsletter` - Email newsletter
- `linkedin` - LinkedIn
- `instagram` - Instagram
- `youtube` - YouTube

**utm_medium** (What type of marketing?)
- `cpc` - Cost-per-click (paid search)
- `email` - Email marketing
- `social` - Social media
- `organic` - Organic search
- `referral` - Referral traffic
- `display` - Display advertising
- `affiliate` - Affiliate marketing

**utm_campaign** (What specific campaign?)
- `summer_sale_2024` - Seasonal campaign
- `product_launch_q1` - Product launch
- `black_friday` - Event-based campaign
- `newsletter_weekly_123` - Newsletter edition

**utm_content** (What specific content/variation?)
- `text_ad_1` - Text ad variation 1
- `banner_blue` - Blue banner design
- `cta_buy_now` - Call-to-action variant
- `header_link` - Placement identifier

**utm_term** (What search keywords?)
- `running+shoes` - Search terms
- `best+laptops+2024` - Keyword phrases
- Only relevant for paid search campaigns

## Example Output

When visiting a URL with campaign parameters:
```
https://example.com/products?utm_source=google&utm_medium=cpc&utm_campaign=spring_sale&utm_term=running+shoes&utm_content=ad_variant_a&gclid=Cj0KCQiA_P6dBhDGARIsAAD4a...
```

The collected signals would be:

```typescript
console.log(idGraph.getSignals());
// Output:
// [
//   { name: "c_utm_source", value: "google", hashed: false },
//   { name: "c_utm_medium", value: "cpc", hashed: false },
//   { name: "c_utm_campaign", value: "spring_sale", hashed: false },
//   { name: "c_utm_term", value: "running+shoes", hashed: false },
//   { name: "c_utm_content", value: "ad_variant_a", hashed: false },
//   { name: "c_gclid", value: "Cj0KCQiA_P6dBhDGARIsAAD4a...", hashed: false }
// ]
```

When visiting a URL without campaign parameters:
```
https://example.com/products
```

No signals are collected (empty array).

## Integration with Analytics Platforms

### Google Analytics
UTM parameters automatically integrate with Google Analytics when properly configured. The module captures the same parameters that GA4 uses for campaign tracking.

### Facebook Ads
The `fbclid` parameter enables Facebook Ads conversion tracking and attribution. This is automatically added by Facebook when users click on your ads.

### Google Ads
The `gclid` parameter enables Google Ads conversion tracking and attribution. This is automatically added by Google when users click on your ads.

## Troubleshooting

### No campaign parameters collected

**Cause:** The URL doesn't contain any UTM or click ID parameters.

**Solution:** Ensure your marketing campaigns are properly tagged with UTM parameters. Use tools like Google's Campaign URL Builder.

### Parameters appear in URL but not collected

**Possible causes:**
1. **Case sensitivity**: UTM parameters are case-sensitive. Use lowercase: `utm_source`, not `UTM_SOURCE`
2. **Typos**: Ensure parameters are spelled correctly
3. **Special characters**: Some characters may need URL encoding

### Testing campaign parameters locally

```typescript
// Manually test by visiting URLs with parameters
window.location = 'http://localhost:3000/?utm_source=test&utm_campaign=local_test';

// Or use URLSearchParams to build test URLs
const params = new URLSearchParams({
  utm_source: 'test',
  utm_medium: 'email',
  utm_campaign: 'test_campaign'
});
window.location.href = `${window.location.origin}${window.location.pathname}?${params}`;
```

## Campaign URL Builders

Use these free tools to generate properly formatted campaign URLs:

1. **Google Campaign URL Builder**: https://ga-dev-tools.google/campaign-url-builder/
2. **Google Sheets Template**: Create your own URL builder spreadsheet
3. **HubSpot Campaign URL Builder**: https://www.hubspot.com/campaign-url-builder

## Debug Mode

Enable debug mode to see campaign parameter collection:

```typescript
const idGraph = new IdGraph('my-container', {
  debug: true,
  modules: ['utm_params']
});

// Check console for:
// "Samhub -> IdGraph Module loaded: utm_params"
// And all collected signals when flushed
```

## Advanced: Custom Parameter Collection

If you need to collect additional custom campaign parameters, you can extend the module or add them as custom signals:

```typescript
// After IdGraph initialization
const customParam = new URLSearchParams(window.location.search).get('custom_param');
if (customParam) {
  await idGraph.addCustomSignal({
    name: 'custom_param', // Will be prefixed as 'd_custom_param'
    value: customParam,
    hashed: false
  });
}
```

## Browser Compatibility

The module uses the standard `URL` and `URLSearchParams` APIs, which are supported in:
- ✅ Chrome 49+
- ✅ Firefox 44+
- ✅ Safari 10+
- ✅ Edge 14+
- ✅ All modern mobile browsers

## Security Considerations

- Campaign parameters are automatically sanitized by the URL API
- No code execution risk from parameter values
- Parameters are transmitted as-is without modification
- Consider URL length limits (generally 2048 characters for maximum compatibility)
