https://github.com/guidevloper/nullstack-view-counter
Nullstack example of counting views and avoiding requests from non-user sources
https://github.com/guidevloper/nullstack-view-counter
nullstack
Last synced: 12 months ago
JSON representation
Nullstack example of counting views and avoiding requests from non-user sources
- Host: GitHub
- URL: https://github.com/guidevloper/nullstack-view-counter
- Owner: GuiDevloper
- Created: 2023-05-19T23:55:51.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2023-07-06T08:34:37.000Z (over 2 years ago)
- Last Synced: 2025-02-08T06:27:14.715Z (about 1 year ago)
- Topics: nullstack
- Language: TypeScript
- Homepage: https://nullstack-view-counter.vercel.app
- Size: 665 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# nullstack-view-counter
Nullstack example of counting views and avoiding requests from non-user sources.
## Reasoning
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](https://nullstack.app/server-functions) 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.
## How to run this project
1. Install the dependencies: `npm install`
2. Rename the **.env.example** file to **.env**
3. Run the app in production mode:
```sh
npm run build && node .production/server.js
```
5. Open [http://localhost:3000](http://localhost:3000) in a anonymous/zero-cache tab.
6. Check the terminal and view.
> :bulb: Vercel Serverless instances does have a temporary state being a good environment to test this behavior in production and storing logs.
## Learn more
[Read Nullstack documentation](https://nullstack.app/documentation)