We ramble about code, technology and life. Sometimes we actually code...


How to backup Universal Analytics data?

by Cornelius Weidmann on 19 April 20242 min read

Google Analytics allows you to export your data in several formats including PDF, Google Sheets, Excel and CSV through its user interface. While there are plenty of guides out there that cover these methods, they all seem to assume that you love spending hours on end laboriously exporting your data manually. We can skip these time-consuming approaches and use a smarter, more streamlined, automated approach.

Automating data export with code

Instead of relying on the manual process in Google's user interface, we will use code to directly access and format the data we need. Our goal is to create a tool which will end up looking something like the below.

Demo: Google Analytics Viewer

The tool provides a basic "pagepath" / "pageviews" chart and table, which can be effortlessly exported to both CSV and JSON.

Fetching data programatically

To start fetching data from Google Analytics you need to setup a "report request". For this you will require a service account linked to your Google Analytics account and a View ID, which are essential for authentication with the Universal Analytics API. Below is the foundation of our automated approach:

// ua-report.js
import { google } from 'googleapis'

// ensure your service account credentials and view ID are correctly configured (see GitHub instructions)
const serviceAccount = <compressed_json_credentials>
const viewId = <your_universal_view_id>

// modify the request params based on your data needs
const request = {
  'start-date': '2021-04-01',
  'end-date': '2021-04-15',
  metrics: 'ga:pageViews',
  dimensions: 'ga:pagePath',  
}

const runReport = async (requests: any[]) => {
  const scopes = 'https://www.googleapis.com/auth/analytics.readonly'
  const jwt = new google.auth.JWT(
    keys.client_email,
    undefined,
    keys.private_key.replace(/\\n/g, '\n'),
    scopes
  )
  await jwt.authorize()

  const response = await google.analytics('v3').data.ga.get({
    auth: jwt,
    ids: `ga:${viewId}`,
    ...request,
  })

  return response.data
}

You can also enhance your report by adding more metrics and dimensions. For instance:

{
  // other request params
  metrics: 'ga:pageViews,ga:sessions',
  dimensions: 'ga:pagePath,ga:userType',
}

If you want to dive deeper explore the full code example on GitHub. If you have specific questions about the report request then the Universal Analytics API reference is a good starting point.

Leveraging Google Analytics Viewer

Google Analytics Viewer simplifies the process of retrieving and displaying data and gives you a good basis to start your own "code to data export" mission. For a detailed walkthrough on setting it up locally refer to the GitHub page.

Core files and their roles

utils/Analytics/index.ts

Configure the metrics and dimensions which are relevant to you.

pages/api/ua-report/index.page.ts

Manage initial data transformations and adjust the frequency of API calls. The code already accounts for API request limits and uses the library p-queue to ensure all data can be fetched without hitting thresholds.

pages/actions.ts

Adjust how the data is finally transformed and exported. The main methods you'll want to adjust are:

And that's already it! I hope this tool helps you get your data exported.