Skip to content

Instantly share code, notes, and snippets.

@IgorHalfeld
Last active September 20, 2024 20:52
Show Gist options
  • Save IgorHalfeld/a449e522f24b4690dd26fa29c447d890 to your computer and use it in GitHub Desktop.
Save IgorHalfeld/a449e522f24b4690dd26fa29c447d890 to your computer and use it in GitHub Desktop.
Update, publish or delete an URL from Google Search Console - more details πŸ‘‰πŸ» https://notes.igorhalfeld.com/note/automatically-request-gsc-to-index-website-routes
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 };
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment