Hello all,
I’m new to Worker and dont have much knowledge with cookies settings
My goal is to:
- i want to check if a certain cookie exists,
- if it does, then continue to page normally (no more processing is needed).
- if the cookie is missing, first check for a certain querystring,
- if that is missing too, then redirect to a different page. (this page will eventually send the user back to the original page - this time WITH the correct querystring)
- if the querystring does exist, i want to use it to set a new cookie, then reload the page - with the new cookie - returning to step 1 (this time it should pass the cookie check)
My unsuccessful Worker code:
addEventListener(‘fetch’, event => {
event.respondWith(fetchAndApply(event.request))
})
async function fetchAndApply(request) {
console.log(“started processing”)
// Forward request to origin, get response.
let response = await fetch(request)
////// Copy Response object so that we can edit headers.
response = new Response(response.body, response)
///// // Check for cookie.
let cookies = request.headers.get('Cookie') || ""
if (cookies.includes("myCookie=true")) {
console.log("the cookie is already set")
return fetch(request)
}
else{
console.log("no cookie was found")
const init = {
method: request.method,
headers: request.headers
}
let qrystring = new URL(request.url).searchParams.get('qrystring');
console.log("qrystring: " + qrystring)
if(qrystring === null){
console.log("didnt find a querystring, redirecting")
return fetch(new Request('http://somewhereelse.com/somepage.html', init));
}
else{
console.log("found the querystring, setting the cookie")
var now = new Date();
var time = now.getTime();
var expireTime = time + 1000*36000;
now.setTime(expireTime);
response.headers.set("Set-Cookie", "myCookie=true;expires=" + now.toGMTString())
return response
}
}
}
The problem is:
i think the cookie is not created (cant see it in chrome’s inspect->storage->cookies)
- opening the page without cookie AND without query-string redirects to the other page successfully.
- opening the page WITH the query-string continues to the page BUT no cookie is created, so removing the query-string again behaves the same as original step.
Thank you all in advance!!
Ram