Use a Google Cloud Function as a CDN5 min read

If you ever looked into the web implementation snippets of Google Analytics or trackers from Facebook and Google Ads, they have one similarity.

In order to keep their implementation as short and simple as possible, their snippets all include a call/request to an external script hosted on their respective platforms. This request loads the script with all the extra code necessary to make their implementation function.

Google, Facebook and others host their scripts on their own servers and make that code available through publicly available urls. Their server function as a content delivery network or CDN. And while a lot of technical work could go into setting one up, we’re going to use different route using a Google Cloud Function to host our additional code.

Is this a best practise? No, probably not, but it works! Google Cloud Functions are notoriously fast and rarely offline and could therefore really help developers and engineers to getting code reliably and fast!

Facebook’s use case

Let’s take the Facebook Pixel script as an example:

<!-- Facebook Pixel Code -->
<script>
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', '111222333');
  fbq('track', 'PageView');
</script>
<!-- End Facebook Pixel Code -->

This is the script which get from Facebook in order to setup remarketing and conversion attribution capabilities. One line within the <script> tag makes a request to url: https://connect.facebook.net/en_US/fbevents.js. If you follow that url, you’ll find all the additional code that Facebook loads onto your website.

In essence, this extra script has two functionalities:

  • Enhance the tracking capabilities and data-collection towards Facebook.
  • Facilitate web and analytics developers with the fbq function that simplifies implementation of follow-up interactions/conversions.

We’re going to do something similar. We’re going to host a script that enhanced some basic functionalities of Google Tag Manager.

Hosting a script in a Google Cloud Function

To make this work, we’ll have to create a Google Cloud Function with the HTTP trigger type. We can trigger this function by making a request to the cloud function’s url, exactly like the Facebook Pixel’s snippet does.

To make the cloud function return a hosted script, we need to setup two values.

  1. First we set the response type of the cloud function to “.js”.
  2. After that, we instruct the cloud function to send a stringified javascript as a response. This can be anything you like.
exports.myfunction = (req, res) => {
  res.type('.js');
  res.send("(function(){window.my_function = function(i){console.log(i)};})();")
};

The function above, I simply included a function that logs the input value to the console of the browser. But this works as an example.

Save your cloud function and make sure the “to be executed function” matches the one in your cloud function and to choose the most closest region available to reduce latency.

Trigger Cloud Function

We now have a cloud function which returns a javascript script when triggered. We can trigger this cloud function using the trigger-url after deploying the function.

I saved my cloud function as “myfunction_cdn”. When deployed I can go to the “Trigger” tab of my new cloud function to find the trigger-url. This is the url we can request in our snippets to load the code in the cloud function:

Calling the cloud function with HTML or JS

The only thing left now is to make a request to the cloud function from our website using either a HTML script tag or a javascript request. This can also be inserted through tag management tools.

HTML script tag

<script src="https://europe-west1-markaay-15187.cloudfunctions.net/myfunction_cdn"></script>

Javascript request

var cloud_cdn = document.createElement("script");
cloud_cdn.src = "https://europe-west1-markaay-15187.cloudfunctions.net/myfunction_cdn";
document.body.appendChild(cloud_cdn);

Both the scripts do exactly the same, so choose the method that fits your implementation options.

Using either of these methods, will make the code returned by the cloud function available on your website for further usage. In my case, I get access to myfunction() to log it’s input to the console.

A quite simple and useless use case to be hones, but in full potential this cloud function could contain a whole library of custom / generic code which you could use on multiple websites to enhance your implementation or analytics options.

Final thoughts

So there you have it, my example of using a Google Cloud Function as a content delivery network.

Again this is not a best practise, and I’m no expert developers. But it’s another creative use case for using cloud functions, which could help some or have fun with 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.