GA4 Analytics Toolkit
Setup
Install dependencies:
CODEBLOCK0
Configure credentials by creating a .env file in the project root:
CODEBLOCK1
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" | INLINECODE1 |
| "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:
CODEBLOCK2
Or run directly with tsx:
CODEBLOCK3
Workflow Pattern
Every analysis follows three phases:
1. Analyze
Run API functions. Each call hits the Google APIs and returns structured data.
2. Auto-Save
All results automatically save as timestamped JSON files to
results/{category}/. File naming pattern: INLINECODE9
3. Summarize
After analysis, read the saved JSON files and create a markdown summary in
results/summaries/ with data tables, trends, and recommendations.
High-Level Functions
GA4 Analytics
| Function | Purpose | What it gathers |
|---|
| INLINECODE11 | Comprehensive site snapshot | Page views, traffic sources, demographics, events |
| INLINECODE12 |
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 |
|---|
| INLINECODE17 | SEO snapshot | Top queries, pages, device, country breakdown |
| INLINECODE18 |
Keyword deep-dive | Queries with device breakdown |
|
seoPagePerformance(dateRange?) | Page SEO metrics | Top pages by clicks, country breakdown |
Indexing
| Function | Purpose |
|---|
| INLINECODE20 | Request re-indexing for multiple URLs |
| INLINECODE21 |
Check if URLs are indexed |
Utility
| Function | Purpose |
|---|
| INLINECODE22 | 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 | INLINECODE23 , "30d", INLINECODE25 | 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
Results auto-save to results/ with this structure:
CODEBLOCK4
Managing Results
CODEBLOCK5
Common Dimensions and Metrics
Dimensions
pagePath,
pageTitle,
sessionSource,
sessionMedium,
country,
deviceCategory,
browser,
date,
eventName,
landingPage, INLINECODE42
Metrics
screenPageViews,
activeUsers,
sessions,
newUsers,
bounceRate,
averageSessionDuration,
engagementRate,
conversions,
totalRevenue, INLINECODE52
Tips
- 1. 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
- 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
GA4 分析工具包
设置
安装依赖:
bash
cd scripts && npm install
在项目根目录创建 .env 文件来配置凭据:
GA4PROPERTYID=123456789
GA4CLIENTEMAIL=service-account@project.iam.gserviceaccount.com
GA4PRIVATEKEY=-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n
SEARCHCONSOLESITE_URL=https://your-domain.com
GA4DEFAULTDATE_RANGE=30d
前置条件:一个已启用 Analytics Data API、Search Console API 和 Indexing API 的 Google Cloud 项目。一个有权访问您的 GA4 媒体资源和 Search Console 的服务账号。
快速开始
| 用户指令 | 调用的函数 |
|---|
| 显示最近30天的网站流量 | siteOverview(30d) |
| 我的热门搜索查询是什么? |
searchConsoleOverview(30d) |
| 现在谁在网站上? | liveSnapshot() |
| 重新索引这些URL | reindexUrls([https://example.com/page1, ...]) |
| 比较本月与上月 | compareDateRanges({startDate: 30daysAgo, endDate: today}, {startDate: 60daysAgo, endDate: 31daysAgo}) |
| 哪些页面流量最大? | contentPerformance(30d) |
通过从 scripts/src/index.ts 导入来执行函数:
typescript
import { siteOverview, searchConsoleOverview } from ./scripts/src/index.js;
const overview = await siteOverview(30d);
或者直接使用 tsx 运行:
bash
npx tsx scripts/src/index.ts
工作流模式
每次分析都遵循三个阶段:
1. 分析
运行 API 函数。每次调用都会访问 Google API 并返回结构化数据。
2. 自动保存
所有结果自动保存为带时间戳的 JSON 文件到 results/{category}/ 目录。文件命名模式:YYYYMMDD
HHMMSSoperationextrainfo.json
3. 总结
分析完成后,读取保存的 JSON 文件,在 results/summaries/ 中创建包含数据表格、趋势和建议的 Markdown 摘要。
高级函数
GA4 分析
| 函数 | 用途 | 收集内容 |
|---|
| siteOverview(dateRange?) | 全面的网站快照 | 页面浏览量、流量来源、用户画像、事件 |
| trafficAnalysis(dateRange?) |
流量深度分析 | 来源、按来源/媒介划分的会话、新访客与回访用户 |
| contentPerformance(dateRange?) | 热门页面分析 | 页面浏览量、着陆页、退出页 |
| userBehavior(dateRange?) | 用户参与模式 | 用户画像、事件、每日参与度指标 |
| compareDateRanges(range1, range2) | 时间段对比 | 两个日期范围的并排指标对比 |
| liveSnapshot() | 实时数据 | 活跃用户、当前页面、当前事件 |
Search Console
| 函数 | 用途 | 收集内容 |
|---|
| searchConsoleOverview(dateRange?) | SEO 快照 | 热门查询、页面、设备、国家分布 |
| keywordAnalysis(dateRange?) |
关键词深度分析 | 带设备划分的查询 |
| seoPagePerformance(dateRange?) | 页面 SEO 指标 | 按点击量排序的热门页面、国家分布 |
索引
| 函数 | 用途 |
|---|
| reindexUrls(urls) | 请求重新索引多个 URL |
| checkIndexStatus(urls) |
检查 URL 是否已被索引 |
工具
| 函数 | 用途 |
|---|
| getAvailableFields() | 列出所有可用的 GA4 维度和指标 |
单个 API 函数
如需精细控制,可从 API 模块导入特定函数。请参阅 references/api-reference.md 获取包含参数、类型和示例的 30 多个 API 函数的完整列表。
日期范围
所有函数都接受灵活的日期范围格式:
| 格式 | 示例 | 描述 |
|---|
| 简写 | 7d, 30d, 90d | 从指定天数前到今天 |
| 显式 |
{startDate: 2024-01-01, endDate: 2024-01-31} | 特定日期 |
| GA4 相对 | {startDate: 30daysAgo, endDate: today} | GA4 相对格式 |
默认值为 30d(可通过 .env 中的 GA4DEFAULTDATE_RANGE 配置)。
结果存储
结果自动保存到 results/ 目录,结构如下:
results/
├── reports/ # GA4 标准报告
├── realtime/ # 实时快照
├── searchconsole/ # Search Console 数据
├── indexing/ # 索引 API 结果
└── summaries/ # 人类可读的 Markdown 摘要
管理结果
typescript
import { listResults, loadResult, getLatestResult } from ./scripts/src/index.js;
// 列出最近的结果
const files = listResults(reports, 10);
// 加载特定结果
const data = loadResult(files[0]);
// 获取某个操作的最新结果
const latest = getLatestResult(reports, site_overview);
常用维度和指标
维度
pagePath, pageTitle, sessionSource, sessionMedium, country, deviceCategory, browser, date, eventName, landingPage, newVsReturning
指标
screenPageViews, activeUsers, sessions, newUsers, bounceRate, averageSessionDuration, engagementRate, conversions, totalRevenue, eventCount
提示
- 1. 指定日期范围 — 最近7天或最近90天能提供与默认30天不同的洞察
- 请求摘要 — 拉取数据后,请求生成包含表格和洞察的 Markdown 摘要
- 比较时间段 — 使用 compareDateRanges() 发现趋势(本月与上月对比)
- 查看实时数据 — liveSnapshot() 显示当前谁在网站上
- 结合 GA4 + Search Console — 流量数据加上搜索查询数据能呈现完整图景