Why must a voting backend store its counts on the server — in a file or database — rather than in a JavaScript variable or in the browser?
Because the tally must be shared by all clients and survive restarts: browser storage is per-user, and an in-memory variable dies with the server process — only persistent server-side storage gives one durable, shared count.
* Only persistent server-side storage is both shared by all clients and durable across restarts. *
There are three places the count could live, and two of them fail:
- In the browser — each visitor would hold their own private copy, so no shared result could ever exist; worse, users control their browser and could set the count to anything.
- In a server variable (
let counter = 0next to the handler) — this is shared between clients while the program runs, since every request hits the same process. But it lives in RAM: any crash, restart, or redeploy silently resets every vote to zero. - In persistent server-side storage — e.g. a
votes.jsonfile the handler reads withfs.readFileSync()and rewrites withfs.writeFileSync()(checkingfs.existsSync()on first use). All clients update the same stored tally, and it survives restarts.
The file-system version is the simplest possible illustration — real applications almost always use a database instead — but the principle is identical: results must be stored on the server, in something that outlives both the browser session and the server process.
Go deeper:
Node.js: File system (fs) API —
existsSync,readFileSync,writeFileSyncand their async counterparts.