Proxy Plausible analytics through the backend - #95
Conversation
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.
✅ Deploy Preview for climate-ref ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
📝 WalkthroughWalkthroughThe 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. ChangesAnalytics proxy
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
Merge Risk: 🟡 Moderate · up to 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)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation 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.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Team
Run ID: 5fdf1000-dce6-436e-9b90-355a91e9b9c5
⛔ Files ignored due to path filters (1)
backend/uv.lockis excluded by!**/*.lock
📒 Files selected for processing (6)
backend/pyproject.tomlbackend/src/ref_backend/analytics.pybackend/src/ref_backend/builder.pybackend/tests/test_analytics.pychangelog/95.fix.mdfrontend/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) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
sed -n '1,130p' backend/src/ref_backend/analytics.pyRepository: 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"
doneRepository: 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, |
There was a problem hiding this comment.
🎯 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.
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 byfrontend/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 back405 Method Not Allowed. This is visible in the browser console on https://staging.climate-ref.org.Changes:
backend/src/ref_backend/analytics.py, a/logrouter that forwardsscript.jsandapi/eventto plausible.io.frontend/src/client/needs no regeneration.Summary by CodeRabbit
Bug Fixes
Chores