Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
241 changes: 131 additions & 110 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
# 🎯 Ads Click Tracker

[![npm version](https://img.shields.io/npm/v/ads-click-tracker)](https://www.npmjs.com/package/ads-click-tracker)
[![bundle size](https://img.shields.io/bundlephobia/minzip/ads-click-tracker)](https://bundlephobia.com/package/ads-click-tracker)
[![license](https://img.shields.io/npm/l/ads-click-tracker)](LICENSE)
[![Downloads](https://img.shields.io/npm/dm/ads-click-tracker)](https://www.npmjs.com/package/ads-click-tracker)
[![npm version](https://img.shields.io/npm/v/@analytics-debugger/ads-click-tracker)](https://www.npmjs.com/package/@analytics-debugger/ads-click-tracker)
[![bundle size](https://bundlephobia.com/package/@analytics-debugger/ads-click-tracker)](https://bundlephobia.com/package/@analytics-debugger/ads-click-tracker@latest)
[![license](https://img.shields.io/npm/l/@analytics-debugger/ads-click-tracker)](LICENSE)
[![Downloads](https://img.shields.io/npm/dm/@analytics-debugger/ads-click-tracker)](https://www.npmjs.com/package/@analytics-debugger/ads-click-tracker)

## 📖 Overview
# @analytics-debugger/ads-click-tracker

Ads Click Tracker is a powerful, lightweight solution for marketing attribution tracking that simplifies the complexity of capturing and managing click data across multiple advertising platforms.
A lightweight, client-side library for tracking and managing ad click IDs across user sessions.

## 🌟 Key Features
## Features

- **💡 Comprehensive Attribution Tracking**
- Automatically capture click IDs from various sources
Expand All @@ -30,166 +30,187 @@ Ads Click Tracker is a powerful, lightweight solution for marketing attribution
- Automatic data management and cleanup
- Minimal performance overhead

- **🪝 Event callbacks**
- For onLoad, New Click Id found, Updated ClickID

- **🚀 Developer-Friendly**
- Zero dependencies
- Full TypeScript support
- < 912 bytes gzipped
- Simple, intuitive API

## 🔧 Installation
## Installation

```bash
# npm
npm install ads-click-tracker

# Yarn
yarn add ads-click-tracker

# pnpm
pnpm add ads-click-tracker
npm install @analytics-debugger/ads-click-tracker
# or
yarn add @analytics-debugger/ads-click-tracker
```

## 💻 Quick Start

### Basic Usage
## Quick Start

```javascript
import { initTracker } from 'ads-click-tracker'
import AdsClickTracker from '@analytics-debugger/ads-click-tracker'

// Initialize with multiple click ID configurations
const tracker = initTracker({
// Initialize the tracker
const tracker = AdsClickTracker({
debug: true,
clickIdConfigs: [
{ name: 'gclid', expirationMs: 30 * 24 * 60 * 60 * 1000 }, // 30 days for Google Ads
{ name: 'fbclid', maxClicks: 50 } // 50 clicks limit for Facebook
{ name: 'gclid', ttl: 30 * 24 * 60 * 60 * 1000, maxClicks: 100 }, // Google Ads (30 days)
{ name: 'fbclid', ttl: 7 * 24 * 60 * 60 * 1000, maxClicks: 50 }, // Facebook (7 days)
{ name: 'ttclid', ttl: 14 * 24 * 60 * 60 * 1000, maxClicks: 50 }, // TikTok (14 days)
{ name: 'msclkid', ttl: 30 * 24 * 60 * 60 * 1000, maxClicks: 100 } // Microsoft (30 days)
],
debug: true // Enable console logging
callbacks: {
onLoaded: (clicks) => {
console.log('Tracker initialized with clicks:', clicks)
},
onNewClickId: (click) => {
console.log('New click ID detected:', click)
},
onUpdatedClickId: (click) => {
console.log('Click ID updated:', click)
}
}
})

// Get all tracked clicks
const allClicks = tracker.get()

// Get only the latest click for each source
const latestClicks = tracker.get(true)

// Manually track a click
tracker.trackClick('affiliate', 'ref123', 24 * 60 * 60 * 1000) // 1 day expiration
tracker.track('gclid', 'EAIaIQobChMIh76p9Y3', 2592000000) // value, expiration in ms

// Clear clicks for a specific source
tracker.clear('fbclid')

// Retrieve tracked clicks
const googleClicks = tracker.getClicks('gclid')
// Clear all clicks
tracker.clear()
```

## 📊 Click Data Structure
## API Reference

Each tracked click includes:
### Initialization

```typescript
interface TrackedClick {
value: string // Click ID (e.g., "abc123")
timestamp: number // Recording timestamp (milliseconds)
expiresAt: number // Expiration timestamp (milliseconds)
landing: string // Landing page URL
referrer: string // Referring URL
class AdsClickTracker {
constructor(options: TrackerOptions)
// ... other methods
}
```

## ⚙️ Configuration Options
#### TrackerOptions

### `initTracker(options)`
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `storageKey` | string | `'_act_'` | Key used for localStorage |
| `clickIdConfigs` | ClickConfig[] | *required* | Array of click ID configurations |
| `debug` | boolean | `false` | Enable debug logging |
| `checkHash` | boolean | `true` | Check hash fragment for click IDs |
| `decodeValues` | boolean | `true` | URL decode click ID values |
| `callbacks` | object | `{}` | Callback functions |

| Option | Type | Description | Default |
|--------|------|-------------|---------|
| `storageKey` | `string` | Custom storage key in localStorage | `'_ads_clicks'` |
| `clickIdConfigs` | `ClickConfig[]` | Click ID tracking configurations | `[]` |
| `debug` | `boolean` | Enable debug logging | `false` |
#### ClickConfig

### `ClickConfig`
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `name` | string | *required* | Parameter name to track (e.g., 'gclid') |
| `ttl` | number | `2592000000` (30 days) | Time in milliseconds before click expires |
| `maxClicks` | number | `100` | Maximum number of clicks to store per source |

| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | Parameter name (e.g., 'gclid') |
| `expirationMs` | `number?` | Expiration time in milliseconds |
| `maxClicks` | `number?` | Maximum number of clicks to store |
### Methods

## 📚 API Reference
#### get(latest?: boolean): Record<string, ClickData[]>

### `trackClick(source, value, expirationMs?)`
Get all tracked clicks. If `latest` is `true`, returns only the most recent click for each source.

Manually track a click:
#### track(source: string, value: string, ttl?: number): void

```javascript
tracker.trackClick(
'campaign_id', // Source name
'summer_sale', // Click ID value
7 * 24 * 60 * 60 * 1000 // Optional 7-day expiration
)
```
Manually track a click ID.

### `getClicks(source?)`
#### clear(source?: string): void

Retrieve tracked clicks:
Clear clicks for a specific source or all sources if no source is provided.

```javascript
// Get all active clicks
const allClicks = tracker.getClicks()
### ClickData Structure

// Get clicks for a specific source
const fbClicks = tracker.getClicks('fbclid')
```typescript
interface ClickData {
value: string // Click ID value
timestamp: number // When the click was recorded
expiresAt: number // When the click data expires
landing: string // Landing page URL
referrer: string // Referrer URL
}
```

### `clear(source?)`

Clear stored clicks:
## Use Cases

```javascript
// Clear Google clicks
tracker.clear('gclid')

// Clear all clicks
tracker.clear()
```
### Attribution Tracking

## 🚀 Advanced Examples

### Marketing Attribution Setup
Track which ad campaigns are driving conversions by capturing click IDs when users arrive on your site.

```javascript
const marketingTracker = initTracker({
storageKey: 'marketing_clicks',
// On your conversion/thank you page
import AdsClickTracker from '@analytics-debugger/ads-click-tracker'

const tracker = AdsClickTracker({
clickIdConfigs: [
{ name: 'gclid', expirationMs: 30 * 24 * 60 * 60 * 1000 }, // Google (30 days)
{ name: 'fbclid', expirationMs: 7 * 24 * 60 * 60 * 1000 }, // Facebook (7 days)
{ name: 'utm_campaign', maxClicks: 200 } // Custom campaign tracking
{ name: 'gclid' },
{ name: 'fbclid' }
]
})
```

### React Integration
// Get the latest clicks to include in your conversion tracking
const latestClicks = tracker.get(true)

```javascript
import { initTracker } from 'ads-click-tracker'
import { useEffect } from 'react'

function useClickTracker() {
useEffect(() => {
const tracker = initTracker({
clickIdConfigs: [{ name: 'campaign_id' }]
})

return () => tracker.clear()
}, [])
}
// Send this data to your analytics or CRM system
sendToAnalytics({
conversion: true,
value: 100,
adClicks: latestClicks
})
```

## 🌐 Browser Support
### Integration with Forms

- Chrome
- Firefox
- Safari
- Edge (latest versions)
Automatically include ad click data in your form submissions for attribution.

```javascript
document.querySelector('#leadForm').addEventListener('submit', (event) => {
const tracker = initTracker({
clickIdConfigs: [
{ name: 'gclid' },
{ name: 'fbclid' },
{ name: 'ttclid' },
{ name: 'msclkid' }
]
})

const latestClicks = tracker.get(true)

// Add hidden fields to your form with click data
Object.entries(latestClicks).forEach(([source, clicks]) => {
if (clicks.length > 0) {
const hiddenField = document.createElement('input')
hiddenField.type = 'hidden'
hiddenField.name = source
hiddenField.value = clicks[0].value
event.target.appendChild(hiddenField)
}
})
})
```

**Requirements:**
- localStorage support
- Modern browsers
## Browser Support

**Note:** Internet Explorer 11 is not supported
AdsClickTracker works in all modern browsers that support localStorage and ES6 features. For older browsers, consider using a transpiler like Babel.

## 📜 License
## License

MIT License
MIT

## 🤝 Contributing

Expand Down
1 change: 1 addition & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export default antfu(
{
ignores: [
'pnpm-workspace.yaml',
'README.md',
],
type: 'lib',
pnpm: true,
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@analytics-debugger/ads-click-tracker",
"type": "module",
"version": "0.0.1-beta.1",
"version": "0.0.1-beta.2",
"packageManager": "pnpm@10.6.2",
"description": "Library to keep track of clickIds from different advertising platforms",
"author": "David Vallejo <thyngster@gmail.com>",
Expand Down
Loading
Loading