Last active
December 28, 2022 12:23
-
-
Save mulhoon/b08e8e62932a75bc655286af6beff400 to your computer and use it in GitHub Desktop.
Counting unique visitors and bounces without cookies.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const app = express() | |
app.get('/ping', (req, res) => { | |
const now = Date.now(), | |
day = 8.64e7 | |
// calculate midnight today and tomorrow | |
const midnight = Math.floor(now / day) * day | |
const midnightDate = new Date(midnight) | |
const midnightTomorrow = Math.ceil(now / day) * day | |
// get the if-modified-since header or default to midnight | |
const modified = req.headers['if-modified-since'] | |
let date = modified ? new Date(modified) : midnightDate | |
// is the date less than today? set it to today | |
date = date - midnightDate < 0 ? midnightDate : date | |
// add 1 second to the date | |
date.setSeconds(date.getSeconds() + 1) | |
// calculate a visit count | |
const counter = (date - new Date(midnight)) / 1000 - 1 | |
// set a max age | |
const maxAge = Math.round((midnightTomorrow - now) / 1000) | |
res.set('Cache-Control', `public, max-age=${maxAge}, no-cache`) | |
// set last-modified header | |
res.set('Last-Modified', date.toGMTString()) | |
// remove the etag | |
res.set('etag', false) | |
// return the count as a string | |
res.send(String(counter)) | |
}) | |
app.listen(3001, () => console.log(`Counter launched on 3001`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
View a demo of this here 👉 https://lastmodified.normally.com/
And read more about it here: Privacy-preserving analytics: How we count unique visitors without cookies, UIDs or fingerprinting.