GA4 Analytics Toolkit
What this skill does with your data
- Network: calls Google only: the Analytics Data API, Search Console API and Indexing API (
*.googleapis.com). - Credentials: a Google Cloud service account from
.envin the working directory. Use least privilege: Viewer on the one GA4 property, and access to the one Search Console site. The Indexing API scope is needed only forreindexUrls/requestIndexing. Keep.envout of version control. - What's sent: your property ID, site URL, date ranges, and any URLs you ask to inspect or re-index.
- Changes it can make:
reindexUrlsasks Google to recrawl URLs.removeFromIndexasks Google to drop a URL from Search; it refuses unless called with{ confirm: true }, and should only be used when the site owner asks to remove that exact URL. Everything else is read-only. - Files: nothing is written unless you set
SAVE_RESULTS=true; no function argument can turn saving on. Saved files are readable only by you (0600) and can only go in theresults/folders listed below.
Setup
Install the pinned dependencies from the lockfile:
cd scripts && npm ci --ignore-scripts
Configure credentials by creating a .env file in the project root:
GA4_PROPERTY_ID=123456789
GA4_CLIENT_EMAIL=service-account@project.iam.gserviceaccount.com
GA4_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
SEARCH_CONSOLE_SITE_URL=https://your-domain.com
GA4_DEFAULT_DATE_RANGE=30d
# Optional: keep results on disk
# SAVE_RESULTS=true
Prerequisites: A Google Cloud project with the Analytics Data API, Search Console API, and Indexing API enabled. A service account with access to your GA4 property and Search Console.
Quick Start
| User says | Function to call |
|---|---|
| "Show me site traffic for the last 30 days" | siteOverview("30d") |
| "What are my top search queries?" | searchConsoleOverview("30d") |
| "Who's on the site right now?" | liveSnapshot() |
| "Reindex these URLs" | reindexUrls(["https://example.com/page1", ...]) |
| "Compare this month vs last month" | compareDateRanges({startDate: "30daysAgo", endDate: "today"}, {startDate: "60daysAgo", endDate: "31daysAgo"}) |
| "What pages get the most traffic?" | contentPerformance("30d") |
Execute functions by importing from scripts/src/index.ts:
import { siteOverview, searchConsoleOverview } from './scripts/src/index.js';
const overview = await siteOverview('30d');
Or run it with the project's pinned tsx (installed by npm ci):
cd scripts && npm start
Workflow Pattern
Every analysis follows two phases:
1. Analyze
Run API functions. Each call hits the Google APIs and returns structured data to you. Nothing is written to disk.
2. Summarize
Summarize the returned data for the user: tables, trends and recommendations. Write a summary file only if the user asks for one.
Saving (opt-in): only with SAVE_RESULTS=true in .env are results also saved as timestamped JSON in results/{category}/ (YYYYMMDD_HHMMSS__operation__extra_info.json).
High-Level Functions
GA4 Analytics
| Function | Purpose | What it gathers |
|---|---|---|
siteOverview(dateRange?) |
Comprehensive site snapshot | Page views, traffic sources, demographics, events |
trafficAnalysis(dateRange?) |
Traffic deep-dive | Sources, sessions by source/medium, new vs returning |
contentPerformance(dateRange?) |
Top pages analysis | Page views, landing pages, exit pages |
userBehavior(dateRange?) |
Engagement patterns | Demographics, events, daily engagement metrics |
compareDateRanges(range1, range2) |
Period comparison | Side-by-side metrics for two date ranges |
liveSnapshot() |
Real-time data | Active users, current pages, current events |
Search Console
| Function | Purpose | What it gathers |
|---|---|---|
searchConsoleOverview(dateRange?) |
SEO snapshot | Top queries, pages, device, country breakdown |
keywordAnalysis(dateRange?) |
Keyword deep-dive | Queries with device breakdown |
seoPagePerformance(dateRange?) |
Page SEO metrics | Top pages by clicks, country breakdown |
Indexing
| Function | Purpose |
|---|---|
reindexUrls(urls) |
Ask Google to recrawl multiple URLs |
checkIndexStatus(urls) |
Check if URLs are indexed (read-only) |
removeFromIndex(url, { confirm: true }) is available from the API module but is destructive: it asks Google to drop the URL from Search. Use it only when the site owner asks to remove that exact URL. See references/api-reference.md.
Utility
| Function | Purpose |
|---|---|
getAvailableFields() |
List all available GA4 dimensions and metrics |
Individual API Functions
For granular control, import specific functions from the API modules. See references/api-reference.md for the complete list of 30+ API functions with parameters, types, and examples.
Date Ranges
All functions accept flexible date range formats:
| Format | Example | Description |
|---|---|---|
| Shorthand | "7d", "30d", "90d" |
Days ago to today |
| Explicit | {startDate: "2024-01-01", endDate: "2024-01-31"} |
Specific dates |
| GA4 relative | {startDate: "30daysAgo", endDate: "today"} |
GA4 relative format |
Default is "30d" (configurable via GA4_DEFAULT_DATE_RANGE in .env).
Results Storage (only if you opt in)
Off by default. Only with SAVE_RESULTS=true are results saved to results/ (or RESULTS_DIR) with this structure. Categories are fixed (reports, realtime, searchconsole, indexing, metadata, summaries): other names are refused, and loadResult only reads files inside results/.
results/
├── reports/ # GA4 standard reports
├── realtime/ # Real-time snapshots
├── searchconsole/ # Search Console data
├── indexing/ # Indexing API results
└── summaries/ # Human-readable markdown summaries
Managing Results
import { listResults, loadResult, getLatestResult } from './scripts/src/index.js';
// List recent results
const files = listResults('reports', 10);
// Load a specific result
const data = loadResult(files[0]);
// Get most recent result for an operation
const latest = getLatestResult('reports', 'site_overview');
Common Dimensions and Metrics
Dimensions
pagePath, pageTitle, sessionSource, sessionMedium, country, deviceCategory, browser, date, eventName, landingPage, newVsReturning
Metrics
screenPageViews, activeUsers, sessions, newUsers, bounceRate, averageSessionDuration, engagementRate, conversions, totalRevenue, eventCount
Tips
- Specify date ranges — "last 7 days" or "last 90 days" gives different insights than the default 30 days
- Request summaries — After pulling data, ask for a markdown summary with tables and insights (saved to
results/summaries/only if you ask) - Compare periods — Use
compareDateRanges()to spot trends (this month vs last month) - Check real-time data —
liveSnapshot()shows who's on the site right now - Combine GA4 + Search Console — Traffic data plus search query data gives the full picture
