I want to dynamically add http-headers via CloudFlare workers ONLY for the first time visitors. For example these headers:
Link: </path/to/file.css>; rel=preload; as=style; nopush
Link: </path/to/script.js>; rel=preload; as=script; nopush
So, what I need is the following, via JavaScript, in CloudFlare Workers:
- Check if a specific cookie exists on the client's side.
- If the cookie doesn't exist add http-headers and then set that specific cookie.
- If the cookie does exist do nothing.
You can play with the code here.
Here's a general example (involving cookie and headers) from the CF's blog:
// A Service Worker which skips cache if the request contains
// a cookie.
addEventListener('fetch', event => {
let request = event.request
if (request.headers.has('Cookie')) {
// Cookie present. Add Cache-Control: no-cache.
let newHeaders = new Headers(request.headers)
newHeaders.set('Cache-Control', 'no-cache')
event.respondWith(fetch(request, {headers: newHeaders}))
}
// Use default behavior.
return
})