Tracking pageviews is an essential aspect of understanding how your website is performing. While platforms like Google Analytics offer detailed insights, sometimes you just need a quick, lightweight way to view your traffic directly inside a tool you already use daily — like Google Sheets. In this detailed guide, we will walk through how to create a custom Google Sheets function that pulls pageview data using Google Analytics API into your spreadsheet.
This guide assumes you are using Google Analytics 4 (GA4) and know the basics of Google Sheets and Google Apps Script.
Before jumping into the code, let’s explore why tracking pageviews directly in Google Sheets is useful:
Custom dashboards: Create quick, tailored dashboards without complex tools.
Client reports: Automate weekly or monthly traffic reports.
Trend analysis: Compare and analyze performance over time using built-in sheet functions.
Lightweight usage: For small websites or quick checks, it's faster than opening full analytics dashboards.
A Google Analytics 4 property
Access to the GA4 data API
A Google Cloud Platform (GCP) project
Enabled Google Analytics API in GCP
Google Service Account with access to GA4 property
Google Sheets and access to Apps Script Editor
Click “New Project” and name it something like GA4 Pageview Tracker.
Once created, go to the “APIs & Services > Library”.
Search for Google Analytics Data API and enable it.
Go to Credentials > Create Credentials > Service Account.
Assign a role like Viewer or Editor.
After creation, go to the service account and create a JSON key. Download this file. You’ll use this key in Apps Script.
Go to https://analytics.google.com/ and open your GA4 property.
Navigate to Admin > Property Access Management.
Click the blue “+” and add the service account email (from your JSON key) with Viewer access.
Upload the downloaded JSON key file to your Google Drive.
Make note of its file ID — you can find this in the file’s share URL:
https://drive.google.com/file/d/FILE_ID/view
Open your Google Spreadsheet.
Go to Extensions > Apps Script.
Delete any default code and paste the following:
const KEY_FILE_ID = 'YOUR_JSON_FILE_ID'; // Replace with actual ID
const PROPERTY_ID = 'YOUR_GA4_PROPERTY_ID'; // Replace with your GA4 property ID
function getPageviewsGA4(startDate, endDate, pagePath) {
const service = getService();
if (!service.hasAccess()) {
Logger.log('Authentication error: ' + service.getLastError());
return 'Authentication failed';
}
const url = `https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport`;
const payload = {
dimensions: [{ name: 'pagePath' }],
metrics: [{ name: 'screenPageViews' }],
dateRanges: [{ startDate: startDate, endDate: endDate }],
dimensionFilter: {
filter: {
fieldName: 'pagePath',
stringFilter: {
value: pagePath
}
}
}
};
const options = {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload),
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
muteHttpExceptions: true
};
const response = UrlFetchApp.fetch(url, options);
const result = JSON.parse(response.getContentText());
try {
const value = result.rows[0].metricValues[0].value;
return parseInt(value);
} catch (e) {
return 0;
}
}
function getService() {
const file = DriveApp.getFileById(KEY_FILE_ID);
const json = JSON.parse(file.getBlob().getDataAsString());
return OAuth2.createService('ga4')
.setTokenUrl('https://oauth2.googleapis.com/token')
.setPrivateKey(json.private_key)
.setIssuer(json.client_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setScope('https://www.googleapis.com/auth/analytics.readonly');
}
After saving the script, go back to your spreadsheet. In a cell, type:
=getPageviewsGA4("2025-07-01", "2025-07-04", "/blog/custom-google-spreadsheet-pageviews")
This will return the pageviews for the specified page between July 1 and July 4, 2025.
If you see “Authentication failed”, double-check your service account permissions and key.
If pageviews always return 0, make sure the page path is exactly correct (case-sensitive).
If the function hangs or throws errors, check the Execution log in Apps Script editor (View > Logs).
You can customize or improve the function by:
Making PROPERTY_ID a parameter
Returning multiple rows (for top pages)
Adding filters like country, deviceCategory, etc.
Caching results for better performance
Triggering automatic refresh with Google Apps Script triggers
No need for third-party add-ons
Data stays in your control
Free and highly customizable
Integrates easily into dashboards, charts, or reports
Using a custom Google Spreadsheet function to track pageviews provides flexibility and simplicity, especially for users who frequently work in Google Sheets. With Google Analytics 4 and the power of Apps Script, you can create tailored, real-time pageview trackers suited to your exact needs — whether you're a solo blogger or managing client reports.
This method empowers you to turn a spreadsheet into a live traffic monitoring tool — lightweight, cost-free, and endlessly customizable.