Integrating Google Search Console APIs in Vue.js

In this article we’ll see how to integrate the Google Search Console APIs in Vue.js using the authentication flow provided by the API client.

First, you need to obtain a Client ID by creating OAuth credentials of type Web application in the Google API Console. We also need to allow the origins from which requests can be made and specify the correct scope for the APIs, namely https://www.googleapis.com/auth/webmasters.readonly.

In Vue, place the credentials in the .env file:

VITE_GOOGLE_CLIENT_ID=ID.apps.googleusercontent.com
VITE_GOOGLE_SCOPES=https://www.googleapis.com/auth/webmasters.readonly

Modify the index.html file by inserting the API script in the head element:

<head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://accounts.google.com/gsi/client"></script>
    <title>Vite App</title>
</head>

At this point, define a function that instantiates the API client and save the access token obtained after accepting the OAuth prompt in web storage.

// src/api/google.js

export function getClient() {
  const tokenClient = google.accounts.oauth2.initTokenClient({
    client_id: import.meta.env.VITE_GOOGLE_CLIENT_ID,
    scope: import.meta.env.VITE_GOOGLE_SCOPES,
    prompt: 'consent',
    callback: (resp) => {
      if (resp && resp.access_token) {
        localStorage.setItem('google-access-token', resp.access_token);
      } else {
        localStorage.setItem('google-access-token', '');
      }
    },
  });
  return tokenClient;
}

To trigger the browser OAuth prompt, you need to use a specific method of the client:

import { getClient } from '@/api/google';

const tokenClient = getClient();

const handleRequestAccess = () => {
    tokenClient.requestAccessToken({ prompt: 'consent' });
};

Once the token has been obtained, we can define a function to query the APIs:

// src/api/google.js

export async function runQuery(domain = 'example.com', dimension = 'query', start = null, end = null) {
  try {
    const accessToken = localStorage.getItem('google-access-token');
    const siteURL = 'sc-domain:' + domain;

    const endpoint =
      'https://www.googleapis.com/webmasters/v3/sites/' +
      encodeURIComponent(siteURL) +
      '/searchAnalytics/query';

    const startDate = start instanceof Date ? start.toISOString().slice(0, 10) :  new Date(Date.now() - 28 * 24 * 3600 * 1000)
        .toISOString()
        .slice(0, 10);
    const endDate = end instanceof Date ? end.toISOString().slice(0, 10) :  new Date().toISOString().slice(0, 10);

    const body = {
      startDate: startDate,
      endDate: endDate,
      dimensions: [dimension],
      rowLimit: 20,
    };

    if(dimension === 'page') {
        body.searchType = 'web';
    }

    const res = await fetch(endpoint, {
      method: 'POST',
      headers: {
        Authorization: 'Bearer ' + accessToken,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    });

    if (!res.ok) {
      const err = await res.json().catch(() => ({}));
      throw new Error(
        res.status + ' ' + res.statusText + ' — ' + JSON.stringify(err)
      );
    }

    const data = await res.json();
    return data.rows || []; 
  } catch (e) {
    return [];
  }
}

The analytical data are returned in the rows array. The domain passed as the first parameter must not be a URL but a domain name, to avoid ownership and authorization issues. To obtain consistent and reliable results, you should choose a meaningful date range (start and end of the period).

Conclusion

The Google Search Console APIs are an excellent tool for monitoring and analyzing how our sites perform on Google’s SERPs, and it’s relatively simple to integrate them into Vue.js.

Back to top