Run GA4 Report

runGa4Report(propertyId, {startDate, endDate, dimensions, metrics}) calls the Analytics Data advanced service and returns a header row plus data rows, ready for setValues. When the report has no data it returns the header row only. Metric values come back as numbers.

When to use

  • A weekly sessions, users, or top-pages report in a sheet
  • Pulling GA4 numbers next to other data without opening Analytics
  • Any script that needs a GA4 report as a plain 2D array

How to use this snippet

Enable the Google Analytics Data API advanced service (Services in the Apps Script editor, identifier AnalyticsData), and make sure the Analytics Data API is enabled in the script's Cloud project. The running account needs access to the GA4 property. propertyId is the numeric property id (Admin, Property details), not a G- measurement id; a properties/ prefix is accepted. The scope is read-only (analytics.readonly).

/** * Run a GA4 report through the Analytics Data advanced service. Returns a * header row (dimension names, then metric names) followed by data rows with * metrics as numbers. Header only when the report has no rows. Defaults: * startDate '7daysAgo', endDate 'yesterday', dimensions ['pagePath'], * metrics ['sessions']. opts.limit sets the row limit. * * @param {string|number} propertyId numeric GA4 property id * @param {{startDate?: string, endDate?: string, dimensions?: string[], metrics?: string[], limit?: number}} [opts] * @return {Array<Array<*>>} */ function runGa4Report(propertyId, opts) { opts = opts || {}; var id = String(propertyId == null ? '' : propertyId).trim().replace(/^properties\//, ''); if (!/^\d+$/.test(id)) { throw new Error('runGa4Report: propertyId must be the numeric GA4 property id (Admin > Property details), not a G- measurement id'); } if (typeof AnalyticsData === 'undefined' || !AnalyticsData || !AnalyticsData.Properties) { throw new Error('runGa4Report: enable the Google Analytics Data API advanced service (Services > Analytics Data API, identifier AnalyticsData)'); } var dimensions = opts.dimensions == null ? ['pagePath'] : opts.dimensions; var metrics = opts.metrics == null ? ['sessions'] : opts.metrics; if (!metrics.length) throw new Error('runGa4Report: at least one metric is required'); var request = { dateRanges: [{ startDate: opts.startDate || '7daysAgo', endDate: opts.endDate || 'yesterday' }], dimensions: dimensions.map(function (name) { return { name: name }; }), metrics: metrics.map(function (name) { return { name: name }; }) }; if (opts.limit) request.limit = String(opts.limit); var response = AnalyticsData.Properties.runReport(request, 'properties/' + id); var header = dimensions.concat(metrics); var out = [header]; var rows = (response && response.rows) || []; for (var i = 0; i < rows.length; i++) { var row = []; var d = rows[i].dimensionValues || []; var m = rows[i].metricValues || []; var j; for (j = 0; j < dimensions.length; j++) row.push(d[j] ? d[j].value : ''); for (j = 0; j < metrics.length; j++) { var raw = m[j] ? m[j].value : ''; var num = Number(raw); row.push(raw !== '' && isFinite(num) ? num : raw); } out.push(row); } return out; }

Example

function writeTopPages() { var rows = runGa4Report('123456789', { dimensions: ['pagePath'], metrics: ['screenPageViews'], limit: 25 }); var sheet = SpreadsheetApp.getActive().getSheetByName('GA4 pages') || SpreadsheetApp.getActive().insertSheet('GA4 pages'); sheet.clearContents(); sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows); }

Dates can be yyyy-MM-dd strings or GA4 relative values such as 7daysAgo, yesterday, and today.

Notes

  • This is a read. It only runs a report.
  • GA4 data is not final for a day or so, so ending a report at yesterday is safer than today.
  • Row order is not guaranteed unless you sort. Sort the returned rows in your script if you want a top-N list.
  • Metric and dimension names must be valid GA4 API names. An invalid name comes back as an API error.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free snippets — plus optional Co-Pilot when you want a boost (Day Pass — $3, or 1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension