SERP Tracking in Google Sheets: Complete Apps Script
To track SERPs in Google Sheets, paste a short Apps Script into the sheet, store your TrackSERPs API key in Script Properties, and have a daily time-driven trigger call GET /v1/projects/{project_id}/rankings/latest and write the rows. There is no TrackSERPs Sheets add-on, so the script on this page is the route; the no-code alternative is the CSV export in the app.
Key facts
- Apps Script allows 20,000 URL Fetch calls per day on consumer accounts and 100,000 on Google Workspace accounts, with a 6-minute limit per script execution.Source: developers.google.com
- A time-driven trigger can run as often as every minute, but Google may randomise the start within a window, so a 9 AM trigger can fire anywhere between 9 and 10 AM.Source: developers.google.com
- Custom functions in Sheets are limited to 30 seconds per execution, which is why a per-cell API lookup is a poor design for rankings.Source: developers.google.com
- UrlFetchApp.fetch accepts a headers map and a muteHttpExceptions flag, which lets a script read non-200 responses instead of throwing.Source: developers.google.com
There is no add-on, and you do not need one
TrackSERPs has no Google Sheets add-on and nothing in the Google Workspace Marketplace. What it has is a REST API whose read endpoints are free of credits, and Google Sheets has a scripting engine, Apps Script, that can call any HTTPS API on a schedule. Together they give you a sheet that refreshes itself every morning.
Our position: a 100-line script that writes one flat table beats both an add-on and a per-cell custom function. One scheduled run, a handful of API calls, plain cells for everything downstream. Formulas, charts, conditional formatting and Looker Studio all read the cells, not the API.
This page owns the script. It covers:
- the complete script, with pagination, retry and a history log;
- setup, including where to keep the API key;
- formulas and conditional formatting for movement;
- Apps Script quotas, with a worked example;
- the CSV export from the app, for when you do not want code;
- a troubleshooting table.
If you want the dashboard side, the Looker Studio guide builds on the sheet this page produces.
Which route fits you
| Route | Code needed | Scheduled | Best for |
|---|---|---|---|
| Apps Script (this page) | About 100 lines, pasted once | Yes, daily or hourly | Live team sheets, client workbooks, Looker Studio source |
| CSV export from the app | None | No, manual | One-off analysis, a single monthly report |
| Excel Power Query | Light, in the Power Query editor | On refresh | Teams that live in Excel, not Sheets |
| Python or n8n writing to Sheets | Yes, or a visual workflow | Yes | Pipelines that already run elsewhere |
What the API returns for a sheet
The script calls one endpoint, GET /v1/projects/{project_id}/rankings/latest. It returns the latest snapshot for every keyword and device in the project, in pages. The fields that matter for a sheet:
| Field | Meaning |
|---|---|
phrase, device | Keyword and desktop or mobile |
date | Date of the snapshot, YYYY-MM-DD, or null if never checked |
rank | Organic position 1 to 100, or null when not in the top 100 |
rank_absolute | Position counting ads and SERP features, see absolute vs organic rank |
ranking_url | Your URL found on the SERP, or null |
change_7d, change_30d | Net movement versus 7 or 30 days ago; positive means you moved up |
serp_features | Array such as featured_snippet or people_also_ask |
ai_overview | Object with present, cited and cited_url |
checked | False until at least one check has completed for that keyword and device |
Auth is the standard bearer header, Authorization: Bearer <key>. Responses are cursor-paginated: limit defaults to 50 with a maximum of 500, and the response carries next_cursor, which is null on the last page. The pagination reference has the details.
Two rules shape the script. First, a null rank on a checked keyword is a real result, "not in the top 100", so the script writes a blank cell and not zero. A zero would wreck averages. Second, date: null with checked: false means no check has finished yet; the script keeps those rows so you can see them, and the formulas below skip them.
Set up the sheet in five steps
Create an API key
In the app, go to Settings, API, Keys and create a key. The only scope the script needs is
rankings:read. If you work with clients, restrict the key to the single project this sheet is for, so a leaked workbook cannot read anything else. Reads work on every plan.Find the project ID
Call
GET /v1/projectswith the key and copy theidof the project you want. The IDs look likecmwc0f1yp0005rqk7w1plnab1in the API reference.Open Apps Script from the sheet
In the Google Sheet choose Extensions, Apps Script. This creates a script bound to the spreadsheet. Delete the placeholder function.
Paste the script and store the secrets
Paste the script below into
Code.gs. Then open Project Settings in the Apps Script editor and add two Script Properties:TRACKSERPS_API_KEYandTRACKSERPS_PROJECT_ID. Do not paste the key into the code. Anyone you share the sheet with at editor level can read the script, so a key in code is a key in their hands.Run once, authorise, then schedule
Run
refreshRankingsfrom the editor and approve the permission prompt (it needs access to the spreadsheet and to external services). Then runinstallDailyTriggeronce. From then on the sheet refreshes itself.
The complete script
The script writes two sheets. Rankings is the current snapshot, overwritten on every run. History is append-only: one row per keyword, device and snapshot date, so the trend builds up inside the workbook.
/**
* TrackSERPs to Google Sheets.
* Script Properties required: TRACKSERPS_API_KEY, TRACKSERPS_PROJECT_ID
* Endpoint: GET https://api.trackserps.com/v1/projects/{project_id}/rankings/latest
*/
const BASE_URL = "https://api.trackserps.com/v1";
const PAGE_SIZE = 500; // API maximum for `limit`
const MAX_PAGES = 50; // safety stop: 50 x 500 = 25,000 rows
const LATEST_SHEET = "Rankings";
const HISTORY_SHEET = "History";
const HEADERS = [
"keyword", "device", "date", "rank", "rank_absolute", "change_7d",
"change_30d", "ranking_url", "serp_features", "ai_overview_present",
"ai_overview_cited", "checked", "fetched_at",
];
function getConfig_() {
const props = PropertiesService.getScriptProperties();
const apiKey = props.getProperty("TRACKSERPS_API_KEY");
const projectId = props.getProperty("TRACKSERPS_PROJECT_ID");
if (!apiKey || !projectId) {
throw new Error(
"Add TRACKSERPS_API_KEY and TRACKSERPS_PROJECT_ID under Project Settings > Script Properties."
);
}
return { apiKey: apiKey, projectId: projectId };
}
function headerValue_(response, name) {
const headers = response.getHeaders();
const key = Object.keys(headers).find(function (k) {
return k.toLowerCase() === name.toLowerCase();
});
return key ? headers[key] : null;
}
// One GET with up to 3 attempts. Only HTTP 429 is retried, and the wait
// follows the Retry-After header (capped at 60 s to stay inside the 6-minute
// Apps Script execution limit).
function fetchJson_(url, apiKey) {
for (let attempt = 1; attempt <= 3; attempt++) {
const response = UrlFetchApp.fetch(url, {
method: "get",
headers: { Authorization: "Bearer " + apiKey, Accept: "application/json" },
muteHttpExceptions: true,
});
const code = response.getResponseCode();
if (code === 200) return JSON.parse(response.getContentText());
if (code === 429 && attempt < 3) {
const wait = Number(headerValue_(response, "Retry-After")) || 30;
Utilities.sleep(Math.min(wait, 60) * 1000);
continue;
}
throw new Error("TrackSERPs API " + code + ": " + response.getContentText().slice(0, 300));
}
}
// Follow next_cursor until it is null.
function fetchAllLatest_(config) {
const all = [];
let cursor = null;
let pages = 0;
do {
let url = BASE_URL + "/projects/" + encodeURIComponent(config.projectId) +
"/rankings/latest?limit=" + PAGE_SIZE;
if (cursor) url += "&cursor=" + encodeURIComponent(cursor);
const body = fetchJson_(url, config.apiKey);
Array.prototype.push.apply(all, body.rankings);
cursor = body.next_cursor;
pages++;
} while (cursor && pages < MAX_PAGES);
return all;
}
function blankIfNull_(value) {
return value === null || value === undefined ? "" : value;
}
function toRow_(r, fetchedAt) {
const ai = r.ai_overview || {};
return [
r.phrase,
r.device,
blankIfNull_(r.date),
blankIfNull_(r.rank), // blank = not in the top 100, never 0
blankIfNull_(r.rank_absolute),
blankIfNull_(r.change_7d), // positive = moved up
blankIfNull_(r.change_30d),
blankIfNull_(r.ranking_url),
(r.serp_features || []).join("; "),
ai.present ? "yes" : "no",
ai.cited ? "yes" : "no",
r.checked ? "yes" : "no",
fetchedAt,
];
}
function getOrCreateSheet_(name) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
return ss.getSheetByName(name) || ss.insertSheet(name);
}
function refreshRankings() {
const config = getConfig_();
const fetchedAt = new Date().toISOString();
const rankings = fetchAllLatest_(config);
const rows = rankings.map(function (r) { return toRow_(r, fetchedAt); });
// Overwrite only columns A:M. Anything you add to the right (helper
// formulas, notes) survives the refresh.
const sheet = getOrCreateSheet_(LATEST_SHEET);
const lastRow = Math.max(sheet.getLastRow(), 1);
sheet.getRange(1, 1, lastRow, HEADERS.length).clearContent();
sheet.getRange(1, 1, 1, HEADERS.length).setValues([HEADERS]).setFontWeight("bold");
if (rows.length) {
sheet.getRange(2, 1, rows.length, HEADERS.length).setValues(rows);
}
sheet.setFrozenRows(1);
appendHistory_(rankings);
return rows.length;
}
// Append one row per keyword, device and snapshot date that is not already logged.
function appendHistory_(rankings) {
const sheet = getOrCreateSheet_(HISTORY_SHEET);
if (sheet.getLastRow() === 0) {
sheet.getRange(1, 1, 1, 4).setValues([["date", "keyword", "device", "rank"]]).setFontWeight("bold");
sheet.setFrozenRows(1);
}
const seen = {};
const tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();
if (sheet.getLastRow() > 1) {
sheet.getRange(2, 1, sheet.getLastRow() - 1, 3).getValues().forEach(function (row) {
// Sheets turns "2026-11-09" into a date in the spreadsheet's time zone,
// so format it back in that zone (UTC would shift it a day east of UTC).
const d = row[0] instanceof Date
? Utilities.formatDate(row[0], tz, "yyyy-MM-dd")
: String(row[0]);
seen[d + "|" + row[1] + "|" + row[2]] = true;
});
}
const fresh = [];
rankings.forEach(function (r) {
if (!r.checked || !r.date) return;
const key = r.date + "|" + r.phrase + "|" + r.device;
if (seen[key]) return;
seen[key] = true;
fresh.push([r.date, r.phrase, r.device, blankIfNull_(r.rank)]);
});
if (fresh.length) {
sheet.getRange(sheet.getLastRow() + 1, 1, fresh.length, 4).setValues(fresh);
}
}
// Run once. Replaces any existing trigger for refreshRankings.
function installDailyTrigger() {
ScriptApp.getProjectTriggers()
.filter(function (t) { return t.getHandlerFunction() === "refreshRankings"; })
.forEach(function (t) { ScriptApp.deleteTrigger(t); });
ScriptApp.newTrigger("refreshRankings")
.timeBased()
.everyDays(1)
.atHour(9)
.create();
}
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("TrackSERPs")
.addItem("Refresh rankings now", "refreshRankings")
.addToUi();
}
A few choices in that script are deliberate:
- Secrets in Script Properties.
PropertiesService.getScriptProperties()is a store scoped to the script, and the project settings page is the right place to fill it. The key never appears in the code someone copies when they duplicate your template. - Blank, not zero, for unranked. A zero would drag an average position down and sort above rank 1.
- Retry only on 429. A 401 or 404 will not fix itself on a retry; the script throws the first 300 characters of the error body so you see the API's message in the Apps Script execution log.
clearContenton columns A to M only. Your own helper columns and notes to the right survive each refresh.
Formulas for movement and counts
Assume the Rankings layout the script writes: A keyword, B device, C date, D rank, E rank_absolute, F change_7d, G change_30d, H ranking_url, I serp_features, J ai_overview_present, K ai_overview_cited, L checked, M fetched_at. Put these on a separate Summary sheet.
| What | Formula |
|---|---|
| Keywords in the top 3 | =COUNTIFS(Rankings!D:D,">=1",Rankings!D:D,"<=3") |
| Keywords in the top 10 | =COUNTIFS(Rankings!D:D,">=1",Rankings!D:D,"<=10") |
| Page two (11 to 20) | =COUNTIFS(Rankings!D:D,">=11",Rankings!D:D,"<=20") |
| Checked but not in the top 100 | =COUNTIF(Rankings!L:L,"yes")-COUNTIFS(Rankings!L:L,"yes",Rankings!D:D,">=1") |
| Average rank of ranked keywords | =AVERAGEIF(Rankings!D:D,">=1") |
| Keywords that moved up in 7 days | =COUNTIF(Rankings!F:F,">0") |
| Keywords that moved down in 7 days | =COUNTIF(Rankings!F:F,"<0") |
| Rank of one keyword on desktop | =IFERROR(FILTER(Rankings!D:D,Rankings!A:A="emergency plumber",Rankings!B:B="desktop"),"not found") |
| Ten biggest 7-day gains | =QUERY(Rankings!A:H,"select A,B,D,F where F is not null order by F desc limit 10",1) |
| Ten biggest 7-day drops | =QUERY(Rankings!A:H,"select A,B,D,F where F is not null order by F asc limit 10",1) |
The last two are the most-used cells in an agency workbook: they are the "what changed" list for the Monday client email.
For a readable movement column, put this in N2 of the Rankings sheet. Because the script only clears A to M, it survives refreshes:
=ARRAYFORMULA(IF(F2:F="","",IF(F2:F>0,"▲ "&F2:F,IF(F2:F<0,"▼ "&ABS(F2:F),"–"))))
Conditional formatting
Open Format, Conditional formatting, choose Custom formula is, and add these rules on the Rankings sheet:
| Range | Custom formula | Colour |
|---|---|---|
F2:G | =AND(ISNUMBER($F2),$F2>0) | Green fill: moved up |
F2:G | =AND(ISNUMBER($F2),$F2<0) | Red fill: moved down |
D2:D | =AND(ISNUMBER($D2),$D2<=3) | Dark green: top 3 |
D2:D | =AND(ISNUMBER($D2),$D2>=11,$D2<=20) | Amber: page two, the cheapest wins |
A2:M | =AND($L2="yes",$D2="") | Grey: checked, not in the top 100 |
The page-two rule earns its keep. Keywords at 11 to 20 are the ones where a content refresh or an internal link is most likely to move the number. Sort the sheet by rank and the amber block is your work queue.
A trend chart from the History sheet
History has the shape a chart wants: date, keyword, device, rank. To chart one keyword, filter it into a helper range with =FILTER(History!A:D,History!B:B="emergency plumber",History!C:C="desktop"), select the date and rank columns, and insert a line chart. Flip the vertical axis so rank 1 sits at the top.
A worked example: one client, 300 keywords
Take a fictional plumber, acmeplumbing.com, tracking 300 phrases on desktop and mobile. That is 600 keyword and device pairs, so one project returns 600 rows.
- At
limit=500the first call returns 500 rows and anext_cursor; the second returns the remaining 100 and a null cursor. Two API calls per refresh. - The sheet shows 600 rows of the
Rankingstable. The twoCOUNTIFScells give the top-3 and top-10 counts directly, with no manual tallying. Historygrows by up to 600 rows a day, one for each snapshot date not yet logged. After a year that is on the order of 200,000 rows, so for long retention archive the sheet into a new workbook yearly.
If the same agency has 20 such clients, each in its own workbook, a daily refresh makes 40 calls a day, around 1,200 a month. For context, the smallest plan allows 10,000 API calls a month per account (see the limits in pricing). Reads do not spend credits, only calls.
Apps Script limits that matter here
Google publishes these quotas on its own page, and they are the real limits of this approach:
| Quota | Consumer account | Google Workspace |
|---|---|---|
| URL Fetch calls per day | 20,000 | 100,000 |
| Script runtime per execution | 6 minutes | 6 minutes |
| Total trigger runtime per day | 90 minutes | 6 hours |
| Triggers per user per script | 20 | 20 |
| Custom function runtime | 30 seconds | 30 seconds |
Plug in the worked example: two fetches and a few seconds of runtime per day is under 0.1% of the fetch quota and a trivial slice of trigger time. You will hit TrackSERPs' own limits long before Google's. Your plan has a per-minute rate limit and a monthly call allowance, visible in Settings, API, Usage, and the script's 429 handling covers short bursts.
This is also why the page has no =TRACKSERPS_RANK("keyword") custom function. A custom function runs per cell and recalculates whenever its inputs change. A sheet with 300 such cells would call the API 300 times per recalculation, each under a 30-second cap, and every viewer's open would repeat it. One scheduled script followed by FILTER or INDEX/MATCH against local cells does the same job with two calls.
The no-code route: CSV export from the app
Not every sheet needs a script. The project report in the app has an Export menu with Export CSV. It downloads the table you are looking at, including the filters you applied: device, tag, search term, rank band and movement.
What the file contains, taken from the export code:
- Columns: Keyword, Device, Location, Start, Rank, Life, 1d, 7d, 30d, Search Volume, Tracked URL, Ranking URL, Last Updated, SERP Features, Engine.
- A keyword with tracked URLs gets extra rows beneath it, each prefixed with an arrow so you can tell them apart from the keyword's primary row.
- Unranked keywords show the text
Not in top 100in the rank columns and not a blank. Last Updatedis formatted asYYYY-MM-DD HH:mmin your account's time zone.- The file is UTF-8 with a byte order mark, so non-English keywords open correctly.
- It exports up to 5,000 rows of the filtered table.
To use it, open a new sheet and choose File, Import, Upload, then replace the current sheet. Two clean-ups are worth a formula. Convert the text to a number for charting with =IFERROR(VALUE(E2),""), which turns "Not in top 100" into a blank. Filter out the sub-rows with =NOT(REGEXMATCH(A2,"↳")) in a helper column.
The trade-offs are plain. CSV is manual, so a sheet built on it is only as fresh as the last person who exported. The column names differ from the API's (7d against change_7d), so formulas written for one will not work on the other. And the export needs a login, so you cannot schedule it. If you export weekly by hand today, that is the signal to move to the script.
When not to use Sheets for rank tracking
Be honest about where a spreadsheet stops working:
- Thousands of keywords across many projects. One script handles one project. Stacking 40 projects into one workbook means 40 trigger runs and a sheet that gets slow. Use BigQuery or a database and chart from there.
- Alerting. A sheet shows a drop when someone opens it. If you want to be told, use webhooks or Slack alerts and keep the sheet for analysis.
- Anything needing a shared, locked-down audience. The script and its Script Properties are visible to editors. For client-facing views, share a Looker Studio report or a client report and keep the workbook internal.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Add TRACKSERPS_API_KEY and TRACKSERPS_PROJECT_ID | Script Properties missing or misspelled | Project Settings, Script Properties; names are case-sensitive |
TrackSERPs API 401 | Key wrong, revoked or pasted with a space | Create a fresh key, paste again |
TrackSERPs API 403 | Account has no API access, or the key's IP allowlist excludes Google's servers | Check the plan, and remove the IP restriction for this key |
TrackSERPs API 404 | Wrong project ID, the key is restricted to other projects, or a ts_test_ key used with a real project ID | List projects with GET /v1/projects using the same key and copy the id |
TrackSERPs API 429 | Per-minute rate limit or monthly call quota reached | The script retries twice using the Retry-After header; if it still fails, check Settings, API, Usage |
Rows with blank date and checked = no | Keyword added but no check has finished | Wait for the next scheduled check, or run one from the app |
| Rank column is blank for many rows | Not in the top 100 for that location and device | This is a real result, not a fault |
| Trigger ran but data looks old | Trigger fired before the check finished | Move the trigger later; read the date column |
Exceeded maximum execution time | Project too big for one 6-minute run, or API slow | Split projects, or filter with device and run the script twice |
If a script run fails inside a trigger, you will not see the error on screen. Open Executions in the Apps Script editor to see the thrown message, or add a trigger failure notification in the trigger settings.
Testing safely with a test key
Keys that start with ts_test_ run in test mode: they read a synthetic demo project only, save nothing and spend no credits. Your own project IDs return 404 with a test key, so call GET /v1/projects with the test key and put the demo project's id in TRACKSERPS_PROJECT_ID while you build. Then swap in the live key and your real project ID before the sheet goes to a client, because test-mode numbers are not yours.
Where this fits with other tools
The sheet sits in the middle of a pipeline. Upstream is the API. Downstream, Looker Studio can read the Rankings sheet for an executive dashboard, and the Excel guide covers the same job in Microsoft's stack. For delivery to clients see the SERP reports guide, and for check frequency see daily vs weekly tracking. Plans are on the pricing page; build the sheet against a ts_test_ key before your first live check lands.
Frequently asked questions
Is there a TrackSERPs add-on for Google Sheets?
Where do I find my project ID and API key?
Does refreshing the sheet cost credits?
Why use a script instead of a custom function like =TRACKSERPS_RANK()?
How often should the trigger run?
How do I get history, not just the latest rank?
Can I do this without writing code?
Sources & references
- Google Apps Script: Quotas for Google Services(checked 2026-11-11)
- Google Apps Script: Installable Triggers(checked 2026-11-11)
- Google Apps Script Reference: UrlFetchApp(checked 2026-11-11)
- Google Apps Script Reference: ClockTriggerBuilder(checked 2026-11-11)
- Google Apps Script Reference: PropertiesService(checked 2026-11-11)