How the Plausible JavaScript Tracker Is Compiled and Served Dynamically

The Plausible JavaScript tracker is compiled into a minified static bundle at build time, then dynamically injected with per-site configuration at request time through a placeholder replacement system before being served by an Elixir Plug.

The Plausible analytics platform generates its lightweight tracking script using a hybrid approach that combines compile-time optimization with runtime customization. According to the plausible/analytics source code, the tracker is bundled and minified ahead of deployment, then personalized for each site when requested through a high-performance Elixir endpoint.

Compile-Time Bundling and Minification

The build process begins with tracker/compile.js, which orchestrates the entire compilation pipeline by invoking the core compiler logic in tracker/compiler/index.js. This system processes the raw ES module source code and produces deployment-ready artifacts.

Entry Points and Build Tools

The compilation starts at tracker/src/plausible.js, which serves as the entry point for the bundler. Rollup processes the ES-module dependency graph, configured with @rollup/plugin-json to handle JSON imports. After bundling, SWC (@swc/core) minifies the output with aggressive dead-code elimination. Global flags such as COMPILE_PLAUSIBLE_WEB are passed to the minifier to strip unused code paths, ensuring the final bundle remains lightweight.

The resulting files are written to priv/tracker/js/, typically as plausible-web.js (and variant files for different deployment scenarios).


# Compile all tracker variants to priv/tracker/js/

node tracker/compile.js

# Generate a complete embeddable script tag

node tracker/compile.js --web-snippet > public/plausible.js

Generating Web Snippets

When the --web-snippet flag is provided, the compiler calls compileWebSnippet() defined in tracker/compiler/index.js. This function reads src/web-snippet.js, minifies the code, and wraps it in a complete HTML script tag ready for embedding:

// tracker/compiler/index.js
export function compileWebSnippet() {
  const code = fs.readFileSync(relPath('../src/web-snippet.js')).toString()
  return `
<script>
  ${minify(code)}
  plausible.init()
</script>
  `
}

Dynamic Configuration Injection

While the JavaScript bundle is static, the final script served to each website is dynamically customized. The compiled file contains a specific placeholder string "<%= @config_js %>" that marks where site-specific settings will be inserted.

Placeholder Replacement Strategy

When a browser requests the tracker, PlausibleWeb.Tracker.build_script/1 in lib/plausible_web/tracker.ex reads the pre-compiled template stored in the module attribute @plausible_main_script. It constructs a compact JSON-like configuration fragment from the site's TrackerScriptConfiguration struct—containing values like domain, endpoint URL, and outbound-link flags—and performs an in-memory string replacement:


# lib/plausible_web/tracker.ex

def build_script(%TrackerScriptConfiguration{} = cfg) do
  config_js_content =
    cfg
    |> plausible_main_config()
    |> Enum.flat_map(fn
      {k, v} when is_binary(v) -> ["#{k}:#{JSON.encode!(v)}"]
      {k, true}                -> ["#{k}:!0"]
      {_k, false}              -> []
    end)
    |> Enum.sort_by(&String.length/1, :desc)
    |> Enum.join(",")

  @plausible_main_script
  |> String.replace('" <%= @config_js %> "', "{#{config_js_content}}")
end

This substitution happens entirely in memory, allowing the same static asset to serve unlimited site configurations without filesystem writes or redundant builds.

Configuration Structure

The configuration object uses JavaScript minification-friendly syntax: boolean true values become !0 (shorter than true), and falsy values are omitted entirely to save bytes. The keys are sorted by string length in descending order to optimize gzip compression.

Serving the Script with Elixir Plug

The final delivery is handled by PlausibleWeb.TrackerPlug, which returns the generated script with the proper Content-Type: application/javascript header.

CDN Caching and Performance Optimization

In SaaS (Enterprise Edition) deployments, the Plug integrates with TrackerScriptIdCache and TrackerScriptCache to avoid regenerating scripts for known configuration IDs. When a request arrives, the Plug checks these caches first; if the script has been generated previously, it returns the cached version immediately. This strategy makes the endpoint highly CDN-friendly, as the same configuration ID always resolves to the identical script content:


# Simplified view of PlausibleWeb.TrackerPlug

def call(conn, _opts) do
  script = PlausibleWeb.Tracker.get_plausible_main_script(id, cache_opts)
  send_resp(conn, 200, script)
end

Summary

  • Static compilation: The tracker is bundled from tracker/src/plausible.js using Rollup and minified with SWC in tracker/compiler/index.js, outputting to priv/tracker/js/plausible-web.js.
  • Dynamic injection: PlausibleWeb.Tracker.build_script/1 replaces the "<%= @config_js %>" placeholder at runtime with site-specific configuration from TrackerScriptConfiguration.
  • Efficient serving: PlausibleWeb.TrackerPlug serves the content with aggressive caching via TrackerScriptIdCache, enabling CDN distribution and high-traffic handling.
  • Local generation: Developers can generate scripts locally using node tracker/compile.js with optional flags like --web-snippet.

Frequently Asked Questions

What build tools does Plausible use to compile the tracker script?

The compilation pipeline uses Rollup to bundle the ES module graph starting at tracker/src/plausible.js, paired with SWC (@swc/core) for high-performance minification. Global compile-time flags like COMPILE_PLAUSIBLE_WEB enable dead-code elimination, ensuring only necessary code reaches the final bundle.

How does Plausible inject site-specific settings without rebuilding the script?

The system uses a placeholder string "<%= @config_js %>" embedded in the pre-compiled template. When PlausibleWeb.Tracker.build_script/1 processes a request, it replaces this marker with a compact configuration object derived from the site's TrackerScriptConfiguration, performing the substitution in memory without accessing the filesystem.

Where is the compiled tracker file stored in the repository?

The minified output is written to priv/tracker/js/plausible-web.js (and variant files) during execution of tracker/compile.js. This compiled artifact is checked into version control, allowing the Elixir application to reference it via the @plausible_main_script module attribute.

How does the tracker endpoint handle high traffic loads?

The PlausibleWeb.TrackerPlug leverages TrackerScriptIdCache and TrackerScriptCache to memoize generated scripts by their configuration ID. This caching strategy ensures that identical configurations are served instantly without recomputation, making the endpoint compatible with CDN edge caching and capable of handling high request volumes efficiently.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →