Counterscale Documentation

repository·main·Indexed 24 days ago

https://github.com/benvinegar/counterscale

A self-hosted web analytics solution designed for Cloudflare Workers, featuring a dashboard and a tracker for recording web traffic. Includes documentation for the @counterscale/cli for deployment and authentication management, the @counterscale/tracker for client-side and server-side pageview tracking, and @counterscale/eslint-config for project linting.

Tokens
12.9K
Snippets
21
Records
88
Agent score
83%

What's inside Counterscale

  1. Understand the differences between server-side and client-side trackers

    main

    The @counterscale/tracker/server module behaves differently than the browser-based client-side version:

    • No DOM dependency: It does not include auto-tracking or browser instrumentation.
    • Fetch API: Uses native fetch instead of XMLHttpRequest (requires Node.js 18+).
    • No Cache Checks: Does not perform cache status checks.
    • Explicit Parameters: Requires explicit url and hostname parameters.
    • Hit Type: Always reports hit type as "1" (new visit) because server-side tracking cannot maintain browser session state.
    • Fire-and-forget: Tracking is designed to be non-blocking; errors will not throw exceptions that crash the process.
  2. Track web traffic using the Script Loader (CDN)

    main

    The easiest way to start recording traffic is to include the tracker.js script directly in your HTML. The script is served from your deployed Counterscale URL.

    Copy and paste this snippet into your website's HTML, replacing the placeholders with your actual subdomain and site ID:

    <script
        id="counterscale-script"
        data-site-id="your-unique-site-id"
        src="https://{subdomain-emitted-during-deploy}.workers.dev/tracker.js"
        defer
    ></script>
  3. Advanced usage of @counterscale/eslint-config with granular control

    main

    If you need more granular control over your ESLint setup, you can import and compose individual configuration functions instead of using the monolithic createConfig. This allows you to layer specific configurations (Base, React, or TypeScript) and add your own custom rules.

    Available configuration functions:

    • createBaseConfig: Provides the foundational configuration.
    • createReactConfig: Adds React-specific rules and settings.
    • createTypeScriptConfig: Adds TypeScript-specific rules and settings.

    Note: When using these functions, you can pass specific options like baseDirectory, tsconfigRootDir, and project to each one individually.

    import {
        createBaseConfig,
        createTypeScriptConfig,
        createReactConfig,
    } from "@counterscale/eslint-config";
    import path from "node:path";
    import { fileURLToPath } from "node:url";
    
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    
    export default [
        ...createBaseConfig({
            baseDirectory: __dirname,
            ignores: ["build/*", "node_modules", "dist/*"],
            additionalGlobals: { counterscale: true },
        }),
        ...createReactConfig({ baseDirectory: __dirname }),
        ...createTypeScriptConfig({
            baseDirectory: __dirname,
            tsconfigRootDir: "./",
            project: "./tsconfig.json",
        }),
        // Add any package-specific rules
        {
            files: ["**/*.{ts,tsx}"],
            rules: {
                // Your custom rules here
            },
        },
    ];
  4. Initialize Counterscale for automatic pageview tracking

    main

    Initialize the tracker by calling init() with your siteId and your deployed deploymentUrl. By default, Counterscale automatically tracks pageview events once initialized.

    import * as Counterscale from "@counterscale/tracker";
    
    Counterscale.init({
        siteId: "your-unique-site-id",
        deploymentUrl: "https://{subdomain-emitted-during-deploy}.pages.dev/",
    });
  5. Manually track pageviews in @counterscale/tracker

    main

    If you need fine-grained control over when pageviews are recorded (for example, in Single Page Applications), disable automatic tracking by setting autoTrackPageviews: false in the init configuration. You can then trigger a pageview manually using Counterscale.trackPageview().

    import * as Counterscale from "@counterscale/tracker";
    
    Counterscale.init({
        siteId: "your-unique-site-id",
        deploymentUrl: "https://{subdomain-emitted-during-deploy}.pages.dev/",
        autoTrackPageviews: false, // <- don't forget this
    });
    
    // ... when a pageview happens
    Counterscale.trackPageview();
  6. Standard usage of @counterscale/eslint-config

    main

    To use the standard Counterscale ESLint configuration, create an eslint.config.mjs file in your package and use the createConfig function. This function accepts an options object to configure the environment, including directory paths, ignores, and support for React or TypeScript.

    Key configuration options:

    • baseDirectory: The directory to use as the base for configuration.
    • ignores: An array of patterns to ignore (e.g., build/*, node_modules).
    • includeReact: Set to true to enable React-specific configurations.
    • includeTypeScript: Set to true to enable TypeScript-specific configurations.
    • tsconfigRootDir: The root directory for TypeScript configuration.
    • project: The path to your tsconfig.json.
    • additionalGlobals: An object defining package-specific global variables.
    import { createConfig } from "@counterscale/eslint-config";
    import path from "node:path";
    import { fileURLToPath } from "node:url";
    
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    
    export default createConfig({
        baseDirectory: __dirname,
        ignores: [
            "build/*",
            "node_modules",
            "dist/*",
            // Add any package-specific ignores
        ],
        // Configure based on package type
        includeReact: true, // Set to true for React packages
        includeTypeScript: true, // Set to true for TypeScript packages
        tsconfigRootDir: "./",
        project: "./tsconfig.json", // Path to your tsconfig.json
        additionalGlobals: {
            // Add any package-specific globals
            counterscale: true,
        },
    });
  7. Install and deploy Counterscale

    main

    To deploy Counterscale to Cloudflare, follow these steps:

    1. Requirements Check:
      • macOS or Linux environment
      • Node v20 or above
      • An active Cloudflare account
    2. Cloudflare Preparation:
    3. Deployment:
      • Log in to Cloudflare via Wrangler:
        npx wrangler login
      • Run the installer:
        npx @counterscale/cli@latest install
      • Follow the prompts to provide your API token and choose whether to protect your dashboard with a password.

    Once finished, your server will be available at https://{subdomain}.workers.dev.

    npx wrangler login
    npx @counterscale/cli@latest install
  8. Understand how Counterscale handles deployment configuration

    main

    When deploying, Counterscale stages a local copy of the wrangler.json configuration file into the ~/.counterscale directory.

    To ensure the wrangler deploy command can be executed from any working directory, the CLI performs the following transformations on the configuration:

    1. Path Absolute-ization: All relative paths within the configuration object are converted to absolute paths relative to the @counterscale/server package directory.
    2. Worker Identity: The name field is updated to the specified workerName.
    3. Dataset Mapping: The first entry in the analytics_engine_datasets array is updated with the provided analyticsDataset name.
    4. Account Association: If an accountId is provided, it is added to the configuration object.