URL Shortener on Cloudflare Workers with Visit Count

Thanks to https://github.com/EasyChris/Url-Shorten-Worker for implementing the basic counting functionality.

Building on this, I further optimized the operation page so that you can read the visit count directly on the operation page, without needing to check the visit count in the KV backend.

Demo


Brief description of @EasyChris's solution

Create a record of shortlink-count in KV, storing the number of visits.

For example: if the short link is NEhFs7, then the count record is NEhFs7-count

I'm not the author of this part, so I won't go into detail.


My further optimization process

index.js

Optimized the code, moving the password check out of each command's branch to the outermost level.

Dark editor code validating password from POST request, returning 500 and Invalid password on failure

Added the qry command, which can query KV.
Screenshot showing the qry lookup branch returning status code 500 and shortURL not found error when LINKS.get misses

I use it here to query the count value, but it can actually also be used to query the long link corresponding to a short link. In other words, it can serve as a standalone short link API with add, delete, and query capabilities.


main.js

The actual action of the query count button

queryVisitCount function in the code screenshot disables the qryCntBtn button and checks for status 200


========

Postscript

When the counting feature is enabled, the number of writes to KV increases significantly. When creating a short link, it originally only wrote once, but now it needs to write twice; when querying, it used to just read, but now it also needs to write once.

Setting the visit_count config option to true enables the counting feature. The default in the configuration file on Github is disabled.

In the urlsrv code editor, worker.js visit_count config flagged red as true

Github: https://github.com/crazypeace/Url-Shorten-Worker


Comments