StatCounter Analytics: Tracking Code and API Guide | OpsBlu Docs

StatCounter Analytics: Tracking Code and API Guide

Technical guide to StatCounter installation, sc_project/sc_security globals, summary stats API, exit link tracking, and Magnify session recording.

How StatCounter Works

StatCounter is a page-counter-based analytics platform that tracks visitors using a JavaScript beacon. Each pageview sends a hit to StatCounter's servers containing the visitor's IP, user agent, referrer, screen resolution, and page URL. Data is processed in real-time and stored in two tiers:

  • Summary Statistics -- Aggregated counts (visitors, pageviews, popular pages, referrers, keywords) retained indefinitely regardless of plan.
  • Visitor Log -- Individual visitor records with full session details. The log stores a rolling window of recent pageviews (500 on the free plan, up to 2.5M on paid plans). Older entries are evicted as new ones arrive.

The data model tracks:

  • Visitors -- Identified by a cookie (is_unique) or IP+UA fingerprint. Returning visitors are detected across sessions.
  • Pageviews -- Each page load triggers a hit. StatCounter records the URL, page title, referrer, timestamp, and visitor metadata.
  • Exit Links -- Outbound link clicks are tracked when visitors navigate away from your site to an external URL.
  • Downloads -- File download events for specific extensions (PDF, ZIP, EXE, etc.).
  • Keywords -- Search engine queries that led visitors to your site (limited by search engine referrer data availability).

StatCounter also offers Magnify, a session recording feature that captures visitor mouse movements, clicks, and scrolling for visual playback.


Installing the Tracking Script

Standard Installation

StatCounter generates a project-specific tracking code. The two critical global variables are sc_project (your numeric project ID) and sc_security (a security hash):

<!-- StatCounter Code -->
<script type="text/javascript">
var sc_project=YOUR_PROJECT_ID;
var sc_invisible=1;
var sc_security="YOUR_SECURITY_CODE";
</script>
<script type="text/javascript"
src="https://www.statcounter.com/counter/counter.js" async></script>
<noscript><div class="statcounter"><a title="Web Analytics"
href="https://statcounter.com/" target="_blank"><img class="statcounter"
src="https://c.statcounter.com/YOUR_PROJECT_ID/0/YOUR_SECURITY_CODE/1/"
alt="Web Analytics"></a></div></noscript>

Configuration variables:

Variable Type Description
sc_project Number Your StatCounter project ID
sc_security String Security hash for the project
sc_invisible Number 1 = invisible counter (no badge), 0 = visible counter
sc_https Number 1 = force HTTPS beacon (default on HTTPS pages)
sc_remove_link Number 1 = remove the StatCounter link from noscript fallback
sc_text Number 1 = use text link instead of image badge

WordPress Installation

Install via the official StatCounter plugin:

  1. Install "StatCounter - Free Real Time Visitor Stats" from the WordPress plugin directory.
  2. Enter your sc_project and sc_security values in the plugin settings.
  3. The plugin injects the tracking code into every page.

Alternatively, add the code manually to your theme's footer.php or use a code snippets plugin.

Single-Page Applications

StatCounter does not natively detect SPA route changes. For frameworks like React, Vue, or Angular, re-trigger the counter on navigation:

// After SPA route change
function trackStatCounterPageview() {
  if (window.sc_project) {
    var img = new Image();
    img.src = "https://c.statcounter.com/" + sc_project + "/0/" + sc_security + "/1/?t=" + Date.now() + "&u=" + encodeURIComponent(window.location.href) + "&r=" + encodeURIComponent(document.referrer);
  }
}

// React Router example
useEffect(() => {
  trackStatCounterPageview();
}, [location.pathname]);

This sends a pixel request manually, simulating a fresh page load for StatCounter's counter.


Event Tracking and Data Collection

StatCounter automatically tracks clicks on external links (links pointing to domains other than your own). Exit links appear in the dashboard under Exit Links with the destination URL, click count, and the page the visitor was on when they clicked.

No additional code is required. StatCounter's JavaScript intercepts click events on <a> tags with external href values and logs them before the navigation occurs.

Download Tracking

File downloads are tracked automatically for common extensions: .pdf, .zip, .exe, .doc, .xls, .ppt, .mp3, .mp4, .avi, .mov, .dmg, .rar, .gz, .tar.

When a visitor clicks a link to a file with a tracked extension, StatCounter logs it as a download event. Download stats appear under Downloads in the dashboard.

Keyword Analysis

StatCounter records search engine keywords from referrer URLs when available. Due to search engine encryption ("not provided" in Google), keyword data is increasingly limited. StatCounter still captures keywords from:

  • Bing
  • DuckDuckGo
  • Yahoo
  • Regional search engines
  • Google (when referrer data is present, primarily from ads)

Keywords are accessible in the Keyword Analysis section with search volume, trends over time, and the landing pages visitors arrived at.

StatCounter ranks pages by view count. The Popular Pages report shows:

  • Total pageviews and unique visitors per page
  • Entry pages (first page of a visit)
  • Exit pages (last page before leaving)
  • Bounce rate per page
  • Average time on page

Identity and User Tracking

StatCounter sets an is_unique cookie to distinguish new and returning visitors. The cookie has a configurable expiration (default: 1 year). When the cookie is present, StatCounter marks the visit as a returning visitor.

Returning Visitor Tracking

The Returning Visitors report shows visitors who have come back to your site, including:

  • Number of previous visits
  • Time since last visit
  • Pages viewed across visits
  • Referrer for each visit

This data relies on the is_unique cookie. Visitors who clear cookies or use private browsing appear as new visitors.

IP Address Tracking

By default, StatCounter logs visitor IP addresses in the visitor log. IP-based geolocation determines country, region, and city. For privacy compliance, enable IP anonymization in project settings to mask the last octet.

No Custom User ID

StatCounter does not provide a JavaScript API to set a custom user identifier (like a database user ID). Visitor identity is purely cookie and IP based. There is no equivalent to posthog.identify() or clarity("identify", ...).


API and Data Export

Summary Stats API

StatCounter provides an XML API for retrieving summary statistics:

# Base URL
# https://api.statcounter.com/stats/

# Authentication: username + password or API key via query parameters

# Get summary stats for a project
curl "https://api.statcounter.com/stats/?vn=3&s=summary&pi=YOUR_PROJECT_ID&u=YOUR_USERNAME&t=YOUR_API_KEY&f=json&sd=30"

Parameters:

Param Description
vn API version (use 3)
s Stat type: summary, popular, entry, exit, came-from, keyword, recent-keyword, country, recent-visitor, browser, os, exit-link, download-link
pi Project ID
u StatCounter username
t API key (from Account > API)
f Format: json or xml
sd Number of days to include (e.g., 7, 30)
n Number of results to return
g Granularity: daily, weekly, monthly, quarterly, yearly

Common API Queries

# Popular pages (top 20, last 30 days)
curl "https://api.statcounter.com/stats/?vn=3&s=popular&pi=PROJECT_ID&u=USER&t=KEY&f=json&sd=30&n=20"

# Traffic by country (last 7 days)
curl "https://api.statcounter.com/stats/?vn=3&s=country&pi=PROJECT_ID&u=USER&t=KEY&f=json&sd=7"

# Browser breakdown (last 30 days)
curl "https://api.statcounter.com/stats/?vn=3&s=browser&pi=PROJECT_ID&u=USER&t=KEY&f=json&sd=30"

# Exit links (last 7 days)
curl "https://api.statcounter.com/stats/?vn=3&s=exit-link&pi=PROJECT_ID&u=USER&t=KEY&f=json&sd=7"

# Recent visitors (last 100)
curl "https://api.statcounter.com/stats/?vn=3&s=recent-visitor&pi=PROJECT_ID&u=USER&t=KEY&f=json&n=100"

CSV Export

The StatCounter dashboard provides CSV export for all report types. Navigate to any report and click the Export button. Exports include the full date range and all rows visible in the report.


Common Issues

Tracking Code Not Counting

Verify the JavaScript loads by checking DevTools > Network for requests to statcounter.com. Common causes:

  • Missing sc_project or sc_security: Both globals must be defined before counter.js loads. If either is undefined, the script silently fails.
  • Ad blockers: StatCounter is blocked by most ad blockers and privacy extensions (uBlock Origin, Privacy Badger). This is the primary cause of count discrepancies vs. server-side logs.
  • HTTPS mixed content: If your site is HTTPS but the StatCounter code uses HTTP URLs, browsers will block the request. Use the HTTPS version of all StatCounter URLs.

Visitor Log Shows Fewer Visits Than Summary

This is expected behavior. The summary stats count all pageviews, but the visitor log only retains the most recent N entries based on your plan (500 for free, up to 2.5M for paid). Once the log is full, the oldest entries are removed. Summary stats are unaffected.

Magnify (Session Recording) Not Working

Magnify must be explicitly enabled per project in StatCounter settings. It is a paid-plan feature. After enabling, recordings appear within 24 hours. Verify that the standard tracking code is loading correctly, as Magnify piggybacks on the same JavaScript.

Bot Traffic Inflating Counts

StatCounter applies basic bot filtering using known bot signatures. However, sophisticated bots and headless browsers may bypass detection. If you notice suspicious traffic spikes, check the visitor log for patterns: identical user agents, sequential IP addresses, or impossibly fast page navigation. You can exclude specific IPs in project settings under Blocking.

API Authentication Errors

The API requires your StatCounter username and API key (not your password). Generate an API key at Account > API Key. If you receive authentication errors, verify that:

  • The username is your StatCounter login email
  • The API key matches (not your account password)
  • The project ID belongs to your account

Platform-Specific Considerations

Magnify Session Recording

Magnify records visitor mouse movements, clicks, and scrolling on your pages. Recordings play back as a video overlay on your site's DOM. Key details:

  • Recordings are available for 30 days
  • Only a subset of sessions are recorded (sampling rate depends on traffic volume)
  • Sensitive form fields are masked by default
  • Recordings are accessible in the dashboard under Magnify
  • Requires a paid plan (Silver or higher)

GlobalStats Public Data

StatCounter publishes aggregated browser, OS, and device market share data at gs.statcounter.com. This data is derived from the StatCounter network (billions of pageviews across millions of sites) and is widely cited in industry reports. It is separate from your project analytics.

Invisible vs. Visible Counter

Setting sc_invisible=1 hides the StatCounter badge from your page. Setting it to 0 displays a visible hit counter badge (the classic "you are visitor #12345" widget). Most modern sites use invisible mode.

Multiple Projects

A single StatCounter account can host multiple projects (one per website). Each project has its own sc_project and sc_security values. The dashboard provides a project switcher for managing multiple sites.

Data Retention

Summary statistics (aggregate counts) are retained indefinitely on all plans. The detailed visitor log has a rolling retention window based on plan tier:

Plan Log Size
Free 500 pageviews
Bronze 5,000 pageviews
Silver 25,000 pageviews
Gold 100,000 pageviews
Platinum 500,000 pageviews
Diamond 2,500,000 pageviews