ga4-analytics
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGA4 Analytics Toolkit
GA4分析工具包
Setup
配置步骤
Install dependencies:
bash
cd scripts && npm installConfigure credentials by creating a file in the project root:
.envGA4_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=30dPrerequisites: 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.
安装依赖项:
bash
cd scripts && npm install在项目根目录创建文件以配置凭证:
.envGA4_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前置条件:拥有已启用Analytics Data API、Search Console API和Indexing API的Google Cloud项目,以及具备GA4属性和Search Console访问权限的服务账号。
Quick Start
快速开始
| User says | Function to call |
|---|---|
| "Show me site traffic for the last 30 days" | |
| "What are my top search queries?" | |
| "Who's on the site right now?" | |
| "Reindex these URLs" | |
| "Compare this month vs last month" | |
| "What pages get the most traffic?" | |
Execute functions by importing from :
scripts/src/index.tstypescript
import { siteOverview, searchConsoleOverview } from './scripts/src/index.js';
const overview = await siteOverview('30d');Or run directly with tsx:
bash
npx tsx scripts/src/index.ts| 用户指令 | 调用的函数 |
|---|---|
| "显示过去30天的网站流量" | |
| "我最热门的搜索查询有哪些?" | |
| "现在谁在访问我的网站?" | |
| "重新索引这些URL" | |
| "对比本月与上月的数据" | |
| "哪些页面流量最高?" | |
通过从导入来执行函数:
scripts/src/index.tstypescript
import { siteOverview, searchConsoleOverview } from './scripts/src/index.js';
const overview = await siteOverview('30d');或使用tsx直接运行:
bash
npx tsx scripts/src/index.tsWorkflow Pattern
工作流模式
Every analysis follows three phases:
每次分析都遵循三个阶段:
1. Analyze
1. 分析阶段
Run API functions. Each call hits the Google APIs and returns structured data.
调用API函数。每次调用都会访问Google API并返回结构化数据。
2. Auto-Save
2. 自动保存
All results automatically save as timestamped JSON files to . File naming pattern:
results/{category}/YYYYMMDD_HHMMSS__operation__extra_info.json所有结果会自动保存为带时间戳的JSON文件至目录。文件命名格式:
results/{category}/YYYYMMDD_HHMMSS__operation__extra_info.json3. Summarize
3. 生成摘要
After analysis, read the saved JSON files and create a markdown summary in with data tables, trends, and recommendations.
results/summaries/分析完成后,读取已保存的JSON文件,并在目录中生成包含数据表格、趋势分析及建议的Markdown摘要。
results/summaries/High-Level Functions
核心函数
GA4 Analytics
GA4分析
| Function | Purpose | What it gathers |
|---|---|---|
| Comprehensive site snapshot | Page views, traffic sources, demographics, events |
| Traffic deep-dive | Sources, sessions by source/medium, new vs returning |
| Top pages analysis | Page views, landing pages, exit pages |
| Engagement patterns | Demographics, events, daily engagement metrics |
| Period comparison | Side-by-side metrics for two date ranges |
| Real-time data | Active users, current pages, current events |
| 函数 | 用途 | 采集的数据 |
|---|---|---|
| 全面的网站快照 | 页面浏览量、流量来源、用户统计数据、事件数据 |
| 流量深度分析 | 流量来源、按来源/媒介划分的会话数、新用户与回访用户 |
| 热门页面分析 | 页面浏览量、着陆页、退出页 |
| 用户行为模式分析 | 用户统计数据、事件数据、每日互动指标 |
| 周期对比分析 | 两个日期范围的指标并排对比 |
| 实时数据快照 | 活跃用户、当前访问页面、当前事件 |
Search Console
Search Console
| Function | Purpose | What it gathers |
|---|---|---|
| SEO snapshot | Top queries, pages, device, country breakdown |
| Keyword deep-dive | Queries with device breakdown |
| Page SEO metrics | Top pages by clicks, country breakdown |
| 函数 | 用途 | 采集的数据 |
|---|---|---|
| SEO快照 | 热门查询、页面、设备、地区分布 |
| 关键词深度分析 | 带设备分布的查询数据 |
| 页面SEO指标分析 | 按点击量排序的热门页面、地区分布 |
Indexing
索引管理
| Function | Purpose |
|---|---|
| Request re-indexing for multiple URLs |
| Check if URLs are indexed |
| 函数 | 用途 |
|---|---|
| 请求对多个URL进行重新索引 |
| 检查URL的索引状态 |
Utility
实用工具
| Function | Purpose |
|---|---|
| List all available GA4 dimensions and metrics |
| 函数 | 用途 |
|---|---|
| 列出所有可用的GA4维度与指标 |
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.
所有函数支持灵活的日期范围格式:
| 格式 | 示例 | 说明 |
|---|---|---|
| 简写格式 | | 从指定天数前到今日 |
| 明确日期 | | 具体的起止日期 |
| GA4相对格式 | | GA4支持的相对日期格式 |
默认格式为(可通过文件中的配置)。
"30d".envGA4_DEFAULT_DATE_RANGEDate Ranges
结果存储
All functions accept flexible date range formats:
| Format | Example | Description |
|---|---|---|
| Shorthand | | Days ago to today |
| Explicit | | Specific dates |
| GA4 relative | | GA4 relative format |
Default is (configurable via in ).
"30d"GA4_DEFAULT_DATE_RANGE.env结果会自动保存至目录,结构如下:
results/results/
├── reports/ # GA4标准报告
├── realtime/ # 实时数据快照
├── searchconsole/ # Search Console数据
├── indexing/ # 索引API结果
└── summaries/ # 易读的Markdown摘要Results Storage
结果管理
Results auto-save to with this structure:
results/results/
├── reports/ # GA4 standard reports
├── realtime/ # Real-time snapshots
├── searchconsole/ # Search Console data
├── indexing/ # Indexing API results
└── summaries/ # Human-readable markdown summariestypescript
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');Managing Results
常用维度与指标
—
维度
typescript
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');pagePathpageTitlesessionSourcesessionMediumcountrydeviceCategorybrowserdateeventNamelandingPagenewVsReturningCommon Dimensions and Metrics
指标
Dimensions
—
pagePathpageTitlesessionSourcesessionMediumcountrydeviceCategorybrowserdateeventNamelandingPagenewVsReturningscreenPageViewsactiveUserssessionsnewUsersbounceRateaverageSessionDurationengagementRateconversionstotalRevenueeventCountMetrics
使用技巧
screenPageViewsactiveUserssessionsnewUsersbounceRateaverageSessionDurationengagementRateconversionstotalRevenueeventCount- 指定日期范围 — "过去7天"或"过去90天"会带来与默认30天不同的分析视角
- 请求生成摘要 — 获取数据后,可请求生成包含表格和分析见解的Markdown摘要
- 对比不同周期 — 使用发现趋势(如本月与上月对比)
compareDateRanges() - 查看实时数据 — 可显示当前网站的访客情况
liveSnapshot() - 结合GA4与Search Console — 流量数据搭配搜索查询数据可呈现完整的网站运营图景
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
- Compare periods — Use to spot trends (this month vs last month)
compareDateRanges() - Check real-time data — shows who's on the site right now
liveSnapshot() - Combine GA4 + Search Console — Traffic data plus search query data gives the full picture
—