Repository navigation
feat: detect visitor type and report human/crawler/AI traffic to GA4 - #122
Conversation
Classify each request (human / search-crawler / AI agent) from its User-Agent in the SSR server and expose it via res.locals + the X-Visitor-Type header. Report a visitor_hit GA4 event per page render so all three buckets land in one comparable dimension: humans client-side via VisitorAnalyticsService, bots via the GA4 Measurement Protocol (env-gated on GA_MP_API_SECRET, bot User-Agent omitted so GA4's bot filter does not drop the hit). Measurement is scoped to Angular page renders, not static/well-known/sitemap requests. The MP secret is injected through the deploy pipeline (GitHub Actions secret -> ssh-action envs -> docker-compose substitution).
|
Warning Review limit reached
More reviews will be available in 34 minutes and 43 seconds. Learn how PR review limits work. Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file). ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
WalkthroughAdds server-side User-Agent classification into ChangesVisitor Analytics: UA Classification + GA4 Measurement Protocol
Sequence Diagram(s)sequenceDiagram
participant Browser
participant ExpressSSR as Express SSR
participant classifyVisitor
participant AngularSSR as Angular Renderer
participant sendVisitorHit
participant GA4_MP as GA4 Measurement Protocol
participant VisitorAnalyticsService
Browser->>ExpressSSR: HTTP GET /page with User-Agent
ExpressSSR->>classifyVisitor: userAgent string
classifyVisitor-->>ExpressSSR: VisitorType human or crawler or ai-agent
ExpressSSR->>ExpressSSR: store in res.locals, set X-Visitor-Type header
ExpressSSR->>AngularSSR: render page
AngularSSR-->>ExpressSSR: rendered HTML
alt visitorType is not human
ExpressSSR->>sendVisitorHit: visitorType, absolute URL, userAgent
sendVisitorHit->>GA4_MP: POST visitor_hit event fire-and-forget
end
ExpressSSR-->>Browser: HTML + X-Visitor-Type header
Note over Browser,VisitorAnalyticsService: On NavigationEnd in browser
Browser->>VisitorAnalyticsService: NavigationEnd event
VisitorAnalyticsService->>GA4_MP: gtag visitor_hit with visitor_type human
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 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: 4
🧹 Nitpick comments (1)
src/app/services/visitor-analytics.service.ts (1)
6-6: ⚡ Quick winUse the configured environment alias instead of a direct
src/...path.Please switch this import to
@environments/environmentto follow the repo alias contract.Suggested fix
-import { environment } from "src/environments/environment"; +import { environment } from "`@environments/environment`";As per coding guidelines, "
**/*.ts: Use path alias@environments/*to reference files in thesrc/environments/directory`".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/services/visitor-analytics.service.ts` at line 6, The import statement in visitor-analytics.service.ts is using a direct filesystem path instead of the configured path alias. Replace the import path from "src/environments/environment" to "`@environments/environment`" to follow the repository's path alias conventions for the environments directory.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/ga-ssr-visitor-type.md`:
- Around line 25-27: The instruction at step 2 incorrectly identifies
G-6GS9Y7GJD3 as a property ID when it is actually a web stream Measurement ID.
Clarify the instruction by either: specifying that users should select the GA4
Property ID (not the Measurement ID) in the property selection dropdown at the
top left, or if the intent is to help users locate the Measurement ID for
tracking code implementation, redirect them to navigate to Admin > Data Streams
where they can find the G-6GS9Y7GJD3 Measurement ID for the techinterview.space
web stream. Remove the misleading reference to selecting a "resource (property)"
using the Measurement ID.
In `@docs/interactions.md`:
- Line 117: The documentation row for GA_MP_API_SECRET incorrectly describes the
runtime source as coming from a Droplet .env file, which misleads operators
about where to set this configuration. Update the row to accurately reflect the
actual flow where the secret originates from GitHub Actions, passes through an
SSH session, and is then interpolated by docker-compose, rather than pointing
operators to a Droplet .env file.
In `@src/app/services/visitor-analytics.service.ts`:
- Around line 21-32: The init() method in VisitorAnalyticsService can be called
multiple times, creating duplicate subscriptions to router.events that cause the
track() method to be invoked multiple times for the same navigation event. Make
init() idempotent by adding a private flag property to track whether
initialization has already occurred, then check this flag at the start of init()
and return early if already initialized. Alternatively, apply the
takeUntilDestroyed() operator to the pipe chain to ensure automatic subscription
cleanup when the service is destroyed, preventing duplicate subscriptions from
accumulating.
In `@src/server/ga-measurement-protocol.util.ts`:
- Around line 79-86: The fetch call in the function is directly interpolating
measurement_id and api_secret into the query string without URL encoding, which
is not a best practice and could cause malformed requests if the secret format
changes or contains special characters. Replace the template string
interpolation with URLSearchParams to properly encode the query parameters.
Create a URLSearchParams object with the measurement_id and api_secret as
key-value pairs, then append it to the GA_MP_ENDPOINT URL using the search
property before passing it to the fetch call.
---
Nitpick comments:
In `@src/app/services/visitor-analytics.service.ts`:
- Line 6: The import statement in visitor-analytics.service.ts is using a direct
filesystem path instead of the configured path alias. Replace the import path
from "src/environments/environment" to "`@environments/environment`" to follow the
repository's path alias conventions for the environments directory.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 13575a33-a07b-49bd-bfe8-b2ad20596d23
📒 Files selected for processing (13)
.github/workflows/deploy.ymlREADME.mddocker-compose.frontend.ymldocs/ga-ssr-visitor-type.mddocs/geo.mddocs/interactions.mdsrc/app/app.component.tssrc/app/services/visitor-analytics.service.tssrc/server.tssrc/server/ga-measurement-protocol.util.spec.tssrc/server/ga-measurement-protocol.util.tssrc/server/visitor-type.util.spec.tssrc/server/visitor-type.util.ts
Classify each request (human / search-crawler / AI agent) from its User-Agent in the SSR server and expose it via res.locals + the X-Visitor-Type header.
Report a visitor_hit GA4 event per page render so all three buckets land in one comparable dimension: humans client-side via VisitorAnalyticsService, bots via the GA4 Measurement Protocol (env-gated on GA_MP_API_SECRET, bot User-Agent omitted so GA4's bot filter does not drop the hit). Measurement is scoped to Angular page renders, not static/well-known/sitemap requests.
The MP secret is injected through the deploy pipeline (GitHub Actions secret -> ssh-action envs -> docker-compose substitution).
Summary by CodeRabbit
Release Notes
New Features
Documentation
Tests
Chores