A page views counter that pulls data from Google Analytics API.
This is a Node.js implementation built with Express framework. For PHP version, checkout to php branch.
To start, you need to first enable Google Analytics Reporting API, and create corresponding credentials.
Follow this guide to create a service account and get your keys in JSON format. You should find fileds project_id
, private_key
and client_email
in the JSON file downloaded from Developer Console.
Copy the config file config.sample.json
to config.json
and replace the values inside:
{
"listenPort": 8000,
// Maximum amount of queries in a single request
"maxQueryAmount": 10,
// TTL of cache for remote API response (in seconds)
"apiCacheTtl": 3600,
// Credentials of service account (you can find this in your JSON key file)
"authorization": {
"projectId": "<REPLACE_WITH_PROJECT_ID>",
"privateKey": "-----BEGIN PRIVATE KEY-----\n(...)",
"clientEmail": "[email protected]"
},
"analytics": {
// View ID of Analytics
"viewId": "<REPLACE_WITH_VIEW_ID>",
// To count total pageviews, set an early enough value
"startDate": "2010-01-01",
"endDate": "today"
}
}
To find your Google Analytics View ID, navigate to Admin > View > View Settings.
docker run -d --restart=always \
--name ga-hit-counter \
-p 8000:8000 \
-v "$(pwd)"/config.json:/usr/src/app/config.json \
ghcr.io/prinsss/ga-hit-counter:latest
Install pnpm if you haven't.
pnpm install
pnpm run build
pnpm start
Make a HTTP GET request to get pageviews (multiple identifiers can be separated by commas):
curl -X GET -H 'Content-Type: application/json' \
'http://localhost:8000/api/pageviews?pages=/foo-bar,/test/page'
{
"data": {
"/foo-bar": 114,
"/test/page": 514
}
}
To show detailed logs, run program with DEBUG
environment variable set as:
DEBUG='api,cache'
MIT