Last active
September 20, 2024 20:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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