Demo on how to force cache refresh with AMP
NB : all the follwing instructions are on node.js
https://glitch.com/edit/#!/bust-amp-cache
openssl genrsa 2048 > private-key.pem
openssl rsa -in private-key.pem -pubout >public-key.pem
The public-key.pem should be accesible to the public on this URL :
https://myAwesomeSite.com/.well-known/amphtml/apikey.pub
NB : Do not convert your public key to .pub
NB : You should send you keys in the text/plain
content-type
Example :
router.get("/.well-known/amphtml/apikey.pub", (request, response) => {
try{
// we get the key
const key = fs.readFileSync('/app/public-key.pem').toString();
// we set the content-type to text/plain
response.type('text/plain');
// let's send the key !
response.send(key);
}catch(e){
response.send(e.toString());
}
});
Let's create a file ( bustCache.js ) and add this code :
// Install ( amp-toolbox-update-cache ) with npm install amp-toolbox-update-cache
const UpdateCacheUrlProvider = require('amp-toolbox-update-cache');
// we use fs to get our key
const fs = require('fs');
// We wil have to make HTTP requests to the cache. here I use node-fetch ( npm install node-fetch )
const fetch = require('node-fetch');
// we get our key
const privateKey = fs.readFileSync('/app/private-key.pem').toString();
/**
* @description Clear the cache for a given URL
* @param {string} url the URL you want to invalid
* @returns {promise}
*/
const bustThatUrl = async (url) => {
// we init UpdateCacheUrlProvider with our private key
const updateCacheUrlProvider = UpdateCacheUrlProvider.create(privateKey);
// we get all the URLs from the cache
let cacheUpdateUrls = await updateCacheUrlProvider.calculateFromOriginUrl(url);
// We only want Google ( remove this line if you want to refresh the cache not only on Google )
cacheUpdateUrls = cacheUpdateUrls.filter( c => c.cacheId === "google");
const requestsToCaches = cacheUpdateUrls.map( c => fetch(c.updateCacheUrl) );
const responsesFromCaches = await Promise.all(requestsToCaches);
for ( const responsesFromCache of responsesFromCaches){
const textResponse = await responsesFromCache.text();
if( textResponse !== "OK") throw new Error(textResponse);
}
return true;
};
// we list the urls we want to refresh
const URLS_TO_CLEAR = ["https://bust-amp-cache.glitch.me/","https://bust-amp-cache.glitch.me/amp-list"];
(async () => {
for( const URL of URLS_TO_CLEAR){
try {
// we refresh the cache
const bustingResult = await bustThatUrl(URL);
console.log(`✅ ${URL} has been busted with the following response : ${bustingResult}`);
}catch(e) {
console.log(`${URL} didn't get busted with the following response : ${e}`);
}
}
})()
.catch(console.log)
Execute this script
node bustCache.js