Why Google Analytics?
As part of our ongoing drive to automate expertise at Shoelace, we’ve decided to integrate with Google Analytics and my focus lately has been to see this to fruition. Google Analytics, in our early stage integration, will play a vital role in helping us to better understand the size of a retargeting audience available to a particular store, and allow us to offer them better retargeting advertising campaigns.
Google Analytics and NodeJS
Google has released an alpha version of their client library for NodeJS, which can be found on Github. One of the main advantages to using a client library supported by Google is that they offer automatic token refreshing, so you don’t have to put too much effort into ensuring the access token you’ve received is still valid.
Another incredibly useful resource was Google Analytics’ Query Explorer. I found it really helpful over the development process to be able to rely on this as a means of verifying the data I received from the API.
As of googleapis version 28, native async/await are supported, making calls to the GA API much cleaner to read and process.
Getting authorization
We use OAuth2 to enable users to grant us permission to their GA account. Once authorized, we're able to store their access token and refresh token, and use this to authenticate requests for data in their account.
Authenticating and making requests
When we prepare to make requests over the GA API, we use the OAuth2 client to set credentials - in this case, it's a simple Node object containing two keys, access_token
and refresh_token
, and the corresponding data. Here's an example of using an OAuth2 client to get an analytics API object that's ready to make requests.
const oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
const credentials = { refresh_token: 'REFRESH_TOKEN', access_token: 'ACCESS_TOKEN' };
oauth2Client.setCredentials(credentials);
const analyticsAPI = googleApi.analytics({ version: 'v3', auth: oauth2Client });
We can use analyticsAPI
now to make requests:
await analyticsAPI.management.profiles.list({ accountId: '~all', webPropertyId: '~all' });
The above will fetch all profiles available for a particular user.
Shoelace and GA
Right now at Shoelace, we're most interested in understanding retargeting audience sizes. So, when a user integrates GA into their Shoelace account, we also keep track of an appropriate view to query against (we highly recommend to our users that they select their default, unfiltered view, for best results). With that, we dynamically generate a segment to isolate traffic that's targeted towards their Shopify domain, and from there we can understand different metrics of users across a range of time spans.
We're excited to continue to grow this integration and leverage a lot more data that's tracked by GA.
Top comments (1)