store cookies in kv
Read cookies from a request and store in a KV
info
CF documentation: https://developers.cloudflare.com/workers/runtime-apis/kv/
addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(event) {
const response = await fetch(event.request);
event.waitUntil(logNewCookies(event.request, response));
return response;
}
async function logNewCookies(thisrequest, thisresponse) {
//get request cookies and log them
console.log(thisrequest.url)
const cookiestring = thisrequest.headers.get('cookie');
//Check there are cookies present and log them if they are
var cookies = {};
if (cookiestring && cookiestring != '') {
var split = cookiestring.split('; ')
//loop through the cookie list
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
//console.log('name:', )
await addCookieIfNotLogged(name_value[0], thisrequest.url)
}
} else { console.log('no cookies with this request') }
}
async function addCookieIfNotLogged(cookieName, path) {
console.log(cookieName + path)
if (cookieName != undefined && path != undefined
&& !cookieName.includes(".AspNetCore.Antiforgery.")
&& !cookieName.includes(".AspNetCore.Correlation.")) {
console.log(cookieName)
var currentValue = await COOKIES.get(cookieName)
console.log(currentValue)
if (currentValue === null) {
await COOKIES.put(cookieName, path)
}
}
}
note
Within the Worker > Settings > Variables a KV Namespace Binding called COOKIES will need to be created and bound.