marcelo.ar/ full stack + IA

Automate Search Console Reports in Google Sheets with Apps Script

Automate Search Console reports in Google Sheets. Pull your Google clicks every week with Apps Script and get an email alert when they drop.

Published October 21, 20269 min read[SEO · Search Console · Google Sheets · Apps Script · Automation]
Automate Search Console Reports in Google Sheets with Apps Script

You can automate a Search Console report by connecting it to a Google Sheet with Apps Script: a script calls the Search Console API, writes your queries and their clicks into a sheet, and runs by itself once a week. Add the optional email alert and you also find out when this week's clicks fall below last week's, without logging into anything. Below is the full code and how to get it running.

Why a business owner wants this

Search Console is Google's free tool that shows how many people reached your site from search and which searches they used. The problem is not missing data. It is that you have to remember to log in, pick dates, compare against the previous period and export. If you are busy running a shop or a service business, that task gets pushed back until nobody looks at it at all.

A sheet that updates itself changes that. You open the file you already use for everything else and see which queries brought visits last week. If something drops, an email shows up. And if you later want to line those clicks up against sales or customer inquiries, they are already in a spreadsheet.

If you are not sure your site shows up in Google at all, start with this guide on why your website is not showing up on Google and come back to automate afterward.

What you need

  • A Google account with access to the property in Search Console (you will authorize the script with that same account).
  • The exact property name. If you added it as a Domain property, it is written sc-domain:example.com. If it is a URL-prefix property, write it exactly as it appears, trailing slash included: https://example.com/.
  • A new Google Sheet.

Step 1: create the sheet and open Apps Script

Create a blank sheet and name it something like "SEO report". Then go to Extensions → Apps Script. The editor opens with a Code.gs file holding an empty function. The script is bound to that sheet, which is why the "this spreadsheet only" permission is enough later.

Step 2: turn on the manifest

The manifest is an appsscript.json file that defines, among other things, which permissions the script asks for. It is hidden by default. In the editor, open Project Settings and check Show "appsscript.json" manifest file in editor. Go back to Editor and the file appears in the list.

Replace its contents with the following, and set timeZone to your business's time zone:

{
  "timeZone": "Etc/GMT",
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/webmasters.readonly",
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/spreadsheets.currentonly",
    "https://www.googleapis.com/auth/script.send_mail",
    "https://www.googleapis.com/auth/script.scriptapp"
  ]
}

Declaring permissions by hand has one advantage: you see exactly what the script can access and nothing more. Each one does a specific job:

Permission What it is for
webmasters.readonly Reading Search Console data, with no ability to change anything
script.external_request Making the HTTP call with UrlFetchApp
spreadsheets.currentonly Writing only to the sheet the script lives in
script.send_mail Sending the email alert (remove it if you do not want one)
script.scriptapp Creating the weekly trigger from code

The official reference is in the Apps Script docs on manifests and authorization scopes.

Step 3: the code

Replace the contents of Code.gs with this. The only thing you must change is SITE.

// Domain property: 'sc-domain:example.com'. URL-prefix property: 'https://example.com/'
const SITE = 'sc-domain:example.com';
const SHEET_NAME = 'Queries';
const DELAY_DAYS = 3;   // Search Console publishes data a few days late
const ROW_LIMIT = 100;
const SEND_ALERT = true;

function formatDate_(date) {
  return Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy-MM-dd');
}

function daysAgo_(n) {
  const d = new Date();
  d.setDate(d.getDate() - n);
  return d;
}

function queryGsc_(startDate, endDate, dimensions, rowLimit) {
  const url = 'https://searchconsole.googleapis.com/webmasters/v3/sites/' +
    encodeURIComponent(SITE) + '/searchAnalytics/query';
  const body = { startDate: startDate, endDate: endDate, rowLimit: rowLimit };
  if (dimensions.length) body.dimensions = dimensions;

  const response = UrlFetchApp.fetch(url, {
    method: 'post',
    contentType: 'application/json',
    headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
    payload: JSON.stringify(body),
    muteHttpExceptions: true
  });

  const code = response.getResponseCode();
  if (code !== 200) {
    throw new Error('Search Console responded ' + code + ': ' + response.getContentText());
  }
  const data = JSON.parse(response.getContentText());
  return data.rows || [];
}

function totalClicks_(startDate, endDate) {
  const rows = queryGsc_(startDate, endDate, [], 1);
  return rows.length ? rows[0].clicks : 0;
}

function generateReport() {
  const end = daysAgo_(DELAY_DAYS);
  const start = daysAgo_(DELAY_DAYS + 6);
  const prevEnd = daysAgo_(DELAY_DAYS + 7);
  const prevStart = daysAgo_(DELAY_DAYS + 13);

  const rows = queryGsc_(formatDate_(start), formatDate_(end), ['query'], ROW_LIMIT);

  const values = [['Query', 'Clicks', 'Impressions', 'CTR', 'Position']];
  rows.forEach(function (r) {
    values.push([r.keys[0], r.clicks, r.impressions, r.ctr, r.position]);
  });

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName(SHEET_NAME) || ss.insertSheet(SHEET_NAME);
  sheet.clearContents();
  sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
  sheet.getRange(2, 4, Math.max(values.length - 1, 1), 1).setNumberFormat('0.0%');
  sheet.getRange(2, 5, Math.max(values.length - 1, 1), 1).setNumberFormat('0.0');

  if (SEND_ALERT) {
    const thisWeek = totalClicks_(formatDate_(start), formatDate_(end));
    const lastWeek = totalClicks_(formatDate_(prevStart), formatDate_(prevEnd));
    if (thisWeek < lastWeek) {
      MailApp.sendEmail(
        Session.getEffectiveUser().getEmail(),
        'SEO alert: Google clicks dropped',
        'Clicks from ' + formatDate_(start) + ' to ' + formatDate_(end) + ': ' + thisWeek + '\n' +
        'Clicks the week before: ' + lastWeek + '\n' +
        'Open the "' + SHEET_NAME + '" sheet to see which queries changed.'
      );
    }
  }
}

function createWeeklyTrigger() {
  ScriptApp.getProjectTriggers().forEach(function (t) {
    if (t.getHandlerFunction() === 'generateReport') ScriptApp.deleteTrigger(t);
  });
  ScriptApp.newTrigger('generateReport')
    .timeBased()
    .onWeekDay(ScriptApp.WeekDay.MONDAY)
    .atHour(8)
    .create();
}

How it works

  • queryGsc_ builds the request to the Search Console API. The URL contains the property name run through encodeURIComponent, because sc-domain:example.com or https://example.com/ have characters that cannot sit loose in a URL. Authorization travels in the Authorization header with the token from ScriptApp.getOAuthToken().
  • muteHttpExceptions: true stops UrlFetchApp from throwing when Google returns an error. That lets you read the response code and show the real message (misspelled property, missing access, and so on) instead of a generic failure.
  • dimensions: ['query'] asks for data grouped by search query. Switch it to ['page'] and the report lists your top pages by clicks instead. rowLimit sets how many rows come back.
  • Dates are built with Utilities.formatDate in yyyy-MM-dd format, which is what the API expects. The range covers seven days and ends a few days before today.
  • setValues is called once with the whole table. Writing row by row is much slower because every call to the spreadsheet has a cost.
  • totalClicks_ runs the same query with no dimensions, and the API returns a single row of totals. That is what the current and previous weeks are compared with.

About the data delay

Search Console does not show yesterday's numbers: its data arrives a few days late, and the most recent days can be adjusted afterward. That is why the script does not end the range today but DELAY_DAYS days earlier. For how Google describes the data and the request parameters, see the official Search Analytics query documentation.

Step 4: authorize

In the editor, pick the generateReport function in the dropdown at the top and click Run. Google shows a window asking for the permissions you declared. Because the project is yours and unverified, you will see an "unverified app" warning: go through Advanced and continue. That is normal for your own script. Check the permission list (it should match the table above) and accept.

When it finishes, look at the sheet: there should be a Queries tab with the week's searches. If it fails, open Executions in the side menu. Since the script throws the API's error message, the reason shows up there. The most common causes are a misspelled SITE or an account without access to that property.

Step 5: schedule the weekly trigger

You can create the trigger by hand from the clock icon, but the code already includes createWeeklyTrigger. Run it once from the editor. It deletes any earlier trigger for generateReport and creates a new one that runs on Mondays in the first hour of the day (Apps Script does not guarantee the exact minute). From then on the sheet updates itself.

To change the day, replace ScriptApp.WeekDay.MONDAY with another weekday.

The email alert (optional)

With SEND_ALERT = true, the script compares the last seven days of clicks with the seven days before. If they dropped, it emails the owner of the sheet. The address comes from Session.getEffectiveUser().getEmail(), that is, the account that authorized the script. No address is written in the code.

If you do not want alerts, set it to false and remove script.send_mail from the manifest. One down week is not always a problem (holidays or seasonality can explain it), so treat the email as a prompt to look at the sheet, not as a diagnosis.

The same idea applied to other data

The pattern is always the same: pull a figure from a source, write it into a sheet in one block, and leave a trigger to repeat it. You can see it applied to a different case in the sales and expenses sheet with a monthly summary built by script. And if you wonder what happens when something fails halfway, the automation demo shows error logging and retries.

If you would rather not write code, the same thing can be built with n8n, connecting Search Console and Google Sheets with visual nodes.

Frequently asked questions

Is it free?

Yes. Search Console, Google Sheets and Apps Script cost nothing for a regular Google account. Apps Script has daily usage quotas, but a weekly report stays far from any reasonable limit.

Why don't my numbers exactly match the Search Console screen?

Because of Google's data delay and the dates: the report stops a few days before today and uses the full days Search Console has already published. The row limit also matters: the report pulls the top ROW_LIMIT queries by clicks.

Can I use it for more than one site?

Yes. You can copy the sheet with a different SITE value, or extend the script to loop over a list of properties and write each one to its own tab.

What if the script fails on a Monday?

Apps Script can notify you about trigger failures: in the triggers list you set a failure notification. And since the API's error message is recorded under Executions, it is easy to see what happened.

Try it in a demo

[Excel · Google Sheets] · Demo

Sales and expenses spreadsheet and dashboard

Validations, charts with monthly filters and a monthly summary generated by macro or script.

Download the spreadsheet ↓
[Automation · Google · n8n] · Demo

Quote request automation

Form, spreadsheet, CRM, notifications and daily summary, with error logging and retries.

Try it live ↗

More posts

Need something like this for your business?

Hiring is done through the platform you came from to this site.