Skip to content

Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.

feat(ga4): expose ordered report pagination

Rudy Celeklie21c9f2d3d2e
diff --git a/tests/clis/ga4-report-pagination.test.cjs b/tests/clis/ga4-report-pagination.test.cjs
new file mode 100644
index 0000000..b3acb96
--- /dev/null
+++ b/tests/clis/ga4-report-pagination.test.cjs
@@ -0,0 +1,53 @@
+const { test } = require('node:test')
+const assert = require('node:assert/strict')
+const { spawnSync } = require('node:child_process')
+const path = require('node:path')
+const cli = path.resolve(__dirname, '../../tools/clis/ga4.js')
+const orders = [{dimension:{dimensionName:'date'}},{dimension:{dimensionName:'country'}}]
+function run(args, oracle='') {
+ const fixture = `global.fetch=async(url,options)=>{
+ const assert=require('node:assert/strict');const body=JSON.parse(options.body);${oracle}
+ assert.equal(url,'https://analyticsdata.googleapis.com/v1beta/properties/123:runReport');
+ assert.equal(options.method,'POST');assert.equal(options.headers.Authorization,'Bearer fixture-token');
+ const index=body.offset==='1'?1:0;
+ return new Response(JSON.stringify({rowCount:2,dimensionHeaders:[{name:'date'},{name:'country'}],rows:[{dimensionValues:[{value:'20260901'},{value:index?'US':'GB'}],metricValues:[{value:'10'}]}],request:body}),{status:200});
+ };process.argv=['node',${JSON.stringify(cli)},...${JSON.stringify(args)}];require(${JSON.stringify(cli)});`
+ return spawnSync(process.execPath,['-e',fixture],{encoding:'utf8',timeout:10000,env:{...process.env,GA4_ACCESS_TOKEN:'fixture-token'}})
+}
+function output(result){assert.equal(result.status,0,result.stderr);return JSON.parse(result.stdout)}
+const report=['reports','run','--property','123','--dimensions','date,country','--metrics','activeUsers','--start-date','2026-09-01','--end-date','2026-09-30']
+test('report pages use unchanged dimensions/date/order and an explicit next offset',()=>{
+ const first=output(run([...report,'--limit','1','--order-bys',JSON.stringify(orders)]))
+ assert.equal(first.request.limit,'1');assert.deepEqual(first.request.orderBys,orders)
+ const next=output(run([...report,'--limit','1','--offset','1','--order-bys',JSON.stringify(orders)]))
+ assert.equal(next.request.offset,'1');assert.equal(next.rows[0].dimensionValues[1].value,'US');assert.equal(next.rowCount,2)
+ const {offset,...request}=next.request;assert.deepEqual(request,first.request)
+})
+test('int64 offsets remain exact strings beyond Number safe precision',()=>{
+ const result=output(run([...report,'--offset','9007199254740993']))
+ assert.equal(result.request.offset,'9007199254740993')
+})
+test('metric and dimension ordering preserve caller sequence and direction',()=>{
+ const mixed=[{metric:{metricName:'activeUsers'},desc:true},...orders]
+ assert.deepEqual(output(run([...report,'--order-bys',JSON.stringify(mixed)])).request.orderBys,mixed)
+})
+test('report page preview includes zero offset, limit and ordering without a request',()=>{
+ const result=output(run([...report,'--limit','250000','--offset','0','--order-bys',JSON.stringify(orders),'--dry-run'],"throw new Error('unexpected request')"))
+ assert.equal(result.body.limit,'250000');assert.equal(result.body.offset,'0');assert.deepEqual(result.body.orderBys,orders);assert.equal(result.headers.Authorization,'***')
+})
+for(const field of ['offset','limit'])test(`invalid ${field} values fail before HTTP`,()=>{
+ const bad=field==='limit'?['0','-1','1.5','x','9223372036854775808']:['-1','1.5','x','9223372036854775808']
+ for(const value of bad){const result=run([...report,`--${field}`,value],"throw new Error('unexpected request')");assert.equal(result.status,1);assert.match(JSON.parse(result.stderr).error,new RegExp(`--${field}`))}
+})
+test('invalid order JSON and container shapes fail before HTTP',()=>{
+ for(const value of ['[bad','{}','null','[]','[null]','[1]']){const result=run([...report,'--order-bys',value],"throw new Error('unexpected request')");assert.equal(result.status,1);assert.match(JSON.parse(result.stderr).error,/--order-bys/)}
+})
+test('default report still omits all newly optional fields',()=>{
+ const body=output(run(report)).request
+ for(const key of ['limit','offset','orderBys'])assert.equal(Object.hasOwn(body,key),false)
+ assert.deepEqual(body.dateRanges,[{startDate:'2026-09-01',endDate:'2026-09-30'}])
+})
+test('realtime previews remain outside runReport pagination',()=>{
+ const result=output(run(['realtime','run','--property','123','--metrics','activeUsers','--offset','bad','--order-bys','[bad','--dry-run']))
+ assert.equal(result.url,'https://analyticsdata.googleapis.com/v1beta/properties/123:runRealtimeReport');assert.deepEqual(result.body,{metrics:[{name:'activeUsers'}]})
+})
diff --git a/tools/clis/ga4.js b/tools/clis/ga4.js
index 5f67828..6d216ce 100755
--- a/tools/clis/ga4.js
+++ b/tools/clis/ga4.js
@@ -74,6 +74,14 @@ if (!ACCESS_TOKEN && rawArgs.length > 0 && !(cmd === 'events' && sub === 'send')
process.exit(1)
}
+function reportInteger(name, minimum) {
+ const value = args[name]
+ if (typeof value !== 'string' || !/^\d+$/.test(value) || BigInt(value) < minimum || BigInt(value) > 9223372036854775807n) {
+ throw new Error(`--${name} must be an integer between ${minimum} and 9223372036854775807`)
+ }
+ return BigInt(value).toString()
+}
+
async function main() {
let result
@@ -95,6 +103,19 @@ async function main() {
if (args.metrics) {
body.metrics = args.metrics.split(',').map(m => ({ name: m.trim() }))
}
+ // The Data API represents pagination integers as decimal strings.
+ if (args.limit !== undefined) body.limit = reportInteger('limit', 1n)
+ if (args.offset !== undefined) body.offset = reportInteger('offset', 0n)
+ if (args['order-bys'] !== undefined) {
+ let orderBys
+ try { orderBys = JSON.parse(args['order-bys']) } catch {
+ throw new Error('--order-bys must be a JSON array of ordering objects')
+ }
+ if (!Array.isArray(orderBys) || !orderBys.length || orderBys.some(order => !order || typeof order !== 'object' || Array.isArray(order))) {
+ throw new Error('--order-bys must be a nonempty JSON array of ordering objects')
+ }
+ body.orderBys = orderBys
+ }
result = await api('POST', DATA_API, `/properties/${property}:runReport`, body)
break
}
@@ -179,7 +200,7 @@ async function main() {
result = {
error: 'Unknown command',
usage: {
- reports: 'reports run --property <id> [--start-date <date>] [--end-date <date>] [--dimensions <dims>] [--metrics <metrics>]',
+ reports: 'reports run --property <id> [--start-date <date>] [--end-date <date>] [--dimensions <dims>] [--metrics <metrics>] [--limit <rows>] [--offset <start-row>] [--order-bys <JSON array>]',
realtime: 'realtime run --property <id> [--dimensions <dims>] [--metrics <metrics>]',
conversions: 'conversions [list|create] --property <id> [--event-name <name>]',
events: 'events send --measurement-id <id> --api-secret <secret> --client-id <id> --event-name <name> [--params <json>]',
diff --git a/tools/integrations/ga4.md b/tools/integrations/ga4.md
index a15f9be..78c5e97 100644
--- a/tools/integrations/ga4.md
+++ b/tools/integrations/ga4.md
@@ -127,3 +127,39 @@ POST https://www.google-analytics.com/mp/collect?measurement_id={measurement_id}
- ab-testing
- seo-audit
- cro
+
+## Paging standard reports from the CLI
+
+`reports run` returns one page per invocation. Use `--limit` and `--offset` to
+read subsequent rows and `--order-bys` to keep their ordering explicit. The CLI
+sends these pagination integers as decimal strings, as required by the Data API,
+without rounding offsets through JavaScript's floating-point Number type.
+`--offset 0` starts at the first row. The API defaults to 10,000 rows when limit
+is omitted, and returns at most 250,000 rows per request even if you ask for more.
+
+```bash
+node tools/clis/ga4.js reports run --property 123 \
+ --start-date 2026-09-01 --end-date 2026-09-30 \
+ --dimensions date,country --metrics activeUsers --limit 1000 --offset 0 \
+ --order-bys '[{"dimension":{"dimensionName":"date"}},{"dimension":{"dimensionName":"country"}}]'
+# Repeat with --offset 1000, keeping every other report option unchanged.
+```
+
+For an export, order by the complete set of requested dimensions so ties in a
+metric do not leave page order ambiguous. If metric ordering is useful, put it
+first and retain dimension ordering as tie-breakers. Keep the same property,
+fixed date boundaries, dimensions, metrics, page size and order on every page.
+The CLI passes ordering objects unchanged; Google validates referenced fields
+and ordering types. Relative dates or mutable recent analytics data can change
+between requests, so pagination does not guarantee a snapshot of live data.
+
+Read the response's `rowCount`, headers and metadata together with its rows.
+Advance the offset by the number of rows actually returned and stop when all
+reported rows have been consumed or a page is empty. Do not advance by a limit
+larger than the API's 250,000-row cap. These flags affect `reports run`; they do
+not add offset pagination to realtime reports or Measurement Protocol events.
+`--dry-run` previews the same body with OAuth authorization masked.
+
+See the official [runReport request contract](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport),
+[report pagination guide](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination)
+and [OrderBy schema](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/OrderBy).