Developer Tools Web Analytics 1 min read

Stop Paying Google Analytics! Deploy Traffic Source in One Click

B
Bright Coding
Author
Share:
Stop Paying Google Analytics! Deploy Traffic Source in One Click
Advertisement

Stop Paying Google Analytics! Deploy Traffic Source in One Click

What if I told you that every pageview you track in Google Analytics is being monetized against you? That the "free" tool dominating the market is actually one of the most expensive decisions your business can make — not in dollars, but in data sovereignty, privacy compliance nightmares, and the slow erosion of trust with your own visitors.

Here's the painful truth developers and founders face daily: you build something remarkable, pour your soul into the product, then hand over your most valuable asset — user behavior data — to Google's advertising machine. GDPR consent banners. Cookie banners destroying conversion rates. Monthly bills climbing past $150 for tools like Mixpanel or Amplitude. And for what? Dashboards you barely control, sampled data at scale, and the nagging suspicion you're the product, not the customer.

But what if the alternative wasn't just cheaper — what if it was better in every dimension that matters?

Enter Traffic Source — the open-source, self-hosted analytics platform that's making experienced developers abandon Google Analytics in droves. Built by the team behind SuperDevPro, NoCode Web Scraper, and CrawlAPI, this isn't another side project. This is a battle-tested, production-ready analytics engine you deploy in one click, run on a $4 VPS, and own forever.

No monthly fees. No data sharing. No limits. And yes — it tracks conversions, affiliate revenue, and even syncs with Stripe automatically.

Ready to reclaim your data? Let's dive deep into why Traffic Source might be the most important infrastructure decision you make this year.


What is Traffic Source?

Traffic Source is an open-source, self-hosted web analytics platform with conversion tracking and affiliate management capabilities. Created by Mohd Danish and the experienced team behind multiple successful developer tools, it represents a fundamental shift in how we think about analytics infrastructure.

The project emerged from a simple observation: modern analytics has become bloated, expensive, and privacy-invasive. Small teams and indie hackers were forced to choose between "free" surveillance capitalism (Google Analytics) or prohibitively expensive SaaS tools (Mixpanel, Amplitude, Heap) that charge by event volume. Neither option served the growing movement of developers who want control, privacy, and predictable costs.

Traffic Source solves this by combining a lightweight ~3KB tracking script with a full-featured Next.js dashboard, SQLite database, and zero external dependencies. It's trending now because it hits a perfect storm of developer needs: privacy regulations making cookie-based tracking legally hazardous, the rise of self-hosted infrastructure via Railway and VPS providers, and a cultural shift toward data ownership.

The architecture is deliberately opinionated and refreshingly simple. Next.js 16 with React 19 for the frontend. SQLite with WAL mode for zero-config persistence. JWT authentication with httpOnly cookies. SASS for styling. Recharts for visualization. No Redis, no PostgreSQL cluster, no Kafka streams — just solid, boring technology that works reliably at the scale most businesses actually operate at.

This isn't trying to be the analytics tool for Netflix. It's the analytics tool for the other 99.9% of websites — and it might be exactly what you've been searching for.


Key Features That Separate Traffic Source from the Pack

Let's dissect what makes this platform genuinely compelling beyond the marketing copy:

Real-time Analytics Without the Bloat

Live visitor counts, pageviews, sessions, bounce rates, and session duration — all computed from raw hit data, not pre-aggregated samples. You see what's happening now, not 24-48 hours delayed like Google's free tier.

Traffic Source Intelligence

Beyond basic referrers, Traffic Source captures full UTM parameter decomposition (source, medium, campaign, term, content). This means you can trace exactly which Twitter thread, newsletter sponsorship, or Hacker News post drove quality traffic versus vanity visits.

Privacy-First Geo & Device Tracking

Here's where it gets technically clever. Instead of using invasive IP geolocation databases or browser fingerprinting, Traffic Source leverages Cloudflare proxy headers (cf-ipcountry, cf-ipcity). This means:

  • No storing visitor IP addresses
  • No cookies required for basic tracking
  • Geographic data derived from Cloudflare's edge network, not your server
  • GDPR compliance without consent banners for analytics

Google Search Console Integration

One-click OAuth connection that surfaces keyword data Google has but doesn't show you effectively. The "keyword explorer" view displays pages, countries, and devices for any single query — a unified view that requires three separate clicks in GSC's native interface. The system maintains 90 days of historical data and categorizes opportunities as "winners," "losers," "opportunities," and "quick wins."

Stripe Conversion Tracking (The Secret Weapon)

This is where Traffic Source transcends typical "open-source Google Analytics" clones. By polling Stripe every 60 seconds and matching payments to visitor sessions via metadata, you get revenue-attributed analytics without webhooks, without Stripe Connect, without complex infrastructure. Just pass two tracking IDs in your checkout session creation.

Affiliate Management System

Create affiliates with custom commission rates, generate shareable referral links (?ref=affiliate-slug), and provide public dashboards. When a referred visitor converts, attribution happens automatically. This replaces separate affiliate software for many use cases.

Visitor Journey Replay

Full session reconstruction showing every page viewed before conversion. Not screen recording (privacy nightmare) — but a clean timeline of navigation paths that reveals where your funnel actually breaks.


Use Cases: Where Traffic Source Absolutely Dominates

The Bootstrapped SaaS Founder

You're running a $5K MRR product on DigitalOcean. Google Analytics 4's event model confuses your team. Mixpanel wants $200/month for your volume. With Traffic Source on a $4 Hetzner VPS, you get conversion tracking, affiliate management, and Search Console integration for the cost of a coffee. The Stripe sync alone justifies migration — you finally see which content drives revenue, not just pageviews.

The Privacy-Focused Agency

Your clients are lawyers, healthcare providers, European businesses. Every Google Analytics implementation requires cookie consent banners, Data Processing Agreements, and anxiety about Schrems II rulings. Traffic Source's cookie-free tracking and self-hosted model means you deliver analytics without legal exposure. Your clients' data never touches third-party servers.

The Content-First Creator

You run multiple niche sites, a newsletter, and a YouTube channel. You need to compare performance across properties without paying per-site fees. Traffic Source's multi-site dashboard lets you track everything centrally. The UTM parameter tracking reveals which newsletter issue actually drove course sales, not just which got clicks.

The E-commerce Operator with Affiliates

You're selling digital products with a small affiliate program. Previously you needed: analytics (GA), affiliate tracking (Tapfiliate/Refersion), and revenue attribution (manual spreadsheet). Traffic Source replaces all three. Affiliates get public dashboards, you get automatic commission attribution, and the visitor journey shows you which affiliates send browsers versus buyers.


Step-by-Step Installation & Setup Guide

Traffic Source offers two deployment paths. Let's cover both exhaustively.

Option 1: Railway One-Click Deploy (Fastest)

For those who value speed over server control:

# Literally just click this button — no commands needed
# https://railway.com/deploy/traffic-source

The Railway template handles Node.js, SQLite persistence, and SSL automatically. You'll be live in under 60 seconds. This is ideal for prototyping or when you simply don't want to manage a server.

Option 2: VPS Self-Host (Recommended for Production)

Prerequisites:

  • Node.js 20+ installed
  • A VPS (Hetzner CX11 at €3.79/month or DigitalOcean Droplet at $6/month)
  • Cloudflare account (free tier sufficient)

Step 1: Clone and Install Dependencies

# Clone the repository from GitHub
git clone https://github.com/mddanishyusuf/traffic-source.git

# Enter the project directory
cd traffic-source

# Install all dependencies (Next.js, React, SQLite driver, etc.)
npm install

Step 2: Environment Configuration

# Copy the local environment template to production config
cp .env.local .env.production

Edit .env.production with your values:

# Critical: 64-character random hex string for JWT signing
# Generate with: openssl rand -hex 32
JWT_SECRET=your-random-64-char-hex-string-here-generate-with-openssl

# Token expiry — 7 days default, adjust as needed
JWT_EXPIRY=7d

# Your public domain — must match where you deploy
NEXT_PUBLIC_APP_URL=https://analytics.yourdomain.com

# SQLite database location — persists between restarts
DATABASE_PATH=./data/analytics.db

Generate a cryptographically secure secret:

# Produces a 64-character hex string (32 bytes)
openssl rand -hex 32

Step 3: Build and Launch

# Production build with static optimization
npm run build

# Start the production server on port 3000
npm start

Step 4: Cloudflare Proxy Setup (Essential for Geo Data)

  1. Add your domain to Cloudflare's free plan
  2. Create an A record pointing to your VPS IP address
  3. Enable the orange cloud icon (proxy mode) — this is critical
  4. Cloudflare now injects cf-ipcountry and cf-ipcity headers on every request

Without this step, geo tracking simply won't function. Cloudflare's proxy is the magic that enables privacy-preserving location data.

Step 5: First User Registration

Navigate to your domain. The first registration is automatically permitted and immediately becomes the admin account. Registration closes after this — there's no open signup vulnerability.

Production Hardening with PM2

# Install PM2 process manager globally
npm install -g pm2

# Start Traffic Source as a managed process
pm2 start npm --name "trafficsource" -- start

# Configure auto-start on system boot
pm2 startup

# Save current process list for restoration
pm2 save

Zero-Downtime Deployments

Traffic Source includes an atomic deployment script:

# Pulls latest code, builds in temp directory, swaps atomically, restarts PM2
npm run deploy

This prevents the "service unavailable" moments that plague basic git pull && npm run build workflows.

Nginx Reverse Proxy Configuration

server {
    listen 80;
    server_name analytics.yourdomain.com;

    location / {
        # Forward to Next.js application
        proxy_pass http://localhost:3000;
        
        # WebSocket support for real-time features
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        
        # Preserve original client information
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # Prevent stale cached responses
        proxy_cache_bypass $http_upgrade;
    }
}

With Cloudflare handling SSL termination, you can use Full (Strict) mode with an Origin CA certificate for end-to-end encryption without Let's Encrypt complexity.


REAL Code Examples from the Repository

Let's examine actual implementation patterns from Traffic Source's codebase and documentation.

Example 1: The Tracking Script Integration

After creating a site in your dashboard, embed this minimal snippet:

<!-- Place in your site's <head> section -->
<!-- 'defer' ensures non-blocking load -->
<!-- 'data-site' associates hits with your property -->
<script defer src="https://your-domain.com/t.js" data-site="YOUR_SITE_ID"></script>

That's the entire integration. The t.js script (located at public/t.js in the repo) automatically:

  • Fires pageview events on initial load
  • Intercepts pushState/popState for SPA navigation tracking
  • Captures referrer, UTM parameters, screen dimensions
  • Stores a visitor ID in localStorage (not cookies — privacy win)
  • Detects affiliate referrals via ?ref= query parameters

The ~3KB size compares favorably to Google Tag Manager's 100KB+ payload or Matomo's heavier tracker.

Example 2: Stripe Conversion Tracking Integration

This is where Traffic Source's architecture shines. In your application's checkout creation code:

// Your existing Stripe checkout session creation
const session = await stripe.checkout.sessions.create({
  // ... your standard checkout configuration
  line_items: [{ price: 'price_123', quantity: 1 }],
  mode: 'payment',
  success_url: 'https://your-site.com/success',
  
  // Traffic Source magic: attach visitor identifiers
  metadata: {
    // The visitor ID assigned by the tracking script
    ts_visitor_id: window.__ts.vid,
    // The current session identifier (function call for dynamic value)
    ts_session_id: window.__ts.sid(),
  },
});

Behind the scenes, src/lib/stripe-sync.js polls Stripe's API every 60 seconds:

// Simplified representation of the polling mechanism
// Actual implementation handles pagination, rate limits, and deduplication

async function syncStripePayments() {
  // Fetch recent checkout sessions from Stripe
  const sessions = await stripe.checkout.sessions.list({
    limit: 100,
    created: { gte: lastSyncTimestamp }
  });
  
  for (const session of sessions.data) {
    // Extract Traffic Source identifiers from metadata
    const { ts_visitor_id, ts_session_id } = session.metadata;
    
    if (ts_visitor_id) {
      // Match to existing visitor journey in SQLite
      await db.run(`
        INSERT INTO conversions 
        (visitor_id, session_id, stripe_session_id, amount, currency, created_at)
        VALUES (?, ?, ?, ?, ?, ?)
      `, [ts_visitor_id, ts_session_id, session.id, 
          session.amount_total, session.currency, new Date());
      
      // Trigger affiliate commission calculation if applicable
      await calculateAffiliateCommission(ts_visitor_id, session.amount_total);
    }
  }
}

Why this matters: Traditional conversion tracking requires webhook endpoints, signature verification, retry logic, and exposed public URLs. Traffic Source's polling approach eliminates all of this — your Stripe secret key never leaves your server, and there's no webhook infrastructure to maintain or debug when Stripe's delivery fails.

Example 3: Database Backup (Critical for Production)

# Simple timestamped backup — run via cron daily
# SQLite files are portable and self-contained
cp ./data/analytics.db ./data/analytics-backup-$(date +%Y%m%d).db

# For automated backups, add to crontab:
# 0 2 * * * cd /path/to/traffic-source && cp ./data/analytics.db ./data/analytics-backup-$(date +\%Y\%m\%d).db && find ./data -name 'analytics-backup-*.db' -mtime +30 -delete

The WAL (Write-Ahead Logging) mode ensures backups are consistent even if taken during active writes — SQLite handles this automatically.

Example 4: Project Structure Navigation

Understanding the codebase for customization:

traffic-source/
├── public/
│   └── t.js                    # The ~3KB tracking snippet served to all sites
├── scripts/
│   └── deploy.sh               # Atomic deployment: build temp → swap → restart
├── src/
│   ├── lib/
│   │   ├── db.js               # better-sqlite3 connection + migrations
│   │   ├── analytics.js        # Complex queries: funnels, retention, cohorts
│   │   ├── stripe-sync.js      # Polling logic for revenue attribution
│   │   └── withAuth.js         # API route middleware — JWT verification
│   └── pages/api/              # Next.js API routes handle all data collection
└── data/                       # Persistent SQLite storage (backup this!)

The monolithic structure is intentional — no microservices, no distributed systems complexity. A single developer can understand and modify the entire application in an afternoon.


Advanced Usage & Best Practices

Security Hardening:

  • Rotate JWT_SECRET immediately if compromised — all sessions invalidate
  • Back up data/.appkey alongside your database — it encrypts GSC credentials
  • Use CRON_SECRET to protect any custom cron endpoints from public triggering
  • Restrict VPS SSH to key-based authentication; disable password login

Performance Optimization:

SQLite with WAL mode handles surprisingly high read loads. For write-heavy sites, consider:

  • Enabling Cloudflare caching for the tracking script (t.js)
  • Using a separate read replica if you exceed ~10K pageviews/minute (rare)
  • Monitoring data/analytics.db-wal file size — automatic checkpoints manage this

Scaling the Affiliate System:

Commission calculations run synchronously on payment detection. For large affiliate programs, modify stripe-sync.js to queue these via a background job system, or simply increase the polling interval to reduce frequency.

Custom Event Tracking:

While not documented in the README, the tracking script architecture supports extension. The window.__ts global exposes the visitor ID and session functions — you can build custom event collection by POSTing to /api/collect with the same payload structure.


Comparison with Alternatives

Feature Traffic Source Google Analytics 4 Matomo (Self-hosted) Plausible Mixpanel
Self-hosted ✅ Native ❌ No ✅ Complex ✅ Simple ❌ No
Monthly Cost $4 VPS Free (data cost) $10+ VPS $9+ hosted $200+
Cookie-free ✅ Yes ❌ Required ⚠️ Optional ✅ Yes ❌ No
Stripe Revenue ✅ Built-in ❌ Manual ❌ Plugin ❌ No ❌ Manual
Affiliate System ✅ Built-in ❌ No ❌ Plugin ❌ No ❌ No
GSC Integration ✅ One-click ⚠️ Separate tool ❌ No ❌ No ❌ No
Setup Complexity 15 minutes 5 minutes 2+ hours 10 minutes 1 hour
Data Ownership ✅ Full ❌ Google ✅ Full ⚠️ Hosted ❌ Mixpanel
Script Size ~3KB ~100KB+ ~20KB ~1KB ~50KB+

When to choose Traffic Source: You want revenue attribution, affiliate management, and Search Console integration in a single self-hosted package without the bloat of Matomo or the surveillance model of Google.

When to choose alternatives: Plausible if you need absolute minimalism (but lose conversion tracking); Matomo if you need enterprise features like heatmaps; Mixpanel if you have dedicated analytics engineering resources and $500+/month budget.


FAQ

Is Traffic Source GDPR compliant without cookie banners?

Yes. The default tracking uses localStorage for visitor identification, not cookies. No personal data is stored server-side beyond aggregated analytics. However, consult your legal counsel for your specific use case — compliance depends on implementation details.

How does the Stripe integration work without webhooks?

The server polls Stripe's API every 60 seconds using your secret key, querying recent checkout sessions and matching them to visitor sessions via metadata. This is more reliable than webhooks (no delivery failures) but introduces ~60 second latency. For most businesses, this is imperceptible.

Can I track multiple websites?

Yes. The multi-site dashboard lets you create unlimited properties, each with unique data-site IDs. Perfect for agencies or creators with portfolio businesses.

What happens if my VPS goes down?

Tracking data is lost during outages — there's no client-side queue. For critical applications, implement health monitoring and consider Railway's managed option for higher availability.

How do I migrate from Google Analytics?

Export historical data via GA4's BigQuery export if needed. For Traffic Source, simply add the tracking script and begin collecting new data. There's no import tool — the philosophy is forward-looking data ownership.

Is SQLite enough for production?

For sites under ~1M pageviews/month, absolutely. SQLite with WAL mode is surprisingly capable. The better-sqlite3 driver uses synchronous, prepared statements for maximum throughput. For massive scale, you'd need to fork and add PostgreSQL support.

Can I customize the dashboard?

The codebase is standard Next.js + React. Modify components in src/components/ and styles in src/styles/. The MIT license permits any modification.


Conclusion: Own Your Data or Someone Else Will

The analytics landscape has been dominated by false choices for too long: "free" tools that monetize your visitors, or expensive SaaS platforms that penalize growth. Traffic Source explodes this dichotomy by proving you can have professional-grade analytics — with conversion tracking, affiliate management, and Search Console integration — on infrastructure that costs less than a sandwich.

The technical decisions behind this project reveal deep understanding of what developers actually need. SQLite instead of database complexity. Polling instead of webhook fragility. Cloudflare headers instead of IP geolocation databases. Every choice reduces operational burden while preserving capability.

Is it perfect? No. The polling model won't suit real-time arbitrage businesses. SQLite has scaling ceilings. The affiliate system lacks multi-tier commissions. But for the vast majority of SaaS founders, content creators, and privacy-conscious agencies, these are acceptable tradeoffs for complete data sovereignty.

The team behind SuperDevPro, CrawlAPI, and MailLayer didn't build this as a toy. They built it because they needed it themselves — and that origin story shows in every architectural decision.

Your next step is simple: Star the repository, deploy to Railway in one click, or clone to your $4 VPS tonight. Your future self — reviewing revenue-attributed analytics without a cookie banner in sight — will thank you.

The era of renting your own business intelligence is ending. The era of owning it starts with a single git clone.


Found this guide valuable? Share it with a founder still paying $200/month for analytics they don't control. And don't forget to watch the repository for updates — the roadmap includes enhanced funnel visualization and BigQuery export options.

Advertisement

Comments (0)

No comments yet. Be the first to share your thoughts!

Leave a Comment

Apps & Tools Open Source

Apps & Tools Open Source

Bright Coding Prompt

Bright Coding Prompt

Categories

Advertisement
Advertisement