### Install Dependencies Source: https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-admin/README.md Install the necessary Node.js dependencies for the samples. ```sh npm install ``` -------------------------------- ### Run Report with Pagination Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Retrieves large result sets in pages using `limit` (max rows per request) and `offset` (starting row index). Combine `rowCount` from the first response to calculate how many pages to fetch. Requires `BetaAnalyticsDataClient` import. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReportWithPagination(propertyId = '123456789') { const baseRequest = { property: `properties/${propertyId}`, dateRanges: [{startDate: '350daysAgo', endDate: 'yesterday'}], dimensions: [ {name: 'firstUserSource'}, {name: 'firstUserMedium'}, {name: 'firstUserCampaignName'}, ], metrics: [{name: 'sessions'}, {name: 'keyEvents'}, {name: 'totalRevenue'}], limit: 100000, }; // Page 1 const [page1] = await analyticsDataClient.runReport({...baseRequest, offset: 0}); console.log(`Page 1: ${page1.rowCount} total rows, fetched ${page1.rows.length}`); page1.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); }); // Page 2 (if total rows exceed the limit) if (page1.rowCount > 100000) { const [page2] = await analyticsDataClient.runReport({...baseRequest, offset: 100000}); console.log(`Page 2: fetched ${page2.rows.length} rows`); page2.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); }); } } runReportWithPagination(); // Run: node google-analytics-data/run_report_with_pagination.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Run Pivot Report with runPivotReport() Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Creates a cross-tabulated report by pivoting one or more dimensions, producing a matrix-style breakdown. Useful for analyzing sessions by country and browser, for example. Requires the `@google-analytics/data` package. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runPivotReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runPivotReport({ property: `properties/${propertyId}`, dateRanges: [{startDate: '2021-01-01', endDate: '2021-01-30'}], pivots: [ { fieldNames: ['country'], limit: 250, orderBys: [{dimension: {dimensionName: 'country'}}], }, { fieldNames: ['browser'], offset: 3, limit: 3, orderBys: [{metric: {metricName: 'sessions'}, desc: true}], }, ], metrics: [{name: 'sessions'}], dimensions: [{name: 'country'}, {name: 'browser'}], }); console.log('Pivot report result:'); response.rows.forEach((row) => { row.dimensionValues.forEach((dv) => console.log(dv.value)); row.metricValues.forEach((mv) => console.log(mv.value)); }); } runPivotReport(); // Run: node google-analytics-data/run_pivot_report.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Get Common Metadata Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Retrieves all dimensions and metrics available across every GA4 property (no custom fields). Pass property ID `0` to get the universal set. ```APIDOC ## Get Common Metadata ### Description Retrieves all dimensions and metrics available across every GA4 property (no custom fields). Pass property ID `0` to get the universal set. ### Method `getMetadata` ### Endpoint `properties/0/metadata` ### Parameters #### Path Parameters - **name** (string) - Required - The resource name of the metadata to retrieve. Use `properties/0/metadata` for common metadata. ### Request Example ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function getCommonMetadata() { const [response] = await analyticsDataClient.getMetadata({ name: 'properties/0/metadata', }); // ... response handling ... } ``` ### Response #### Success Response (200) - **dimensions** (array) - An array of available dimensions. - **apiName** (string) - The API name of the dimension. - **uiName** (string) - The UI name of the dimension. - **description** (string) - The description of the dimension. - **customDefinition** (boolean) - Indicates if the dimension is custom. - **deprecatedApiNames** (array) - An array of deprecated API names for the dimension. - **metrics** (array) - An array of available metrics. - **apiName** (string) - The API name of the metric. - **uiName** (string) - The UI name of the metric. - **description** (string) - The description of the metric. - **type** (string) - The data type of the metric. - **expression** (string) - The expression for the metric. ### Response Example ```javascript { "dimensions": [ { "apiName": "country", "uiName": "Country", "description": "The country of the user.", "customDefinition": false } ], "metrics": [ { "apiName": "activeUsers", "uiName": "Active Users", "description": "The number of users who were actively engaged with your website or app.", "type": "TYPE_INTEGER" } ] } ``` ``` -------------------------------- ### Get Property-Specific Metadata Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Returns all dimensions and metrics available for a specific GA4 property, including custom dimensions and metrics defined for that property. ```APIDOC ## Get Property-Specific Metadata ### Description Returns all dimensions and metrics available for a specific GA4 property, including custom dimensions and metrics defined for that property. ### Method `getMetadata` ### Endpoint `properties/{propertyId}/metadata` ### Parameters #### Path Parameters - **name** (string) - Required - The resource name of the metadata to retrieve. Use `properties/{propertyId}/metadata` for property-specific metadata. ### Request Example ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function getMetadataByPropertyId(propertyId = '123456789') { const [response] = await analyticsDataClient.getMetadata({ name: `properties/${propertyId}/metadata`, }); // ... response handling ... } ``` ### Response #### Success Response (200) - **dimensions** (array) - An array of available dimensions for the property. - **apiName** (string) - The API name of the dimension. - **uiName** (string) - The UI name of the dimension. - **description** (string) - The description of the dimension. - **customDefinition** (boolean) - Indicates if the dimension is custom. - **metrics** (array) - An array of available metrics for the property. - **apiName** (string) - The API name of the metric. - **uiName** (string) - The UI name of the metric. - **description** (string) - The description of the metric. - **type** (string) - The data type of the metric. - **customDefinition** (boolean) - Indicates if the metric is custom. ### Response Example ```javascript { "dimensions": [ { "apiName": "customDimension1", "uiName": "Custom Dimension 1", "description": "A custom dimension.", "customDefinition": true } ], "metrics": [ { "apiName": "customMetric1", "uiName": "Custom Metric 1", "description": "A custom metric.", "type": "TYPE_FLOAT", "customDefinition": true } ] } ``` ``` -------------------------------- ### Get Property-Specific Metadata Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Fetch dimensions and metrics for a specific GA4 property, including any custom dimensions and metrics defined for that property. Use the property's ID in the `getMetadata` request. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function getMetadataByPropertyId(propertyId = '123456789') { const [response] = await analyticsDataClient.getMetadata({ name: `properties/${propertyId}/metadata`, }); console.log(`Dimensions and metrics for property ${propertyId} (including custom fields):`); response.dimensions.forEach((dimension) => { console.log(` DIMENSION: ${dimension.apiName} (${dimension.uiName})`); console.log(` Description: ${dimension.description}`); console.log(` Custom: ${dimension.customDefinition}`); }); response.metrics.forEach((metric) => { console.log(` METRIC: ${metric.apiName} (${metric.uiName})`); console.log(` Description: ${metric.description}`); console.log(` Type: ${metric.type}`); if (metric.customDefinition) console.log(` Custom: true`); }); } getMetadataByPropertyId(); // Run: node google-analytics-data/get_metadata_by_property_id.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Get Common Metadata for All Properties Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Retrieve all dimensions and metrics available across every GA4 property by passing property ID `0` to the `getMetadata` method. This provides the universal set of fields, excluding custom ones. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function getCommonMetadata() { // propertyId = 0 returns dimensions/metrics shared by ALL properties const [response] = await analyticsDataClient.getMetadata({ name: 'properties/0/metadata', }); response.dimensions.forEach((dimension) => { console.log('DIMENSION'); console.log(`${dimension.apiName} (${dimension.uiName}): ${dimension.description}`); console.log(`Custom: ${dimension.customDefinition}`); if (dimension.deprecatedApiNames?.length > 0) { console.log(`Deprecated names: ${dimension.deprecatedApiNames}`); } }); response.metrics.forEach((metric) => { console.log('METRIC'); console.log(`${metric.apiName} (${metric.uiName}): ${metric.description}`); console.log(`Type: ${metric.type}`); if (metric.expression) console.log(`Expression: ${metric.expression}`); }); } getCommonMetadata(); // Run: node google-analytics-data/get_common_metadata.js ``` -------------------------------- ### Run a Sample Source: https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-admin/README.md Execute a sample file using Node.js. Replace SAMPLE_FILE with the name of the script you want to run. ```sh node SAMPLE_FILE ``` -------------------------------- ### Run a Sample Script Source: https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/README.md Execute a sample script using Node.js. Replace SAMPLE_FILE with the name of the script you wish to run. ```sh node quickstart.js ``` -------------------------------- ### Clone Repository and Navigate to Directory Source: https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-admin/README.md Clone the Node.js samples repository and navigate to the google-analytics-admin directory. ```sh git clone https://github.com/googleanalytics/nodejs-docs-samples cd nodejs-docs-samples/google-analytics-admin ``` -------------------------------- ### Clone Repository and Navigate to Directory Source: https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-data/README.md Clone the Node.js samples repository and change the directory to the Google Analytics Data API samples. ```sh git clone https://github.com/googleanalytics/nodejs-docs-samples cd nodejs-docs-samples/google-analytics-data ``` -------------------------------- ### Data API: Service Account via Environment Variable Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Initializes the Data API client using credentials pointed to by `GOOGLE_APPLICATION_CREDENTIALS`. This is the standard authentication method for server-side applications. ```APIDOC ## Data API: Service Account via Environment Variable — `BetaAnalyticsDataClient()` (default) ### Description Initializes the Data API client using credentials pointed to by `GOOGLE_APPLICATION_CREDENTIALS`. This is the standard authentication method for server-side applications. ### Method ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); // Reads GOOGLE_APPLICATION_CREDENTIALS automatically const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{startDate: '2020-03-31', endDate: 'today'}], dimensions: [{name: 'city'}], metrics: [{name: 'activeUsers'}], }); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport(); // Run: node google-analytics-data/quickstart.js YOUR-GA4-PROPERTY-ID ``` ``` -------------------------------- ### Set GOOGLE_APPLICATION_CREDENTIALS Environment Variable Source: https://github.com/googleanalytics/nodejs-docs-samples/blob/main/google-analytics-admin/README.md Set the path to your downloaded credentials file to the GOOGLE_APPLICATION_CREDENTIALS environment variable. ```sh export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json ``` -------------------------------- ### Data API: Service Account via JSON Key File Path Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Explicitly loads a service account JSON key file instead of relying on the environment variable. This is useful when managing multiple sets of credentials in the same process. ```APIDOC ## Data API: Service Account via JSON Key File Path — `BetaAnalyticsDataClient({ keyFilename })` ### Description Explicitly loads a service account JSON key file instead of relying on the environment variable. Useful when managing multiple sets of credentials in the same process. ### Method ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient({ keyFilename: '/path/to/credentials.json', }); async function runReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{startDate: '2020-03-31', endDate: 'today'}], dimensions: [{name: 'country'}], metrics: [{name: 'activeUsers'}], }); console.log('Report result:'); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport(); // Run: node google-analytics-data/quickstart_json_credentials.js YOUR-GA4-PROPERTY-ID /path/to/credentials.json ``` ``` -------------------------------- ### Run Realtime Report with runRealtimeReport() Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Returns data from the last 30 minutes of user activity on a property. Ideal for dashboards monitoring live traffic. No `dateRanges` are needed as it inherently uses the last 30 minutes. Requires the `@google-analytics/data` package. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runRealtimeReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runRealtimeReport({ property: `properties/${propertyId}`, dimensions: [{name: 'country'}], metrics: [{name: 'activeUsers'}], // No dateRanges needed — realtime always uses the last 30 minutes }); console.log(`${response.rowCount} rows received`); console.log('Realtime report:'); response.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); // e.g. "Germany, 17" }); } runRealtimeReport(); // Run: node google-analytics-data/run_realtime_report.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Run Report with Ordering Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Sorts report rows by a metric or dimension in ascending or descending order. Requires `BetaAnalyticsDataClient` to be imported. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReportWithOrdering(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [{name: 'date'}], metrics: [{name: 'activeUsers'}, {name: 'newUsers'}, {name: 'totalRevenue'}], dateRanges: [{startDate: '7daysAgo', endDate: 'today'}], orderBys: [ { metric: {metricName: 'totalRevenue'}, desc: true, // highest revenue day first }, ], }); response.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); // e.g. "20240115, 5420" }); } runReportWithOrdering(); // Run: node google-analytics-data/run_report_with_ordering.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Run GA4 Report via Environment Variable - Node.js Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Initializes the Data API client using credentials from the GOOGLE_APPLICATION_CREDENTIALS environment variable. This is the standard authentication for server-side applications. Ensure the Analytics Data API is enabled. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); // Reads GOOGLE_APPLICATION_CREDENTIALS automatically const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{startDate: '2020-03-31', endDate: 'today'}], dimensions: [{name: 'city'}], metrics: [{name: 'activeUsers'}], }); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport(); // Run: node google-analytics-data/quickstart.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Run Funnel Report with Breakdown Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Visualizes a multi-step user journey with breakdown by a dimension like device category. Requires AlphaAnalyticsDataClient. ```javascript const {AlphaAnalyticsDataClient} = require('@google-analytics/data').v1alpha; const analyticsDataClient = new AlphaAnalyticsDataClient(); async function runFunnelReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runFunnelReport({ property: `properties/${propertyId}`, dateRanges: [{startDate: '30daysAgo', endDate: 'today'}], funnelBreakdown: {breakdownDimension: {name: 'deviceCategory'}}, funnel: { steps: [ { name: 'First open/visit', filterExpression: { orGroup: {expressions: [ {funnelEventFilter: {eventName: 'first_open'}}, {funnelEventFilter: {eventName: 'first_visit'}}, ]}, }, }, { name: 'Organic visitors', filterExpression: { funnelFieldFilter: { fieldName: 'firstUserMedium', stringFilter: {matchType: 'CONTAINS', caseSensitive: false, value: 'organic'}, }, }, }, { name: 'Session start', filterExpression: {funnelEventFilter: {eventName: 'session_start'}}, }, { name: 'Purchase', filterExpression: { orGroup: {expressions: [ {funnelEventFilter: {eventName: 'purchase'}}, {funnelEventFilter: {eventName: 'in_app_purchase'}}, ]}, }, }, ], }, }); // Response contains funnelVisualization and funnelTable sub-reports [response.funnelVisualization, response.funnelTable].forEach((subReport, i) => { console.log(i === 0 ? '=== FUNNEL VISUALIZATION ===' : '=== FUNNEL TABLE ==='); subReport.rows.forEach((row, rowIndex) => { console.log(` Row #${rowIndex}`); row.dimensionValues.forEach((dv, di) => console.log(`${subReport.dimensionHeaders[di].name}: ${dv.value}`)); row.metricValues.forEach((mv, mi) => console.log(`${subReport.metricHeaders[mi].name}: ${mv.value}`)); }); }); } runFunnelReport(); // Run: node google-analytics-data/run_funnel_report.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Run Cohort Report with Cohort Specification Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Measures user retention by grouping cohorts by their first session date. Supports daily, weekly, or monthly granularity. Uses BetaAnalyticsDataClient. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReportWithCohorts(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [{name: 'cohort'}, {name: 'cohortNthWeek'}], metrics: [ {name: 'cohortActiveUsers'}, { name: 'cohortRetentionRate', expression: 'cohortActiveUsers/cohortTotalUsers', // custom expression }, ], cohortSpec: { cohorts: [{ dimension: 'firstSessionDate', name: 'cohort', dateRange: {startDate: '2021-01-03', endDate: '2021-01-09'}, }], cohortsRange: { startOffset: 0, endOffset: 4, // track 5 weeks of data granularity: 'WEEKLY', // DAILY | WEEKLY | MONTHLY }, }, }); console.log(`${response.rowCount} rows received`); response.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); // e.g. "cohort_0, 3482" }); } runReportWithCohorts(); // Run: node google-analytics-data/run_report_with_cohorts.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Basic Report — `runReport()` Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Runs a standard GA4 analytics report for a property, returning aggregated data for the given dimensions, metrics, and date range. ```APIDOC ## Data API — Reporting ### Basic Report — `runReport()` Runs a standard GA4 analytics report for a property, returning aggregated data for the given dimensions, metrics, and date range. ```js const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [{name: 'country'}], metrics: [{name: 'activeUsers'}], dateRanges: [{startDate: '2020-09-01', endDate: '2020-09-15'}], }); console.log(`${response.rowCount} rows received`); response.dimensionHeaders.forEach((h) => console.log(`Dimension: ${h.name}`)); response.metricHeaders.forEach((h) => console.log(`Metric: ${h.name} (${h.type})`)); console.log('Report result:'); response.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); // e.g. "United States, 4823" }); } runReport(); // Run: node google-analytics-data/run_report.js YOUR-GA4-PROPERTY-ID ``` ``` -------------------------------- ### Run Cohort Report Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Measures retention and behavior of user cohorts grouped by their first session date, supporting weekly/daily/monthly granularity. ```APIDOC ## Run Cohort Report ### Description Measures retention and behavior of user cohorts grouped by their first session date, supporting weekly/daily/monthly granularity. ### Method `runReportWithCohorts(propertyId)` ### Parameters - **propertyId** (string) - Optional - The Google Analytics property ID. ### Request Example ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReportWithCohorts(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [{name: 'cohort'}, {name: 'cohortNthWeek'}], metrics: [ {name: 'cohortActiveUsers'}, { name: 'cohortRetentionRate', expression: 'cohortActiveUsers/cohortTotalUsers', // custom expression }, ], cohortSpec: { cohorts: [{ dimension: 'firstSessionDate', name: 'cohort', dateRange: {startDate: '2021-01-03', endDate: '2021-01-09'}, }], cohortsRange: { startOffset: 0, endOffset: 4, // track 5 weeks of data granularity: 'WEEKLY', // DAILY | WEEKLY | MONTHLY }, }, }); console.log(`${response.rowCount} rows received`); response.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); // e.g. "cohort_0, 3482" }); } runReportWithCohorts(); ``` ``` -------------------------------- ### Run GA4 Report via JSON Key File - Node.js Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Explicitly loads a service account JSON key file for Data API client authentication. This is useful when managing multiple credentials within the same process. Ensure the Analytics Data API is enabled. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient({ keyFilename: '/path/to/credentials.json', }); async function runReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{startDate: '2020-03-31', endDate: 'today'}], dimensions: [{name: 'country'}], metrics: [{name: 'activeUsers'}], }); console.log('Report result:'); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport(); // Run: node google-analytics-data/quickstart_json_credentials.js YOUR-GA4-PROPERTY-ID /path/to/credentials.json ``` -------------------------------- ### Run Batch Reports with batchRunReports() Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Executes multiple report queries in a single API call. Useful when multiple datasets are needed simultaneously to reduce latency and quota consumption. Requires the `@google-analytics/data` package. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runBatchReport(propertyId = '123456789') { const [response] = await analyticsDataClient.batchRunReports({ property: `properties/${propertyId}`, requests: [ { // Report 1: Geographic breakdown dimensions: [{name: 'country'}, {name: 'region'}, {name: 'city'}], metrics: [{name: 'activeUsers'}], dateRanges: [{startDate: '2021-01-03', endDate: '2021-01-09'}], }, { // Report 2: Browser breakdown dimensions: [{name: 'browser'}], metrics: [{name: 'activeUsers'}], dateRanges: [{startDate: '2021-01-01', endDate: '2021-01-31'}], }, ], }); console.log('Batch report results:'); response.reports.forEach((report, i) => { console.log(`\n--- Report ${i + 1} ---`); console.log(`${report.rowCount} rows received`); report.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); }); }); } runBatchReport(); // Run: node google-analytics-data/run_batch_report.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Run Basic GA4 Report Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Runs a standard GA4 analytics report for a property, returning aggregated data for the given dimensions, metrics, and date range. Use this for retrieving basic reporting data. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [{name: 'country'}], metrics: [{name: 'activeUsers'}], dateRanges: [{startDate: '2020-09-01', endDate: '2020-09-15'}], }); console.log(`${response.rowCount} rows received`); response.dimensionHeaders.forEach((h) => console.log(`Dimension: ${h.name}`)); response.metricHeaders.forEach((h) => console.log(`Metric: ${h.name} (${h.type})`)); console.log('Report result:'); response.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); // e.g. "United States, 4823" }); } runReport(); // Run: node google-analytics-data/run_report.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### OAuth2 User Credentials Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Authenticates via OAuth2 for user-context access. This method launches a local HTTP server to capture the redirect callback, exchanges the code for tokens, and injects the credentials into the gRPC channel. ```APIDOC ## OAuth2 User Credentials — `BetaAnalyticsDataClient({ sslCreds })` Authenticates via OAuth2 for user-context access (e.g., desktop apps). Launches a local HTTP server to capture the redirect callback, exchanges the code for tokens, and injects the credentials into the gRPC channel. ```js const {OAuth2Client} = require('google-auth-library'); const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const grpc = require('@grpc/grpc-js'); const http = require('http'); const url = require('url'); const open = require('open'); const destroyer = require('server-destroy'); // Requires oauth2.keys.json downloaded from Google Cloud Console (Web or Desktop client) const keys = require('./oauth2.keys.json'); function getAuthenticatedClient() { return new Promise((resolve, reject) => { const oAuth2Client = new OAuth2Client( keys.web.client_id, keys.web.client_secret, keys.web.redirect_uris[0], // Register http://127.0.0.1 as redirect URI ); const authorizeUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: 'https://www.googleapis.com/auth/analytics.readonly', prompt: 'consent', }); const server = http.createServer(async (req, res) => { if (req.url.indexOf('/oauth2callback') > -1) { const code = new url.URL(req.url, 'http://127.0.0.1:3000').searchParams.get('code'); res.end('Authentication successful! Please return to the console.'); server.destroy(); const r = await oAuth2Client.getToken(code); oAuth2Client.setCredentials(r.tokens); resolve(oAuth2Client); } }).listen(3000, () => { open(authorizeUrl, {wait: false}).then((cp) => cp.unref()); }); destroyer(server); }); } async function main(propertyId = '123456789') { const oAuth2Client = await getAuthenticatedClient(); const credentials = grpc.credentials.combineChannelCredentials( grpc.credentials.createSsl(), grpc.credentials.createFromGoogleCredential(oAuth2Client), ); const analyticsDataClient = new BetaAnalyticsDataClient({sslCreds: credentials}); const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{startDate: '2020-03-31', endDate: 'today'}], dimensions: [{name: 'city'}], metrics: [{name: 'activeUsers'}], }); response.rows.forEach((row) => console.log(row.dimensionValues[0], row.metricValues[0])); } main(); // Run: node google-analytics-data/quickstart_oauth2.js YOUR-GA4-PROPERTY-ID ``` ``` -------------------------------- ### OAuth2 User Credentials Authentication Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Authenticates via OAuth2 for user-context access. Launches a local HTTP server to capture the redirect callback, exchanges the code for tokens, and injects the credentials into the gRPC channel. Requires oauth2.keys.json downloaded from Google Cloud Console. ```javascript const {OAuth2Client} = require('google-auth-library'); const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const grpc = require('@grpc/grpc-js'); const http = require('http'); const url = require('url'); const open = require('open'); const destroyer = require('server-destroy'); // Requires oauth2.keys.json downloaded from Google Cloud Console (Web or Desktop client) const keys = require('./oauth2.keys.json'); function getAuthenticatedClient() { return new Promise((resolve, reject) => { const oAuth2Client = new OAuth2Client( keys.web.client_id, keys.web.client_secret, keys.web.redirect_uris[0], // Register http://127.0.0.1 as redirect URI ); const authorizeUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: 'https://www.googleapis.com/auth/analytics.readonly', prompt: 'consent', }); const server = http.createServer(async (req, res) => { if (req.url.indexOf('/oauth2callback') > -1) { const code = new url.URL(req.url, 'http://127.0.0.1:3000').searchParams.get('code'); res.end('Authentication successful! Please return to the console.'); server.destroy(); const r = await oAuth2Client.getToken(code); oAuth2Client.setCredentials(r.tokens); resolve(oAuth2Client); } }).listen(3000, () => { open(authorizeUrl, {wait: false}).then((cp) => cp.unref()); }); destroyer(server); }); } async function main(propertyId = '123456789') { const oAuth2Client = await getAuthenticatedClient(); const credentials = grpc.credentials.combineChannelCredentials( grpc.credentials.createSsl(), grpc.credentials.createFromGoogleCredential(oAuth2Client), ); const analyticsDataClient = new BetaAnalyticsDataClient({sslCreds: credentials}); const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [{startDate: '2020-03-31', endDate: 'today'}], dimensions: [{name: 'city'}], metrics: [{name: 'activeUsers'}], }); response.rows.forEach((row) => console.log(row.dimensionValues[0], row.metricValues[0])); } main(); // Run: node google-analytics-data/quickstart_oauth2.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Run Funnel Report Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Visualizes a multi-step user journey through your app or site. Supports `funnelBreakdown` to split results by a dimension such as device category. ```APIDOC ## Run Funnel Report ### Description Visualizes a multi-step user journey through your app or site. Uses `AlphaAnalyticsDataClient` and supports `funnelBreakdown` to split results by a dimension such as device category. ### Method `runFunnelReport(propertyId)` ### Parameters - **propertyId** (string) - Optional - The Google Analytics property ID. ### Request Example ```javascript const {AlphaAnalyticsDataClient} = require('@google-analytics/data').v1alpha; const analyticsDataClient = new AlphaAnalyticsDataClient(); async function runFunnelReport(propertyId = '123456789') { const [response] = await analyticsDataClient.runFunnelReport({ property: `properties/${propertyId}`, dateRanges: [{startDate: '30daysAgo', endDate: 'today'}], funnelBreakdown: {breakdownDimension: {name: 'deviceCategory'}}, funnel: { steps: [ { name: 'First open/visit', filterExpression: { orGroup: {expressions: [ {funnelEventFilter: {eventName: 'first_open'}}, {funnelEventFilter: {eventName: 'first_visit'}}, ]}, }, }, { name: 'Organic visitors', filterExpression: { funnelFieldFilter: { fieldName: 'firstUserMedium', stringFilter: {matchType: 'CONTAINS', caseSensitive: false, value: 'organic'}, }, }, }, { name: 'Session start', filterExpression: {funnelEventFilter: {eventName: 'session_start'}}, }, { name: 'Purchase', filterExpression: { orGroup: {expressions: [ {funnelEventFilter: {eventName: 'purchase'}}, {funnelEventFilter: {eventName: 'in_app_purchase'}}, ]}, }, }, ], }, }); // Response contains funnelVisualization and funnelTable sub-reports [response.funnelVisualization, response.funnelTable].forEach((subReport, i) => { console.log(i === 0 ? '=== FUNNEL VISUALIZATION ===' : '=== FUNNEL TABLE ==='); subReport.rows.forEach((row, rowIndex) => { console.log(`\nRow #${rowIndex}`); row.dimensionValues.forEach((dv, di) => console.log(`${subReport.dimensionHeaders[di].name}: ${dv.value}`)); row.metricValues.forEach((mv, mi) => console.log(`${subReport.metricHeaders[mi].name}: ${mv.value}`)); }); }); } runFunnelReport(); ``` ``` -------------------------------- ### Realtime Report Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Returns data from the last 30 minutes of user activity on a property, useful for dashboards monitoring live traffic. ```APIDOC ## Realtime Report — `runRealtimeReport()` ### Description Returns data from the last 30 minutes of user activity on a property, useful for dashboards monitoring live traffic. ### Method `runRealtimeReport` ### Parameters - `property` (string) - Required - The Google Analytics property ID (e.g., "properties/123456789"). - `dimensions` (array) - Optional - Dimensions to include in the report (e.g., country). - `metrics` (array) - Optional - Metrics to include in the report (e.g., activeUsers). ### Request Example ```javascript await analyticsDataClient.runRealtimeReport({ property: `properties/${propertyId}`, dimensions: [{name: 'country'}], metrics: [{name: 'activeUsers'}], }); ``` ### Response - `rowCount` (integer) - The number of rows received. - `rows` (array) - The data rows for the report. - Each row object contains: - `dimensionValues` (array) - Values for the requested dimensions. - `metricValues` (array) - Values for the requested metrics. ``` -------------------------------- ### Check Property Quota with Run Report Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Include quota information in the API response to allow applications to self-throttle and prevent RESOURCE_EXHAUSTED errors. Requires the `returnPropertyQuota: true` option. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReportWithPropertyQuota(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, returnPropertyQuota: true, // include quota info in response dimensions: [{name: 'country'}], metrics: [{name: 'activeUsers'}], dateRanges: [{startDate: '7daysAgo', endDate: 'today'}], }); if (response.propertyQuota) { const q = response.propertyQuota; console.log(`Tokens/day — consumed: ${q.tokensPerDay.consumed}, remaining: ${q.tokensPerDay.remaining}`); console.log(`Tokens/hour — consumed: ${q.tokensPerHour.consumed}, remaining: ${q.tokensPerHour.remaining}`); console.log(`Concurrent — consumed: ${q.concurrentRequests.consumed}, remaining: ${q.concurrentRequests.remaining}`); console.log(`Server errors/project/hr — consumed: ${q.serverErrorsPerProjectPerHour.consumed}, remaining: ${q.serverErrorsPerProjectPerHour.remaining}`); console.log(`Thresholded/hr — consumed: ${q.potentiallyThresholdedRequestsPerHour.consumed}, remaining: ${q.potentiallyThresholdedRequestsPerHour.remaining}`); } } runReportWithPropertyQuota(); // Run: node google-analytics-data/run_report_with_property_quota.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Run Report with Multiple Dimension Filters Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Combines multiple filter expressions using boolean logic. Use `andGroup` to require all conditions, `orGroup` for any. Ensure the `BetaAnalyticsDataClient` is imported. ```javascript const {BetaAnalyticsDataClient} = require('@google-analytics/data'); const analyticsDataClient = new BetaAnalyticsDataClient(); async function runReportWithMultipleDimensionFilters(propertyId = '123456789') { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [{name: 'browser'}], metrics: [{name: 'activeUsers'}], dateRanges: [{startDate: '7daysAgo', endDate: 'yesterday'}], dimensionFilter: { andGroup: { // Both conditions must match expressions: [ {filter: {fieldName: 'browser', stringFilter: {value: 'Chrome'}}, {filter: {fieldName: 'countryId', stringFilter: {value: 'US'}}, ], }, }, }); response.rows.forEach((row) => { console.log(`${row.dimensionValues[0].value}, ${row.metricValues[0].value}`); // e.g. "Chrome, 8210" }); } runReportWithMultipleDimensionFilters(); // Run: node google-analytics-data/run_report_with_multiple_dimension_filters.js YOUR-GA4-PROPERTY-ID ``` -------------------------------- ### Batch Report Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Executes multiple report queries in a single API call, reducing latency and quota consumption when multiple datasets are needed simultaneously. ```APIDOC ## Batch Report — `batchRunReports()` ### Description Executes multiple report queries in a single API call, reducing latency and quota consumption when multiple datasets are needed simultaneously. ### Method `batchRunReports` ### Parameters - `property` (string) - Required - The Google Analytics property ID (e.g., "properties/123456789"). - `requests` (array) - Required - An array of report requests. - Each request object can contain: - `dimensions` (array) - Dimensions to include in the report. - `metrics` (array) - Metrics to include in the report. - `dateRanges` (array) - Date ranges for the report. ### Request Example ```javascript await analyticsDataClient.batchRunReports({ property: `properties/${propertyId}`, requests: [ { dimensions: [{name: 'country'}, {name: 'region'}, {name: 'city'}], metrics: [{name: 'activeUsers'}], dateRanges: [{startDate: '2021-01-03', endDate: '2021-01-09'}], }, { dimensions: [{name: 'browser'}], metrics: [{name: 'activeUsers'}], dateRanges: [{startDate: '2021-01-01', endDate: '2021-01-31'}], }, ], }); ``` ### Response - `reports` (array) - An array of report responses, one for each request. - Each report object contains: - `rowCount` (integer) - The number of rows returned in the report. - `rows` (array) - The data rows for the report. ``` -------------------------------- ### Admin API: List All Google Analytics Accounts Source: https://context7.com/googleanalytics/nodejs-docs-samples/llms.txt Returns all Google Analytics accounts accessible to the authenticated user. This method uses the `AnalyticsAdminServiceClient` and automatically handles pagination for all results. ```APIDOC ## Admin API: List All Google Analytics Accounts — `listAccounts()` ### Description Returns all Google Analytics accounts accessible to the authenticated user. Uses `AnalyticsAdminServiceClient` from `@google-analytics/admin` and auto-paginates through all results. ### Method ```javascript const analyticsAdmin = require('@google-analytics/admin'); const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient(); // Uses GOOGLE_APPLICATION_CREDENTIALS env variable for auth async function listAccounts() { // listAccounts() with no args fetches all pages automatically const [response] = await analyticsAdminClient.listAccounts(); console.log('Accounts:'); for (const account of response) { console.log('Account name:', account.name); // e.g. accounts/123456789 console.log('Display name:', account.displayName); // e.g. "My Company" console.log('Region code:', account.regionCode); // e.g. "US" console.log('Create time:', account.createTime.seconds); console.log('Update time:', account.updateTime.seconds); } } process.on('unhandledRejection', (err) => { console.error(err.message); process.exitCode = 1; }); listAccounts(); // Run: node google-analytics-admin/quickstart.js ``` ```