Skip to content

Instantly share code, notes, and snippets.

@Antoinebr
Last active March 29, 2019 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Antoinebr/25673fabb11fd18c31cda4e3fbab74c3 to your computer and use it in GitHub Desktop.
Save Antoinebr/25673fabb11fd18c31cda4e3fbab74c3 to your computer and use it in GitHub Desktop.
Refresh the AMP cache with the invalidation API

Bust AMP cache

Demo on how to force cache refresh with AMP

NB : all the follwing instructions are on node.js

Demo

https://glitch.com/edit/#!/bust-amp-cache

Generate the keys

openssl genrsa 2048 > private-key.pem 

openssl rsa -in private-key.pem -pubout >public-key.pem

Expose your 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());
  }
  
});

Request a cache refresh

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment