This repo is a simple backend server that retrieve the page count using Google Analytics Data API
The tool is build to integrate with static page by default, specifically GitHub pages(Minimal Mistakes)
- Aggregate page view count (include redirect URL)
- Cache page view count with Redis to prevent API rate limit
- The http response is also cached to prevent unnecessary API call, default to
1 day
(since the view count is not updated frequently by the Google Analytics)
- The http response is also cached to prevent unnecessary API call, default to
- Easy deployment with Kubernetes(Helm Chart), Docker-Compose, or standalone
- Enable Google Analytics Data API
- Enable Google Analytics and have some page view data
copy .env.example to .env
and fill in the following variables
Name | Description |
---|---|
PORT | Port number of the server |
LOG_LEVEL | Log level of the server |
CORS | Allow origin url for CORS |
REDIS | Redis connection string |
GOOGLE_APPLICATION_CREDENTIALS | Path to the Google Cloud credential file |
ID | Google Analytics View ID |
DOMAIN | Domain name of the website |
START_DATE | Start date of the query |
Method | Path | Description | Query Parameters |
---|---|---|---|
GET | /views |
Get the page view count | url : URL of the page |
POST | /views |
Renew page view count for page |
$ make build
$ make dev
$ docker-compose build --no-cache
$ docker-compose up -d
$ make docker-build
$ make k3d-create
$ make k3d-import
$ make k3d-apply
$ make k3d-create
$ make skaffold-dev
As per introduction, this tool is designed to integrate with static page, specifically GitHub pages. So the following steps are based on it(Jekyll).
<span>
<i class="fas fa-eye" aria-hidden="true"></i>
Views: <span id="view-field"> Loading...</span>
</span>
<script>
fetch(`http://127.0.0.1:8888/views?url={{ page.url }}`)
.then(response => response.json())
.then(data => {
if (isNaN(data.views)) {
data.views = 0;
}
document.getElementById("view-field").innerHTML = Intl.NumberFormat('en', { notation: 'compact' }).format(data.views);
})
.catch(error => {
console.error(error)
});
</script>
Place the above code snippet in the page you want to display the view count.
Please note that the {{ page.url }}
is the Jekyll variable(written in liquid) that represents the page URL, for example /git/git-hook/
, it doesn't contain the domain name.
And call the API to get the view count(remember to replace the URL with the actual backend).
To beautify the view count,
Intl.NumberFormat
will format the number to a more readable format(e.g.1.4k
).
The final result will look something like this or if the backend server is not accessible at the time.
This project is licensed under Apache 2.0. See the LICENSE file for details.