JSFiddle - React, Tailwind, and code Playground

by devrel_ipinfo

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Access Control</title>
</head>
<body>
    <div id="message"></div>
    <script src="access-control.js"></script>
</body>
</html>

JavaScript

// Replace 'YOUR_API_KEY' with your actual IPinfo.io API key
const apiKey = 'YOUR_API_KEY';

// List of allowed countries
const allowedCountries = ['US', 'CA', 'UK']; // Add your allowed countries here

// Function to get the visitor's country
function getVisitorCountry() {
    // Make a GET request to IPinfo.io using fetch
    fetch(`https://ipinfo.io/json?token=${apiKey}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            const country = data.country;

            // Check if the visitor's country is in the allowed list
            if (allowedCountries.includes(country)) {
                // Allow access
                const messageDiv = document.getElementById('message');
                messageDiv.innerHTML = `<p>Access granted for visitor from ${country}</p>`;
            } else {
                // Block access
                const messageDiv = document.getElementById('message');
                messageDiv.innerHTML = `<p>Access blocked for visitor from ${country}</p>`;
                alert(`Access blocked for visitor from ${country}`);
            }
        })
        .catch(error => {
            console.error('Failed to retrieve visitor information', error);
        });
}

// Call the function when the page loads
window.onload = getVisitorCountry;