A cool thing I've done recently was to automatically request Google Search Console to index blog routes when someone edits the content.
Here is the steps
- Create a service account credential on GCP
- Download the credential as json and put as a string on
GOOGLE_GSC_CREDENTIALS
env var - In the Google Search Console dashboard, go to the settings of your site and navigate to the Users and Permissions section
- Click on Add User and add the service account’s email address (this is the client_email field from your service account JSON credentials)
- Set the permission level to Full
- Wait few minutes for permissions to propagate
Heads up! you need to verify your domain for this works
Here is the code
import { google } from 'googleapis';
const createAuth = () => {
const { GOOGLE_GSC_CREDENTIALS } = process.env;
if (!GOOGLE_GSC_CREDENTIALS) {
throw new Error('GOOGLE_GSC_CREDENTIALS env var is not set');
}
const credentials = JSON.parse(GOOGLE_GSC_CREDENTIALS);
const auth = new google.auth.GoogleAuth({
credentials,
scopes: ['https://www.googleapis.com/auth/indexing'],
});
return () => auth;
};
const getAuth = createAuth();
const gsc = google.indexing({
version: 'v3',
auth: getAuth(),
});
interface PublishOrUpdateUrlToIndex {
url: string;
}
export const publishOrUpdateUrlToIndex = async ({
url,
}: PublishOrUpdateUrlToIndex) => {
try {
await gsc.urlNotifications.publish({
requestBody: {
url,
type: 'URL_UPDATED',
},
});
return { url };
} catch (error) {
return { error: <Error>error };
}
};
interface DeleteUrlFromIndexedRoutes {
url: string;
}
export const deleteUrlFromIndexedRoutes = async ({
url,
}: DeleteUrlFromIndexedRoutes) => {
try {
await gsc.urlNotifications.publish({
requestBody: {
url,
type: 'URL_DELETE',
},
});
return { url };
} catch (error) {
return { error: <Error>error };
}
};