ga4-analytics

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GA4 Analytics Toolkit

GA4分析工具包

Setup

配置步骤

Install dependencies:
bash
cd scripts && npm install
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
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.
安装依赖项:
bash
cd scripts && npm install
在项目根目录创建
.env
文件以配置凭证:
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
前置条件:拥有已启用Analytics Data API、Search Console API和Indexing API的Google Cloud项目,以及具备GA4属性和Search Console访问权限的服务账号。

Quick Start

快速开始

User saysFunction 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
:
typescript
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天的网站流量"
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

Workflow 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
results/{category}/
. File naming pattern:
YYYYMMDD_HHMMSS__operation__extra_info.json
所有结果会自动保存为带时间戳的JSON文件至
results/{category}/
目录。文件命名格式:
YYYYMMDD_HHMMSS__operation__extra_info.json

3. Summarize

3. 生成摘要

After analysis, read the saved JSON files and create a markdown summary in
results/summaries/
with data tables, trends, and recommendations.
分析完成后,读取已保存的JSON文件,并在
results/summaries/
目录中生成包含数据表格、趋势分析及建议的Markdown摘要。

High-Level Functions

核心函数

GA4 Analytics

GA4分析

FunctionPurposeWhat it gathers
siteOverview(dateRange?)
Comprehensive site snapshotPage views, traffic sources, demographics, events
trafficAnalysis(dateRange?)
Traffic deep-diveSources, sessions by source/medium, new vs returning
contentPerformance(dateRange?)
Top pages analysisPage views, landing pages, exit pages
userBehavior(dateRange?)
Engagement patternsDemographics, events, daily engagement metrics
compareDateRanges(range1, range2)
Period comparisonSide-by-side metrics for two date ranges
liveSnapshot()
Real-time dataActive users, current pages, current events
函数用途采集的数据
siteOverview(dateRange?)
全面的网站快照页面浏览量、流量来源、用户统计数据、事件数据
trafficAnalysis(dateRange?)
流量深度分析流量来源、按来源/媒介划分的会话数、新用户与回访用户
contentPerformance(dateRange?)
热门页面分析页面浏览量、着陆页、退出页
userBehavior(dateRange?)
用户行为模式分析用户统计数据、事件数据、每日互动指标
compareDateRanges(range1, range2)
周期对比分析两个日期范围的指标并排对比
liveSnapshot()
实时数据快照活跃用户、当前访问页面、当前事件

Search Console

Search Console

FunctionPurposeWhat it gathers
searchConsoleOverview(dateRange?)
SEO snapshotTop queries, pages, device, country breakdown
keywordAnalysis(dateRange?)
Keyword deep-diveQueries with device breakdown
seoPagePerformance(dateRange?)
Page SEO metricsTop pages by clicks, country breakdown
函数用途采集的数据
searchConsoleOverview(dateRange?)
SEO快照热门查询、页面、设备、地区分布
keywordAnalysis(dateRange?)
关键词深度分析带设备分布的查询数据
seoPagePerformance(dateRange?)
页面SEO指标分析按点击量排序的热门页面、地区分布

Indexing

索引管理

FunctionPurpose
reindexUrls(urls)
Request re-indexing for multiple URLs
checkIndexStatus(urls)
Check if URLs are indexed
函数用途
reindexUrls(urls)
请求对多个URL进行重新索引
checkIndexStatus(urls)
检查URL的索引状态

Utility

实用工具

FunctionPurpose
getAvailableFields()
List all available GA4 dimensions and metrics
函数用途
getAvailableFields()
列出所有可用的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.
所有函数支持灵活的日期范围格式:
格式示例说明
简写格式
"7d"
,
"30d"
,
"90d"
从指定天数前到今日
明确日期
{startDate: "2024-01-01", endDate: "2024-01-31"}
具体的起止日期
GA4相对格式
{startDate: "30daysAgo", endDate: "today"}
GA4支持的相对日期格式
默认格式为
"30d"
(可通过
.env
文件中的
GA4_DEFAULT_DATE_RANGE
配置)。

Date Ranges

结果存储

All functions accept flexible date range formats:
FormatExampleDescription
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/
目录,结构如下:
results/
├── reports/          # GA4标准报告
├── realtime/         # 实时数据快照
├── searchconsole/    # Search Console数据
├── indexing/         # 索引API结果
└── summaries/        # 易读的Markdown摘要

Results Storage

结果管理

Results auto-save to
results/
with this structure:
results/
├── reports/          # GA4 standard reports
├── realtime/         # Real-time snapshots
├── searchconsole/    # Search Console data
├── indexing/         # Indexing API results
└── summaries/        # Human-readable markdown summaries
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');

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');
pagePath
,
pageTitle
,
sessionSource
,
sessionMedium
,
country
,
deviceCategory
,
browser
,
date
,
eventName
,
landingPage
,
newVsReturning

Common Dimensions and Metrics

指标

Dimensions

pagePath
,
pageTitle
,
sessionSource
,
sessionMedium
,
country
,
deviceCategory
,
browser
,
date
,
eventName
,
landingPage
,
newVsReturning
screenPageViews
,
activeUsers
,
sessions
,
newUsers
,
bounceRate
,
averageSessionDuration
,
engagementRate
,
conversions
,
totalRevenue
,
eventCount

Metrics

使用技巧

screenPageViews
,
activeUsers
,
sessions
,
newUsers
,
bounceRate
,
averageSessionDuration
,
engagementRate
,
conversions
,
totalRevenue
,
eventCount
  1. 指定日期范围 — "过去7天"或"过去90天"会带来与默认30天不同的分析视角
  2. 请求生成摘要 — 获取数据后,可请求生成包含表格和分析见解的Markdown摘要
  3. 对比不同周期 — 使用
    compareDateRanges()
    发现趋势(如本月与上月对比)
  4. 查看实时数据
    liveSnapshot()
    可显示当前网站的访客情况
  5. 结合GA4与Search Console — 流量数据搭配搜索查询数据可呈现完整的网站运营图景

Tips

  1. Specify date ranges — "last 7 days" or "last 90 days" gives different insights than the default 30 days
  2. Request summaries — After pulling data, ask for a markdown summary with tables and insights
  3. Compare periods — Use
    compareDateRanges()
    to spot trends (this month vs last month)
  4. Check real-time data
    liveSnapshot()
    shows who's on the site right now
  5. Combine GA4 + Search Console — Traffic data plus search query data gives the full picture