Skip to content

Instantly share code, notes, and snippets.

@ai
Last active March 28, 2024 19:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ai/433e11e0cee604ebaad16987d660fc40 to your computer and use it in GitHub Desktop.
Save ai/433e11e0cee604ebaad16987d660fc40 to your computer and use it in GitHub Desktop.
Cloudflare worker to send statistics to Matomo
async function trackVisit (request, visitorId) {
let data = {
token_auth: 'secret',
country: request.headers.get('CF-IPCountry'),
urlref: request.referrer || request.headers.get('Referer'),
idsite: 1,
lang: request.headers.get('Accept-Language'),
apiv: 1,
rand: Math.random().toString(16).slice(2),
url: request.url,
_id: visitorId.slice(0, 16),
rec: 1,
ua: request.headers.get('User-Agent')
}
let url = 'https://logux.matomo.cloud/matomo.php?' + Object.entries(data)
.map(([k, v]) => `${ k }=${ encodeURIComponent(v) }`)
.join('&')
await fetch(url)
}
function getVisitorId (...headers) {
for (let header of headers) {
if (typeof header === 'string') {
let match = header.match(/__cfduid=([0-9a-f]+)(;|$)/)
if (match) return match[1]
}
}
}
function shouldBeIgnored (request, response) {
return request.headers.get('DNT') === '1' ||
request.headers.get('From') === 'sw@logux.io' ||
!(response.headers.get('Content-Type') || '').includes('text/html')
}
async function fetchAndTrack (event) {
try {
let response = await fetch(event.request)
if (!shouldBeIgnored(event.request, response)) {
let visitorId = getVisitorId(
event.request.headers.get('Cookie'),
response.headers.get('Set-Cookie')
)
event.waitUntil(trackVisit(event.request, visitorId))
}
return response
} catch (err) {
return new Response(err.stack || err)
}
}
addEventListener('fetch', async event => {
event.respondWith(fetchAndTrack(event))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment