google-analytics
ACTIVATE when the user wants to PULL/REPORT GA4 data via the Google Analytics Data API — traffic reports, user behavior, acquisition channels, conversions, audience segments. Trigger phrases: 'google analytics', 'GA4', 'traffic report', 'analytics data', 'user acquisition', 'engagement metrics', 'audience segments', 'page views', 'sessions'. For SETTING UP tracking (events, GTM, UTMs), see analytics-tracking. For search-side data (queries, rankings, CTR, impressions), see search-console.
- License 许可
- MIT
- 最近更新
- 2026-10-13
- Stars
- ★ 9
- Forks
- 2
01 前言 Front Matter
- name
- google-analytics
- description
- ACTIVATE when the user wants to PULL/REPORT GA4 data via the Google Analytics Data API — traffic reports, user behavior, acquisition channels, conversions, audience segments. Trigger phrases: 'google analytics', 'GA4', 'traffic report', 'analytics data', 'user acquisition', 'engagement metrics', 'audience segments', 'page views', 'sessions'. For SETTING UP tracking (events, GTM, UTMs), see analytics-tracking. For search-side data (queries, rankings, CTR, impressions), see search-console.
02 资源文件 1
- 参考文档.skillkit.json222 B
03 SKILL.md 正文
Google Analytics (GA4)
Pull reports and insights from GA4 using the Google Analytics Data API.
Prerequisites
Requires Google OAuth credentials:
GOOGLE_CLIENT_IDGOOGLE_CLIENT_SECRET- A valid OAuth access token (refreshed as needed)
Set credentials in .env, .env.local, or ~/.claude/.env.global.
Getting an Access Token
# Step 1: Visit this URL in a browser; Google redirects to the loopback address with the code
echo "https://accounts.google.com/o/oauth2/v2/auth?client_id=${GOOGLE_CLIENT_ID}&redirect_uri=http://localhost:8085/&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code&access_type=offline"
# Step 2: Copy the code= value from the browser's address bar after the redirect, then exchange it for tokens
curl -s -X POST "https://oauth2.googleapis.com/token" \
-d "code={AUTH_CODE}" \
-d "client_id=${GOOGLE_CLIENT_ID}" \
-d "client_secret=${GOOGLE_CLIENT_SECRET}" \
-d "redirect_uri=http://localhost:8085/" \
-d "grant_type=authorization_code"
# Step 3: Refresh an expired token
curl -s -X POST "https://oauth2.googleapis.com/token" \
-d "refresh_token={REFRESH_TOKEN}" \
-d "client_id=${GOOGLE_CLIENT_ID}" \
-d "client_secret=${GOOGLE_CLIENT_SECRET}" \
-d "grant_type=refresh_token"
Store the refresh token securely. The access token expires after 1 hour.
Finding Your GA4 Property ID
curl -s -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
"https://analyticsadmin.googleapis.com/v1beta/accountSummaries" \
| python3 -c "
import json, sys
data = json.load(sys.stdin)
for acct in data.get('accountSummaries', []):
for prop in acct.get('propertySummaries', []):
print(f\"{prop['property']} | {prop.get('displayName','')} | Account: {acct.get('displayName','')}\")
"
The property ID format is properties/XXXXXXXXX.
API Base
POST https://analyticsdata.googleapis.com/v1beta/{property_id}:runReport
All report requests use POST with a JSON body. Always include Authorization: Bearer {ACCESS_TOKEN}.
1. Traffic Overview Report
Get sessions, users, page views, and engagement rate over a date range.
Example curl
curl -s -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
-H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"metrics": [
{"name": "sessions"},
{"name": "totalUsers"},
{"name": "newUsers"},
{"name": "screenPageViews"},
{"name": "engagementRate"},
{"name": "averageSessionDuration"},
{"name": "bounceRate"}
]
}'
Date Range Shortcuts
today,yesterday7daysAgo,14daysAgo,28daysAgo,30daysAgo,90daysAgo- Specific dates:
2024-01-01 - Compare periods by passing two dateRanges
2. User Acquisition Report
See where users come from (channels, sources, campaigns).
curl -s -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
-H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [
{"name": "sessionDefaultChannelGroup"}
],
"metrics": [
{"name": "sessions"},
{"name": "totalUsers"},
{"name": "engagementRate"},
{"name": "conversions"}
],
"orderBys": [{"metric": {"metricName": "sessions"}, "desc": true}],
"limit": 20
}'
Useful Acquisition Dimensions
| Dimension | Description |
|---|---|
sessionDefaultChannelGroup |
Channel grouping (Organic, Paid, Social, etc.) |
sessionSource |
Traffic source (google, facebook, etc.) |
sessionMedium |
Medium (organic, cpc, referral, etc.) |
sessionCampaignName |
UTM campaign name |
firstUserSource |
First-touch attribution source |
3. Top Pages Report
Find the highest-traffic pages on the site.
curl -s -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
-H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [
{"name": "pagePath"}
],
"metrics": [
{"name": "screenPageViews"},
{"name": "totalUsers"},
{"name": "engagementRate"},
{"name": "averageSessionDuration"}
],
"orderBys": [{"metric": {"metricName": "screenPageViews"}, "desc": true}],
"limit": 25
}'
4. Engagement Metrics
Understand how users interact with your content.
curl -s -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
-H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [
{"name": "pagePath"}
],
"metrics": [
{"name": "engagedSessions"},
{"name": "engagementRate"},
{"name": "averageSessionDuration"},
{"name": "screenPageViewsPerSession"},
{"name": "eventCount"}
],
"orderBys": [{"metric": {"metricName": "engagedSessions"}, "desc": true}],
"limit": 20
}'
Key Engagement Metrics
| Metric | What It Measures |
|---|---|
engagementRate |
% of sessions that were engaged (>10s, 2+ pages, or conversion) |
averageSessionDuration |
Mean session length in seconds |
screenPageViewsPerSession |
Pages per session |
bounceRate |
% of sessions with no engagement |
eventCount |
Total events fired |
5. Conversion Tracking
Report on conversion events (purchases, signups, etc.).
curl -s -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
-H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [
{"name": "eventName"}
],
"metrics": [
{"name": "eventCount"},
{"name": "totalUsers"},
{"name": "eventValue"}
],
"dimensionFilter": {
"filter": {
"fieldName": "eventName",
"inListFilter": {
"values": ["purchase", "sign_up", "generate_lead", "begin_checkout"]
}
}
}
}'
Conversion by Channel
curl -s -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
-H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [
{"name": "sessionDefaultChannelGroup"}
],
"metrics": [
{"name": "sessions"},
{"name": "conversions"},
{"name": "totalRevenue"}
],
"orderBys": [{"metric": {"metricName": "conversions"}, "desc": true}]
}'
6. Audience Segments
Break down traffic by device, geography, and demographics.
By Device Category
curl -s -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
-H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [{"name": "deviceCategory"}],
"metrics": [
{"name": "sessions"},
{"name": "totalUsers"},
{"name": "engagementRate"},
{"name": "conversions"}
]
}'
By Country
Replace deviceCategory with country in the dimensions.
By Landing Page + Source
curl -s -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
-H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [
{"name": "landingPage"},
{"name": "sessionSource"}
],
"metrics": [
{"name": "sessions"},
{"name": "engagementRate"},
{"name": "conversions"}
],
"orderBys": [{"metric": {"metricName": "sessions"}, "desc": true}],
"limit": 30
}'
7. Period Comparison
Compare two time periods to identify trends.
curl -s -X POST \
"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
-H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"dateRanges": [
{"startDate": "30daysAgo", "endDate": "today", "name": "current"},
{"startDate": "60daysAgo", "endDate": "31daysAgo", "name": "previous"}
],
"metrics": [
{"name": "sessions"},
{"name": "totalUsers"},
{"name": "conversions"},
{"name": "engagementRate"}
]
}'
Response Parsing
GA4 API returns JSON. Parse with python3 or jq:
# Parse report into a table
curl -s -X POST "..." | python3 -c "
import json, sys
data = json.load(sys.stdin)
headers = [h['name'] for h in data.get('dimensionHeaders',[])] + [m['name'] for m in data.get('metricHeaders',[])]
print(' | '.join(headers))
print('-' * (len(headers) * 20))
for row in data.get('rows', []):
dims = [d['value'] for d in row.get('dimensionValues',[])]
mets = [m['value'] for m in row.get('metricValues',[])]
print(' | '.join(dims + mets))
"
Workflow: Monthly Analytics Report
When asked for a monthly report:
- Pull traffic overview (sessions, users, page views) with period comparison
- Pull acquisition breakdown by channel
- Pull top 20 pages by page views
- Pull conversion summary by channel
- Pull device and country breakdown
Present as a structured report with tables, trends (up/down arrows), and recommendations:
## Monthly Analytics Report: {Property Name}
### Period: {date range} vs {previous period}
### Traffic Summary
| Metric | Current | Previous | Change |
|--------|---------|----------|--------|
| Sessions | X | Y | +Z% |
| ...
### Top Channels
...
### Top Pages
...
### Conversion Summary
...
### Recommendations
- [Based on data patterns]
Common Issues
- 403 Forbidden: User lacks access to the GA4 property
- Empty rows: No data for the requested date range or filters
- Quota exceeded: GA4 API has daily quotas; reduce date ranges or batch requests
- Property not found: Verify the property ID format (
properties/XXXXXXXXX)
04 同仓库更多 Skills
vitest-test-conventions
ACTIVATE when writing Vitest tests, creating test files, using vi.fn()/vi.mock()/vi.spyOn(), or test factories. ACTIVATE for 'Vitest', 'it.each', 'NestJS testing module', 'supertest', 'vi.fn', 'vi.mock', 'spyOn'. Provides Vitest/NestJS-specific testing patterns; cross-language testing principles (DAMP, AAA, spy over mock, what NOT to test) live in craft:testing-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), TDD workflow/iterations (see vitest:vitest-tdd-workflow), PHP/PHPUnit tests (see phpunit:php-test-conventions).
vitest-tdd-workflow
ACTIVATE when building new features, endpoints, or user stories using TDD with Vitest in a TypeScript/NestJS context. ACTIVATE for '/feature-tdd-dev', 'TDD', 'red-green-refactor' in TS context. Provides Vitest/NestJS-specific TDD examples and commands; cross-language TDD workflow (cross-layer iterations, RED-GREEN-REFACTOR, working app, bug-fix-first-test, mocks-hiding-bugs) lives in craft:tdd-workflow-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), test writing conventions (see vitest:vitest-test-conventions), PHP TDD (see phpunit:php-tdd-workflow).
ts-refactoring
ACTIVATE when refactoring TypeScript code. ACTIVATE for 'refactor', 'extract', 'redesign', 'simplify', or 'clean up' in a TypeScript / Node / NestJS context. This skill provides TS-specific examples for the cross-language refactoring rules defined in craft:refactoring-principles. DO NOT use for: writing new features from scratch, general OOP patterns (see ts-oop).
ts-ports-adapters
ACTIVATE when a TypeScript codebase with no dependency-injection container has to declare a port and wire its adapter — a repository, a clock, an id generator, an event dispatcher the domain depends on. ACTIVATE for 'port', 'adapter', 'SPI', 'dependency inversion' or 'composition root' in a codebase that wires its dependencies by hand. Covers: the port as a type of functions in the domain layer, the adapter as an object literal annotated with it, the handler that takes its dependencies first and its data second, the composition root in the infrastructure layer, and the in-memory stub that substitutes for the adapter in a unit test. DO NOT use for: NestJS, or any container-based DI with decorators and tokens (see nest-ddd-conventions), aggregate operations and smart constructors (see ddd-ts-fp), the Result type itself (see ts-functional).
ts-oop
ACTIVATE when designing TypeScript classes, and the value objects or collections modelled as classes, or when the user asks about object design, encapsulation, Tell Don't Ask, or Symbol.iterator. Provides TS-specific examples for the cross-language OOP rules defined in craft:oop-principles, plus TS-specific patterns (Symbol.iterator, branded types for primitive identifiers). DO NOT use for: a value object or an aggregate modelled as an immutable record rather than a class (see ddd-ts-fp), refactoring methodology (see ts-refactoring).
ts-layer-boundaries
ACTIVATE when wiring a Worker entry point, a Router, a controller, or a domain event consumer in a TypeScript CQRS codebase, or when deciding where a port belongs. ACTIVATE for 'composition root', 'layer boundary', 'ESLint zones', 'domain must not import infrastructure'. Covers: the *Worker.ts composition root, the curried consumer, Router wiring of command endpoints, the five-gesture controller, the domain-to-infrastructure import boundary enforced by ESLint, infrastructure-only ports, in-memory doubles for every port, the read-can-reach-write asymmetry, and read endpoints going through a domain handler. DO NOT use for: the port's own shape and adapter binding (see ts-ports-adapters), the Result type (see ts-functional), domain event structure (see ts-ddd-events).