How can I track button download clicks count using a Worker?

Hi, I want to be able to track when a user clicks a “download” button and send an updated download count to maybe a worker which would store it in the KV or cloud…etc.?

This could be performed using Google Analytics perhaps, but since these days browsers block “Trackers” by default, this wouldn’t probably work.

Is this idea possible? I’m not exactly an intermediate user and not sure how to execute such an idea. If anyone can point me in the right direction/tips, that would be much appreciated!

Thanks,
Jay

1 Like

Cloudflare Durable Objects is the answer for such counters and shared objects needing global strong consistency.

1 Like

You can use a Worker, but KV is not ideal for frequent updates. I see 2 options:

  1. Use Durable Objects to maintain the counter, as suggested above
  2. Use Worker as a Google Analytics proxy - rather than maintaining the counter on Worker side, send a subrequest to Google Analytics from your worker. Here’s their REST API reference: Measurement Protocol Parameter Reference
1 Like

You can use a traditional Worker and KV but you’d need to write a new KV object (kv.put) for each download then tally up the count of KV objects (kv.list) to get a total at any given time. If you use the same key for each user you would lose downloads due to KVs eventually consistent nature.

To make this work, you’d want to use a unique key for each download so something like a millisecond based timestamp should work (unless you have an immense amount of downloads). If you have the user’s email or IP address you could add that you never have collisions: “[email protected]:1611952549123” or “240.123.123.123:1611952549123” (careful with IPv6).

You can store whatever you like in the value of the KV. I frankly like using json and then you could store all kinds of info like file downloaded / url / user info / ip info / time info / geolocation info / etc.

2 Likes

Thanks for your replies guys,
Appreciate it!!!

Y’all are experts :smiley:
I’m a pretty good Front-End Dev but when it comes to this stuff, I need to step up my game up :laughing: