Simple Analytics Troubleshooting | OpsBlu Docs

Simple Analytics Troubleshooting

Troubleshoot and debug Simple Analytics issues — common errors, data discrepancies, and step-by-step diagnostic procedures.

Diagnose and resolve common Simple Analytics tracking issues. This guide covers script installation verification, data collection problems, event tracking errors, and API integration challenges.

Diagnostic Tools

Browser Developer Console

Check Script Loading:

  1. Open DevTools (F12 or Cmd+Option+I)
  2. Navigate to Network tab
  3. Filter for "simpleanalytics"
  4. Reload page
  5. Verify latest.js loads with 200 status

Console Debugging:

Check if Simple Analytics loaded successfully:

// In browser console
console.log(typeof sa_event);
// Should output: "function"

console.log(typeof window.sa_loaded);
// Should output: "boolean" (true if loaded)

Test Pageview Tracking

Manual Pageview Test:

// Open console and run:
window.sa_event('test_pageview');

// Check for network request to:
// queue.simpleanalyticscdn.com/events

Real-Time Verification

Dashboard Check:

  1. Log into Simple Analytics
  2. View your website dashboard
  3. Open your site in another tab/window
  4. Pageview should appear within 5-10 seconds
  5. Check "Live visitors" indicator

No Data Appearing

Script Not Loading

Symptoms:

  • Dashboard shows zero pageviews
  • Script not visible in Network tab
  • No console errors

Diagnostic Steps:

  1. Verify script tag installation:

    <script async defer src="https://scripts.simpleanalyticscdn.com/latest.js"></script>
    <noscript><img src="https://queue.simpleanalyticscdn.com/noscript.gif" alt="" referrerpolicy="no-referrer-when-downgrade" /></noscript>
    
  2. Check script placement - Should be in <head> or before </body>

  3. Validate domain name - Must match exactly (with or without www)

  4. Test in incognito mode - Rules out extension interference

Common Causes:

Content Security Policy (CSP) Blocking:

Add to CSP header:

script-src 'self' https://scripts.simpleanalyticscdn.com;
connect-src 'self' https://queue.simpleanalyticscdn.com;
img-src 'self' https://queue.simpleanalyticscdn.com;

Ad Blockers:

Simple Analytics is blocked by some ad blockers despite being privacy-friendly.

Test:

  1. Disable ad blocker
  2. Clear browser cache
  3. Reload page
  4. Check if data appears

Workaround - Use custom domain (Business plan):

<script async defer src="https://analytics.yourdomain.com/latest.js"></script>

HTTPS Required:

Simple Analytics only works on HTTPS sites. HTTP sites won't send data.

Verify:

Domain Not Added

Symptoms:

  • Script loads but no data appears
  • Console error: "Website not found"

Resolution:

  1. Log into Simple Analytics dashboard
  2. Click "Add website"
  3. Enter exact domain (match www/non-www usage)
  4. Click "Add website"
  5. Wait 1-2 minutes for DNS propagation
  6. Refresh your site

Domain Matching:

Ensure hostname matches exactly:

  • If site is www.example.com, add www.example.com
  • If site is example.com (no www), add example.com
  • Subdomains require separate entries: blog.example.com

Cached HTML

Symptoms:

  • Script added recently
  • No data collecting
  • Old HTML served

Resolution:

  1. Clear CDN cache (if using Cloudflare, AWS CloudFront, etc.)
  2. Purge server cache (WordPress cache plugins, Varnish, etc.)
  3. Hard refresh browser (Ctrl+Shift+R or Cmd+Shift+R)
  4. Check HTML source - Verify script tag present in raw HTML

Events Not Tracking

sa_event Function Not Defined

Symptoms:

  • Console error: sa_event is not defined
  • Custom events don't appear

Cause: Event tracking called before Simple Analytics script loads.

Solution:

Wait for script ready:

// Incorrect - may fire before script loads
sa_event('signup');

// Correct - wait for load
window.addEventListener('load', function() {
  if (typeof sa_event === 'function') {
    sa_event('signup');
  }
});

// Or check in function
function trackEvent(eventName) {
  if (typeof sa_event === 'function') {
    sa_event(eventName);
  } else {
    console.warn('Simple Analytics not loaded');
  }
}

For SPAs (React, Vue, etc.):

// Create helper function
function safeTrackEvent(eventName, metadata) {
  return new Promise((resolve) => {
    const maxAttempts = 20;
    let attempts = 0;

    const checkAndTrack = setInterval(() => {
      attempts++;

      if (typeof sa_event === 'function') {
        sa_event(eventName, metadata);
        clearInterval(checkAndTrack);
        resolve(true);
      }

      if (attempts >= maxAttempts) {
        clearInterval(checkAndTrack);
        console.warn('Simple Analytics not loaded after 2 seconds');
        resolve(false);
      }
    }, 100);
  });
}

// Usage
safeTrackEvent('button_click', { location: 'header' });

Incorrect Event Syntax

Valid Formats:

// Simple event
sa_event('button_click');

// Event with metadata
sa_event('purchase', {
  amount: 99.99,
  currency: 'USD',
  product: 'Pro Plan'
});

// Event with callback
sa_event('form_submit', {}, function() {
  console.log('Event tracked');
});

Common Errors:

// Wrong - missing function name
window.simpleAnalytics('event_name');

// Wrong - incorrect parameter order
sa_event({ metadata: 'value' }, 'event_name');

// Wrong - using array instead of object
sa_event('event', ['value1', 'value2']);

Events Not Appearing in Dashboard

Diagnostic:

  1. Check event name format

    • Use lowercase with underscores: button_click
    • Avoid spaces and special characters
    • Max length: 100 characters
  2. Verify metadata structure

    • Must be valid JavaScript object
    • Values should be strings or numbers
    • Avoid nested objects (flatten data)
  3. Check browser console for errors

    sa_event('test_event', { test: true });
    // Watch Network tab for request to queue.simpleanalyticscdn.com/events
    
  4. Wait for processing

    • Events appear in dashboard within 1-2 minutes
    • Refresh dashboard after tracking event
    • Check "Events" tab (not "Pages" tab)

Single Page Application (SPA) Issues

Only First Page Tracked

Symptoms:

  • Initial page load tracked
  • Navigation within app not counted
  • URL changes don't trigger pageviews

Cause: SPAs don't trigger full page reloads.

Solution:

Track route changes manually.

React (React Router):

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function usePageTracking() {
  const location = useLocation();

  useEffect(() => {
    if (typeof sa_event === 'function') {
      sa_event('pageview');
    }
  }, [location]);
}

// In App component
function App() {
  usePageTracking();
  return <Router>...</Router>;
}

Vue (Vue Router):

// router/index.js
router.afterEach((to, from) => {
  if (typeof sa_event === 'function') {
    sa_event('pageview');
  }
});

Next.js:

import { useRouter } from 'next/router';
import { useEffect } from 'react';

export default function App({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    const handleRouteChange = () => {
      if (typeof sa_event === 'function') {
        sa_event('pageview');
      }
    };

    router.events.on('routeChangeComplete', handleRouteChange);
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

  return <Component {...pageProps} />;
}

Angular:

import { Router, NavigationEnd } from '@angular/router';

constructor(private router: Router) {
  this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
      if (typeof (window as any).sa_event === 'function') {
        (window as any).sa_event('pageview');
      }
    }
  });
}

API Integration Issues

Authentication Failures

Error: "Invalid API key"

Resolution:

  1. Verify API key is correct
  2. Check for extra spaces or line breaks
  3. Ensure key has required permissions
  4. Try regenerating API key

Generate New Key:

  1. Dashboard → Account → API Keys
  2. Click "Create new key"
  3. Select permissions (read/write)
  4. Copy new key
  5. Update application configuration

Test API Key:

curl "https://simpleanalytics.com/api/websites/example.com/stats" \
  -H "Api-Key: YOUR_KEY"

Should return JSON data, not error.

Rate Limiting

Error: HTTP 429 "Too Many Requests"

Limits:

  • 100 requests per minute
  • 10,000 requests per day

Response Headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640995200

Solution:

Implement rate limit handling:

async function fetchStats(domain, retries = 3) {
  try {
    const response = await fetch(
      `https://simpleanalytics.com/api/websites/${domain}/stats`,
      {
        headers: { 'Api-Key': API_KEY }
      }
    );

    if (response.status === 429) {
      const resetTime = response.headers.get('X-RateLimit-Reset');
      const waitMs = (parseInt(resetTime) * 1000) - Date.now();

      if (retries > 0 && waitMs > 0) {
        await new Promise(resolve => setTimeout(resolve, waitMs));
        return fetchStats(domain, retries - 1);
      }

      throw new Error('Rate limit exceeded');
    }

    return await response.json();
  } catch (error) {
    console.error('API Error:', error);
    throw error;
  }
}

Best Practices:

  • Cache API responses
  • Batch requests when possible
  • Add delays between requests
  • Monitor rate limit headers
  • Implement exponential backoff

CORS Errors

Error: "Blocked by CORS policy"

Cause: Browser blocks cross-origin API requests.

Solution:

Make API calls from server-side (not browser):

// Server-side (Node.js)
const fetch = require('node-fetch');

app.get('/api/stats', async (req, res) => {
  const response = await fetch(
    'https://simpleanalytics.com/api/websites/example.com/stats',
    {
      headers: { 'Api-Key': process.env.SA_API_KEY }
    }
  );

  const data = await response.json();
  res.json(data);
});

Data Discrepancies

Differences from Google Analytics

Expected Variations:

  • Ad blocker bypass - Simple Analytics blocked less frequently
  • Bot filtering - Different bot detection algorithms
  • Cookie-less tracking - No cross-visit identification
  • Privacy features - Respects Do Not Track
  • Session definition - 30-minute default vs GA's complex rules

Validation:

Compare like-to-like metrics:

  • Pageviews to Pageviews (not Sessions)
  • Unique visitors to Users
  • Same date ranges and timezones
  • Consider sampling in GA4

Missing Referrer Data

Symptoms:

  • Most traffic shows as "Direct"
  • Referrers appear blank

Causes:

  1. HTTPS to HTTP - Browsers strip referrer for security
  2. Referrer-Policy header - Restricts referrer transmission
  3. Privacy browsers - Brave, Firefox strict mode limit referrers
  4. Link rel="noreferrer" - Explicitly removes referrer

Workaround:

Use UTM parameters for campaign tracking:

https://example.com/page?utm_source=newsletter&utm_medium=email&utm_campaign=launch

Performance Issues

Slow Page Load

Check Script Impact:

  1. Open DevTools → Network tab
  2. Note latest.js file size (~3KB)
  3. Check loading time (should be under 100ms)
  4. Verify async defer attributes present

Optimization:

<!-- Optimal loading -->
<script async defer src="https://scripts.simpleanalyticscdn.com/latest.js"></script>

<!-- NOT recommended - blocks rendering -->
<script src="https://scripts.simpleanalyticscdn.com/latest.js"></script>

CDN Issues:

If script loads slowly:

  1. Check simpleanalyticscdn.com status
  2. Try different network connection
  3. Check DNS resolution time
  4. Consider custom domain (Business plan)

High Event Volume

Issue: Thousands of events cause dashboard slowness.

Solution:

  1. Reduce event frequency

    • Throttle scroll/mouse events
    • Sample high-volume events
    • Aggregate similar events
  2. Use metadata efficiently

    • Combine related data in single event
    • Avoid separate events for each variation
  3. Example throttling:

    let lastScrollEvent = 0;
    const THROTTLE_MS = 1000;
    
    window.addEventListener('scroll', function() {
      const now = Date.now();
      if (now - lastScrollEvent > THROTTLE_MS) {
        sa_event('scroll', {
          depth: Math.round(window.scrollY / document.body.scrollHeight * 100)
        });
        lastScrollEvent = now;
      }
    });
    

Getting Support

Debug Checklist

Before contacting support, verify:

  1. Script tag installed correctly
  2. Domain added to Simple Analytics dashboard
  3. HTTPS enabled on site
  4. No ad blockers active (for testing)
  5. Console shows no JavaScript errors
  6. Network tab shows script loading
  7. Waited 5+ minutes for data processing

Gather Information

When reporting issues, include:

  • Website URL
  • Dashboard domain name
  • Browser and version
  • Console errors (screenshot)
  • Network tab (showing simpleanalytics requests)
  • Steps to reproduce
  • Expected vs actual behavior

Support Channels

Community Resources

Preventative Monitoring

Set Up Alerts

Monitor with OpsBlu:

Configure automated checks:

  • Verify script presence on all pages
  • Monitor data collection continuity
  • Alert on tracking failures
  • Validate event tracking

Regular Health Checks

Weekly:

  • Review pageview trends for anomalies
  • Check event tracking still functioning
  • Verify API integrations working
  • Monitor dashboard load times

Monthly:

  • Audit custom events
  • Review referrer sources
  • Check for JavaScript errors
  • Validate cross-domain tracking (if applicable)

Testing New Implementations

Pre-Deployment Checklist:

  1. Test in staging environment
  2. Verify script loads on all page types
  3. Test custom events fire correctly
  4. Check SPA route tracking
  5. Validate with multiple browsers
  6. Test with ad blockers disabled
  7. Monitor for console errors

Post-Deployment:

  1. Monitor real-time dashboard for first hour
  2. Compare pageview counts to previous period
  3. Verify events appearing correctly
  4. Check for error rate spikes
  5. Validate referrer data collecting