Create a gist now

Instantly share code, notes, and snippets.

Embed
Using Cloudflare Workers and https://Apility.io API to block access to the pages filtered if the IP belongs to an European country because of the GDPR.
addEventListener('fetch', event => {
event.respondWith(fetchAndCheckOrigin(event.request))
})
async function fetchAndCheckOrigin(req) {
try {
const body = await req.body;
const ip = req.headers.get('cf-connecting-ip');
const apilityio = await fetch('https://api.apility.net/badip/' + ip + '?token=APILITY_IO_API_KEY');
const status = await apilityio.status;
if (status == 200) {
// The IP has been found in any blacklist
return new Response('Sorry, you are European and you can sue me from this IP: ' + ip,
{ status: 451, statusText: 'Unavailable For Legal Reasons' })
}
if (status == 429) {
// Quota Exceeded. Too many requests.
return new Response('Your Apility.io quota has run out. Please change your plan to support more traffic.',
{ status: 429, statusText: 'Too many requests.' })
}
return await fetch(req)
} catch (err) {
console.log(err);
return new Response('Internal Error')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment