Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Blocks certain countries from accessing your page, while giving the flexibility to whitelist certain paths.
addEventListener('fetch', event => {
event.respondWith(byPassOrBlock(event.request))
})
async function byPassOrBlock(request) {
let url = new URL(request.url)
let blockedCountries = ['XX']
let whitelistedPaths = ['/about*']
for (let i=0; i<whitelistedPaths.length; i++) {
if (new RegExp("^" + whitelistedPaths[i].split("*").join(".*") + "$").test(url.pathname)) {
return fetch(request)
}
}
if (blockedCountries.includes(request.headers.get('cf-ipcountry'))) {
// Return a Forbidden response
return new Response('Sorry, this page is not available.', { status: 403, statusText: 'Forbidden' })
// Or, alternatively, return a redirect. Make sure to whitelist this to avoid loops
// return Response.redirect('https://example.com')
}
return fetch(request)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment