Nullstack example of counting views and avoiding requests from non-user sources.
Nullstack in production environment by default loads the page and activate a service-worker that loads again, making double-run at the first user visit (calling any initial server function too).
Also many bots (like VercelBot) requests the page, making more runs (and logs).
This example caches the root page /
, and also checks the user-agent from requests, trying to count only real users visits.
-
In server.ts all
get
requests are intercepted and cached for 3s (enough for worker) - Comment line 12 for the initial request double-run again. -
In src/ViewCount.tsx the logic happens. A server variable stores the count - Without the above caching, the initial goes wrong, pressing
Sync with server
shows how the server got hit twice. -
In src/utils.ts there's a method to check if the user agent isn't among known bots, blocking the server count for them.
-
Install the dependencies:
npm install
-
Rename the .env.example file to .env
-
Run the app in production mode:
npm run build && node .production/server.js
-
Open http://localhost:3000 in a anonymous/zero-cache tab.
-
Check the terminal and view.
💡 Vercel Serverless instances does have a temporary state being a good environment to test this behavior in production and storing logs.