Blocking Users by Country

The Ipregistry API enables content restriction from a list of countries.

We recommend performing the check on server side (i.e. not on client side). Otherwise, users can easily bypass your restriction. Unless you are using NodeJS in version 18+, the library node-fetch is required to use the fetch API.

Here is a Javascript code snippet example to detect users country and take action:

// List of country codes to block
const blacklist = ['US', 'CA', 'UK', 'FR'];

// Ipregistry API invocation
fetch('https://api.ipregistry.co/CLIENT_IP?key=YOUR_API_KEY&fields=location.country.code')
    .then(function (response) { return response.json(); })
    .then(function (payload) {
        const userCountryCode = payload['location']['country']['code'];
        if (blacklist.includes(userCountryCode)) {
            // User is not allowed: redirect, show/hide an element or what you need
        } else {
            // User is allowed: optionally perform an action
        }
});

Line 2 defines the countries you want to block based on their 2-letter ISO 3166-1 alpha-2 code. Any world country is globally identified by a unique ISO 3166-1 alpha-2 code. You can easily find the code associated with a country on Wikipedia.

Line 4 calls the Ipregistry API to retrieve IP data for the client IP CLIENT_IP. For this sample, the call is performed by using the Fetch API. The option &fields=location.country.code is used to retrieve the country code only, which reduces bandwidth consumption and latency.

Line 7 extracts the user country code from the response that was received.

Line 8 checks if the user country code is blacklisted.

Line 9 contains the action to perform for blacklisted users.

Line 11 optionally defines the action to perform for whitelisted users.