Mingze Gao

Display Page Views on Static Site

| 2 min read

This site, like many others, is hosted on GitHub Pages. While collecting site statistics is easy with Google Analytics, displaying is not. This post shows how I make it work and automated via GitHub Actions, such as below.

30-day Active Users
30-day Page Views

last updated: 30 Jan 2023

Retrieve site statistics from Google Analytics

The first step is to retrieve statistics from Google Analytics Data API (GA4). The most recent and relevant guide is this one by Google.

Essentially, we need to make a service account, add it as a user to Google Analytics for the site, and save its keystore json file. Then, we use the keystore file to authenticate (at server side) to retrieve statistics.

With a static site, however, there is no "server" to store the keystore file. More specifically, this site is built and deployed with GitHub Actions. Hence, my solution is to use GitHub Secrets. Yet, GitHub Secrets cannot store a json file, so we need to encode the keystore file as a base64 string. I name it GOOGLE_CLIENT_SECRETS_BASE64, along with GOOGLE_PROPERTY_ID for the site id in GA4.

Inject stats to the site at build time

The second step is to put the site statistics somewhere in the site, before or after the build process. I choose to write the statistics to a dedicated astro component (or a React component, a short HTML/Markdown, etc.), which can then be reused.

These two steps combined are done by scripts/add_site_stats.py, which should be run before building the site with astro (e.g., npm run build).

Automation via GitHub Actions

The final step is to streamline the process by modifying the GitHub Actions.

In the workflow, I have the following build job:

    runs-on: ubuntu-latest
      - name: Checkout your repository using git
        uses: actions/checkout@v2
      - name: Setup Python
        uses: actions/setup-python@v4
          python-version: '3.10'
      - name: Inject site stats from Google Analytics V4 API
        run: |
          pip install google-analytics-data
          python scripts/add_site_stats.py
      - name: Install, build, and upload your site
        uses: withastro/action@v0

Note that I make available the GitHub Secrets as environmental variables for the Python script to retrieve statistics and inject it into components.

Lastly, the job is scheduled to run on a daily basis. We successfully make site statistics such as users and page views displayed on a static site. Very good.