I Fit You

Paulina Skorupa - Trener Personalny

Use Guess JS in your Gatsby site to enhance User Experience

Use Guess JS in your Gatsby site to enhance User Experience

Ever since I learn't about HTTP/2's preload and prefetch, I had a very small idea - what if there was a way to use Google Analytics data to predict and prefetch the relevant resources accordingly! That idea came to life with Guess JS, although it had nothing to do with me. What's better is that I learn't about it when a Gatsby JS plugin was released for it. The perfect platform for such a library. But since it is very new and experimental and still evolving there's a lack of proper documentation. While implementing it on this blog I found out that it's not so straight forward. Here's how you can do it.

Get Required Credentials for Google Analytics API

To get your Google Analytics API go to Google API Console go to Credentials section in the sidebar.


Click on Create credentials and select Service account key from the dropdown.


In the new page create a new Service Account. Give desired names, and for the role select Service Accounts > Service Account User.


After clicking on Create, a JSON file would begin downloading.

Add gatsby-plugin-guess-js to gatsby-config.js dynamically

From the above downloaded JSON file we'll need two credentials client_email and private_key for the plugin. Also, we'll need Google Analytics View ID. GA View ID can be found in View Section of Google Analytics Admin Page.


Ideally you store these in an environment variable, for this tutorial's context they'll be GAVIEWID, CLIENT_EMAIL & PRIVATE_KEY.

We begin by installing the plugin:

yarn add gatsby-plugin-guess-js

Next, we add it to our gatsby-config.js file, but wait there's a catch. This is what we call a dynamic plugin, to add this we'll need to first create an array and push the plugin to that.

const dynamicPlugins = []
// pick data from 3 months ago
const startDate = new Date()
startDate.setMonth(startDate.getMonth() - 3)
if(process.env.CLIENT_EMAIL && process.env.PRIVATE_KEY && process.env.GA_VIEW_ID) {
      resolve: `gatsby-plugin-guess-js`,
      options: {
        GAViewID: process.env.GA_VIEW_ID,
        jwt: {
          client_email: process.env.CLIENT_EMAIL,
          private_key: process.env.PRIVATE_KEY,
        period: {
          endDate: new Date(),

Now we take our dynamicPlugins array and concat it with our main plugin config array.

module.exports = {
  siteMetadata: {
  plugins: [

And that's it! Now test it out to see if everything works fine.

TIP: If you are adding it to an existing project and adding this plugin breaks your build, try removing .cache, public and node_modules, reinstalling the npm packages and then then re building.

whatsapp icon
LinkedIn icon