How to block users based on their country
Blocking users based on their country is a very common use case. In this tutorial, we are going to look at an example, where we restrict certain content from a list of countries.
Introduction
In this example, we are specifically blocking users from accessing a website. It is worth mentioning that this example specifically aims to block users that have no association to us or our servers (e.g. a user account). Typically, we are talking about website visitors.
Writing the code
We are sending a GET request to the ipbase IP info endpoint, which provides us with the associated country information.
In fact, the info endpoint (Read more) provides an entire data object that is dedicated to country-specific
information (including currency, timezones, etc.). For our use case, the alpha2 code,
which represents the ISO 3166-1 alpha-2 standard, is all we need.
We look up the country of the visitor's IP address and check its alpha-2 code against a list of blocked countries. If the visitor's country is on the list, they are blocked from the content. If not, they can see it. Instead of actually blocking anyone, the examples print "You are blocked" or "You can see this".
The lookup runs on your server, so pass the visitor's IP address as the ip parameter. Without it, the API returns the location of the IP address the request comes from, which is your server. If your server sits behind a proxy or load balancer, take the visitor's IP from the header it sets (e.g. X-Forwarded-For) instead of the connection address.
// Express route handler
const blockedCountries = ['DE', 'AT', 'ES', 'CH']
app.get('/', async (req, res) => {
const params = new URLSearchParams({ ip: req.ip })
const response = await fetch(`https://api.ipbase.com/v2/info?${params}`, {
headers: { apikey: 'YOUR-API-KEY' },
})
const userCountry = (await response.json()).data.location.country.alpha2
if (blockedCountries.includes(userCountry)) {
res.send('You are blocked')
} else {
res.send('You can see this')
}
})
There are plenty of use cases where you can exclude users because of their country of origin. For example, some companies want to
exclude users from the European Union due to GDPR issues. The location.country.is_in_european_union field tells you that directly.
Register an API key to get started and enter it in the example above.