I am attempting to set a cookie and maintain this cookie while browsing using Cloudflare Workers. Right now I am struggling in two areas:
1.) Custom Expiration Date to Set Time: 1 Day, 1 Week, etc. (I cannot find documentation on this anywhere)
2.) Cookie Disappears when changing URL from the single URL worker is set to run on.
Current Code:
// Fetch the request and pass it through the function
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request))
})
async function fetchAndApply(request) {
var date = new Date();
date.setTime(date.getTime() + (30 * 60 * 60 * 1000));
let response = await fetch(request);
response = new Response(response.body, response);
response.headers.set('Set-Cookie', "4pricing-mode=on; Expires='${date}'; Path='/';");
return response;
}
Note, I was able to fix 2.) by correcting the "Path" inside of my cookie to this:
response.headers.set('Set-Cookie', "6pricing-mode=on; Expires='${date}';Path=/");
I still cannot figure out how to set dynamic expiration
1.) Instead of using Expire, I simply used max-age; which defines the amount of seconds to keep the cookie alive - I have set mine at 7 days
2.) I removed the apostrophe's around /, which now allows the cookie to pass to alternative urls of my website:
response.headers.set('Set-Cookie', "pricing-mode=on;max-age=604800;Path=/");