In this code sample, we will show you how to build the simplest possible visitor counter using a little bit of JavaScript. It is not limited to Web pages, you can implement it from anywhere you have HTTP access.
As is the case with using key-value stores, it's important to design a well-suited schema for keys. For our hit counter, we want to count hits by the day and for each individual URL on our website. This will influence our key naming convention:
URL:YYYY-MM-DD
Values will consist of integers and we will use the KVdb API to increment them. If you wanted to count additional events, such as actions taken by a user, you can use additional keys (with a different naming convention).
First, create a protected bucket:
$ curl -d 'email=MY_EMAIL&secret_key=MY_SECRET_KEY' https://kvdb.io
Fd55uogXyxYdnXJvnyN8Xo
The JavaScript code to increment a counter in KVdb is very simply:
(function() {
var today = new Date().toISOString().substr(0, 10); // YYYY-MM-DD
var path = encodeURIComponent(location.pathname);
$.ajax({
type: 'PATCH',
url: '/Fd55uogXyxYdnXJvnyN8Xo/' + path + ':' + today,
data: '+1'
});
})();
By using a PATCH
HTTP request, you are telling KVdb to operate on a key value. The request body of +1
means the value should be incremented by 1. If the key does not exist, it is initialized with the given value.
Retrieving the latest hit counts is trivial:
$ curl -u MY_SECRET_KEY: https://kvdb.io/Fd55uogXyxYdnXJvnyN8Xo/?values=true
Although functionally simple, the ability to atomically increment a global counter is a powerful concept that you can leverage in your apps. As with all keys, make sure to choose the appropriate expiration policy depending on how long you want to retain the data.
You are not limited to incrementing counters, you can also decrement by using a negative sign -
prefix. You can even use decimal numbers to operate on floating point values.
Check out API reference guides and more code samples at the documentation portal.