Hatch
On this page

A blog or portfolio can show how many times each post was read, like "1,204 views", in post lists and beside a post's date. Turn it on in Publish, Look, Posts, View counts, or in .hatch/site.json:

{ "style": { "views": "show" } }

The Look preview shows made-up numbers so you can see where they go. A post with no views yet shows nothing there.

How it works

The builder leaves an empty mark wherever a count goes, naming the page by its path (<span class="views" data-views="/posts/hello/"></span>). Whatever serves the site fills the marks in as it sends the page. The numbers are in the HTML from the start: no script, nothing loads late, nothing moves.

Nothing about readers is stored. A count is one number per page. No cookie is set, and no address or browser is kept. Crawlers, link previews and prefetches don't count. A page the browser prefetched counts once it's opened (seen.js reports it).

The marks and the words are in packages/publish/src/viewCounts.ts. The server's copy is apps/server/src/viewCounts.ts: change both together.

On Hatch's server

Published sites count visits already (analytics, for owners whose plan has site analytics). The server also keeps each page's views since counting began (site_page_total, up to 5,000 pages a site), reads them at most once a minute, and fills the marks in. The page's ETag changes when its numbers do. On a plan without analytics the marks stay empty.

On Cloudflare Pages

hatch-site build sees the marks and adds a _worker.js, which Cloudflare Pages runs in front of the site, and a _routes.json that sends it only the folders that hold pages. The worker counts in a D1 database and fills the marks in. To set it up once:

  1. Create a database: npx wrangler d1 create hatch-views.
  2. Bind it to the Pages project as VIEWS: in the dashboard (Settings, Bindings, D1 database), or with a wrangler.toml beside the built folder that names it under [[d1_databases]] with binding = "VIEWS".
  3. Deploy as usual. The worker makes its table on the first visit.

Without the binding the site is served as it is, with empty marks. Other static hosts ignore _worker.js, so the marks stay empty there.

The free plan allows 100,000 worker requests and 100,000 database writes a day. Anyone can add to a count by loading a page many times, as on any public counter. The worker counts only pages the site has, and at most 5,000 of them.