Skip to content

Instantly share code, notes, and snippets.

@mulhoon
Last active December 28, 2022 12:23
Show Gist options
  • Save mulhoon/b08e8e62932a75bc655286af6beff400 to your computer and use it in GitHub Desktop.
Save mulhoon/b08e8e62932a75bc655286af6beff400 to your computer and use it in GitHub Desktop.
Counting unique visitors and bounces without cookies.
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`))
@mulhoon
Copy link
Author

mulhoon commented Nov 29, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment