Skip to content

Proxy Plausible analytics through the backend - #95

Merged
lewisjared merged 2 commits into
mainfrom
fix/plausible-proxy
Sep 4, 2026
Merged

Proxy Plausible analytics through the backend#95
lewisjared merged 2 commits into
mainfrom
fix/plausible-proxy

Conversation

@lewisjared

@lewisjared lewisjared commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Page view analytics have never worked on the container deployments. The tracker posts to /log/api/event, and that path is only redirected to plausible.io by frontend/netlify.toml, which applies to Netlify and nothing else. In the container the SPA is served from a FastAPI static mount that answers GET and HEAD only, so every event came back 405 Method Not Allowed. This is visible in the browser console on https://staging.climate-ref.org.

Changes:

  • Adds backend/src/ref_backend/analytics.py, a /log router that forwards script.js and api/event to plausible.io.
  • Keeps the router out of the OpenAPI schema, so frontend/src/client/ needs no regeneration.
  • Makes the tracker endpoint relative, so events go to whichever origin serves the app.

Summary by CodeRabbit

  • Bug Fixes

    • Page-view analytics now works correctly when the application is deployed in containers.
    • Analytics events are sent through the application’s current origin, preventing production activity from being recorded against the staging environment.
    • Added reliable handling for analytics script loading and event forwarding, including graceful behaviour when the analytics service is unavailable.
  • Chores

    • Added runtime support required for analytics communication.

The tracker posts to /log/api/event, and only Netlify ever redirected that path.
The container serves the SPA from a FastAPI static mount that answers GET and HEAD
only, so every event returned 405 and no page views were recorded from staging.

- Adds a /log router that forwards script.js and api/event to plausible.io.
  It is registered above the static mount, so it wins over the file handler.
- Keeps the router out of the OpenAPI schema, so the generated client is unchanged.
- Returns 202 when the upstream call fails, because a dropped event is not worth
  failing the page over.
- Makes the tracker endpoint relative, so production stops reporting into the
  staging site.

netlify.toml is untouched, so both deploy targets now behave the same.
@netlify

netlify Bot commented Sep 4, 2026

Copy link
Copy Markdown

Deploy Preview for climate-ref ready!

Name Link
🔨 Latest commit 9070db9
🔍 Latest deploy log https://app.netlify.com/projects/climate-ref/deploys/6a9a591a27c1a10008c96abe
😎 Deploy Preview https://deploy-preview-95--climate-ref.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Sep 4, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The frontend now sends analytics events to a relative path. The backend proxies tracker scripts and events to Plausible, with distinct handling for upstream failures. Tests cover forwarding, headers, responses, and connectivity errors.

Changes

Analytics proxy

Layer / File(s) Summary
Analytics proxy handlers
backend/pyproject.toml, backend/src/ref_backend/analytics.py
Adds httpx and implements /log/script.js and /log/api/event proxy endpoints.
Route integration
backend/src/ref_backend/builder.py, frontend/src/routes/__root.tsx
Registers the analytics router before static files. Configures the frontend to use /log/api/event.
Proxy validation
backend/tests/test_analytics.py, changelog/95.fix.md
Tests successful forwarding and upstream failures. Records the analytics proxy change.

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant FastAPI
  participant Plausible
  Browser->>FastAPI: Request /log/script.js or /log/api/event
  FastAPI->>Plausible: Forward tracker request
  Plausible-->>FastAPI: Return script or event response
  FastAPI-->>Browser: Return proxied response
Loading

Merge Risk: 🟡 Moderate · up to 9070d

The new same-origin analytics proxy can expose backend workers to oversized event uploads and can report analytics delivery failures to clients during Plausible 5xx responses. Resolve the request-size limit and 5xx-to-202 handling before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 41.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 4 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarises the main change: routing Plausible Analytics requests through the backend. It matches the pull request objectives and changeset.
Full details: Docstring Coverage

Explanation

Docstring coverage is 41.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 4 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/plausible-proxy

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@lewisjared
lewisjared merged commit 81acbdf into main Sep 4, 2026
8 of 9 checks passed
@lewisjared
lewisjared deleted the fix/plausible-proxy branch September 4, 2026 05:42

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: 5fdf1000-dce6-436e-9b90-355a91e9b9c5

📥 Commits

Reviewing files that changed from the base of the PR and between 0fbba78 and 9070db9.

⛔ Files ignored due to path filters (1)
  • backend/uv.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • backend/pyproject.toml
  • backend/src/ref_backend/analytics.py
  • backend/src/ref_backend/builder.py
  • backend/tests/test_analytics.py
  • changelog/95.fix.md
  • frontend/src/routes/__root.tsx

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.

headers["x-forwarded-for"] = forwarded_for

try:
upstream = await _client.post(PLAUSIBLE_EVENT_URL, content=await request.body(), headers=headers)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

sed -n '1,130p' backend/src/ref_backend/analytics.py

Repository: Climate-REF/ref-app

Length of output: 2769


🤖 get_repo_knowledge executed:

get_repo_knowledge Climate-REF/ref-app /tmp/coderabbit-repo-knowledge/climate-ref-ref-app-33a75429/architecture

Length of output: 26993


🏁 Script executed:

printf '%s\n' '--- deployment files ---'
git ls-files | rg '(^|/)(netlify\.toml|Dockerfile[^/]*|docker-compose[^/]*|nginx[^/]*|traefik[^/]*|caddy[^/]*|helm|k8s|kubernetes|ingress|fly\.toml|render\.yaml|railway\.json)$|(^|/)(netlify|deploy|deployment|infrastructure)/'
printf '%s\n' '--- request-size controls ---'
rg -n -i --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' \
  'client_max_body_size|max_body_size|max_request_body|request[_-]?size|body[_-]?limit|limit[_-]?request|payload[_-]?limit|MAX_BODY|CONTENT_LENGTH' .

Repository: Climate-REF/ref-app

Length of output: 317


🏁 Script executed:

for f in Dockerfile frontend/config/nginx.conf frontend/config/nginx-backend-not-found.conf frontend/netlify.toml; do
  printf '\n--- %s ---\n' "$f"
  sed -n '1,220p' "$f"
done

Repository: Climate-REF/ref-app

Length of output: 2881


Denial of Service (CWE-400): Uncontrolled Resource Consumption

Reachability: External · Exploitability: Trivial

Enforce a request-size limit before buffering event bodies.

The public endpoint buffers the complete request with await request.body(). Reject oversized Content-Length values and enforce the same limit while reading chunked bodies. Keep the ingress limit as defence in depth.


return Response(
content=upstream.content,
status_code=upstream.status_code,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Return 202 for upstream 5xx responses.

httpx.AsyncClient.post() does not raise for an upstream 5xx response. This line returns that failure to the tracker, which breaks the stated best-effort event contract. Preserve upstream 4xx responses, but map upstream 5xx responses to 202 and add a mock-5xx test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant