x0nifo
x0nifo
CDCloudflare Developers
Created by x0nifo on 11/14/2023 in #workers-help
How to access env variable containing an object
I have the following in my .dev.vars file: FOO = { bar = true, baz = 5} and now I'm trying to access it from my Worker, with env.FOO.bar but that doesn't work (returns undefined). Any ideas?
2 replies
CDCloudflare Developers
Created by x0nifo on 10/25/2023 in #workers-help
purging fetch cache that uses a custom cache key
I'm using Workers to proxy requests to an origin server and cache the responses using the fetch cache. Essentially I'm doing something like:
// processes request to https://example.com/foo.json
export default {
async fetch(request) {
const url = new URL(request.url);
const cacheKey = `https://${url.hostname}${url.pathname}`;

const headers = new Headers(request.headers);
headers.set("x-foo", url.host);

# rewrite host so that we proxy to origin
url.host = 'originserver.com'

let response = await fetch(url.toString(), {
cf: {
cacheKey: cacheKey,
cacheTtl: cacheTtlSec,
cacheEverything: true,
cacheTtlByStatus: {
'100-199': 0,
'200-299': cacheTtlSec,
'300-599': 0,
}
},
headers: headers,
});
response = new Response(response.body, response);

return response;
},
};
// processes request to https://example.com/foo.json
export default {
async fetch(request) {
const url = new URL(request.url);
const cacheKey = `https://${url.hostname}${url.pathname}`;

const headers = new Headers(request.headers);
headers.set("x-foo", url.host);

# rewrite host so that we proxy to origin
url.host = 'originserver.com'

let response = await fetch(url.toString(), {
cf: {
cacheKey: cacheKey,
cacheTtl: cacheTtlSec,
cacheEverything: true,
cacheTtlByStatus: {
'100-199': 0,
'200-299': cacheTtlSec,
'300-599': 0,
}
},
headers: headers,
});
response = new Response(response.body, response);

return response;
},
};
Is there a way to purge this fetch cache via the API, using the Purge Cache endpoint? I've tried doing:
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/xxx/purge_cache" -H "Authorization: Bearer xxx" -H "Content-Type: application/json" -d '{"files":["https://originserver.com/foo.json"]}'
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/xxx/purge_cache" -H "Authorization: Bearer xxx" -H "Content-Type: application/json" -d '{"files":["https://originserver.com/foo.json"]}'
but that didn't seem to have an effect in the subsequent requests to the cached resource (i.e. I always get CF-Cache-Status: HIT and Last-Modified remains unchanged). I then tried different combinations like:
{"files":[{"url":"https://originserver.com/foo.json", "headers": {"x-foo": "example.com"}}]}
{"files":[{"url":"https://originserver.com/foo.json", "headers": {"x-foo": "example.com"}}]}
But that didn't work either. Any insights would be greatly appreciated.
1 replies