Created
July 16, 2025 14:31
-
-
Save BoredHackerBlog/ec3247f80f95eca45dcb05350b700ecc to your computer and use it in GitHub Desktop.
cloudflare worker logging to d1
This file contains hidden or 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
create d1 database, bind it to worker | |
make a log table, add fields you need. |
This file contains hidden or 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
<script> | |
var _pixel = new Image(1, 1); | |
_pixel.src = "https://WORKER.workers.dev/?page=" + | |
encodeURIComponent(window.location.pathname) + "&" + | |
"ref=" + encodeURIComponent(document.referrer); | |
</script> |
This file contains hidden or 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
/* idk js but this works */ | |
export default { | |
async fetch(request, env, ctx) { | |
let srcip = request.headers.get('CF-Connecting-IP'); | |
let time = Date.now(); | |
let useragent = request.headers.get("User-Agent") | |
const { searchParams } = new URL(request.url) | |
let page = "NULL" | |
let ref = "NULL" | |
page = searchParams.get('page') | |
ref = searchParams.get('ref') | |
try { | |
await env.trafficlog | |
.prepare('INSERT INTO log (srcip, useragent, ref, page, time) VALUES (?1, ?2, ?3, ?4, ?5)') | |
.bind(srcip, useragent, ref, page, time) | |
.run(); | |
} catch(err) { | |
console.log(err) | |
} | |
return new Response(""); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment