Hi
I writed a worker for read geolocalisation headers, it respond the country of the visitor.
I like whitelist the domains may call to my worker.
How do that?
best
There is no config in Workers to whitelist or blacklist domains but you can write it yourself in the worker. Something like this
const currentUrl = new URL(request.url)
if (currentUrl.host != 'mydesireddomain.com') {
return new Response(null, {status: 403})
}
// Do your regular work
Alternatively you could keep a list of domains in Workers KV. You could store all your whitelisted domains in a single key (assuming they’ll all fit - there’s a 2 MB limit) or you could create one key per domain.
1 Like
it not works, current Url show the worker url, here my code, maybe i made some wrong.
addEventListener('fetch', event => {
const currentUrl = new URL(event.request.url) // it's allways the worker host abc.workers.dev
if (currentUrl.host != 'mydesireddomain.com') {
return new Response(null, {status: 403})
}
event.respondWith(new Response(
`${event.request.headers.get("cf-ipcountry")}`,
{
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "text/html",
"charset": "utf-8"
}
}
))
})
This should work:
const handleRequest = async event => {
const currentUrl = new URL(event.request.url);
if (currentUrl.host != "mydesireddomain.com") {
return new Response("Error", { status: 403 });
}
const responseInit = {
headers: {
"Content-Type": "text/html",
charset: "utf-8",
"Access-Control-Allow-Origin": "*"
}
};
return new Response(event.request.headers.get("cf-ipcountry"), responseInit);
};
addEventListener("fetch", event => {
event.respondWith(handleRequest(event));
});
nope, same error it shows the workers domain, I add the host to error msg for debug.
const handleRequest = async event => {
const currentUrl = new URL(event.request.url);
if (currentUrl.host != "mydesireddomain.com") {
return new Response(`Error host: ${currentUrl.host}`, { status: 403 });
}
const responseInit = {
headers: {
"Content-Type": "text/html",
charset: "utf-8",
"Access-Control-Allow-Origin": "*"
}
};
return new Response(event.request.headers.get("cf-ipcountry"), responseInit);
};
addEventListener("fetch", event => {
event.respondWith(handleRequest(event));
});
the call in my website is
const res = await fetch("https://my_nice.workers.dev/");
const country = await res.text();
with the change country
is always null
the call status always is 403 and the response show:
Error host: my_nice.workers.dev