Cloudflare Workers View Counter Badge

Lets make a lightweight solution to create a view counter badge using Cloudflare Workers and Cloudflare D1, a serverless SQL database. This project generates SVG badges to display view counts, stores data persistently, and is easy to integrate into any webpage. Let’s dive into how it works, how to set it up.

So it will creat SVG badge displaying the number of views for a specific page or resource. It uses the badgen library for badge rendering and Cloudflare D1 for persistent storage. The badge can be customized with query parameters for styling, making it versatile for various looks.

Here’s an example of what the default badge looks like:

Badge Output

Repository

GitHub Repo

Once deployed, you can embed the badge in your website using markdown or HTML:

Markdown:

![Views](https://view-counter-badge.<your-account>.workers.dev/?page=your-custom-id)

HTML:

<img src="https://view-counter-badge.<your-account>.workers.dev/?page=your-custom-id" alt="views" />

Replace your-custom-id with a unique identifier for each page or project.

Customization Options

The badge supports several query parameters for customization:

Parameter Default Allowed Values Example
page / Any unique string ?page=mrinal
label Views Any string label=Visitors
labelColor 555 CSS color (name or hex/RGB) labelColor=black
color blue CSS color (name or hex/RGB) color=green
style flat flat, classic style=classic
scale 1 Any positive number scale=2

For example:

![Visitors](https://view-counter-badge.<your-account>.workers.dev/?page=blog&label=Visitors&color=green&style=classic&scale=1.5)

This View Counter Badge is a very simple for adding view tracking to your website. But to enable cross-origin usage securely (so your view badge only increments when embedded on your own site), you can implement CORS protection and Referrer/Origin header checks in your Cloudflare Worker. To avoid incrementing the view count for the same user repeatedly, you can use a combination of cookies and caching in the Cloudflare Worker also.

Add Your Note