I recently needed to add a few hidden form fields with geolocation information (city and country code). Took me longer than I'd like to admit.
Here's the final result so I never forget.
// Step 1: Get the user's public IP address
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
const ipAddress = data.ip;
// Step 2: Get the location info from ipapi.co using the IP address
return fetch(`https://ipapi.co/${ipAddress}/json/`);
})
.then(response => response.json())
.then(data => {
const { country_code, city } = data;
// Step 3: Set cookies with the country_code and city
document.cookie = `country_code=${country_code}; path=/`;
document.cookie = `city=${city}; path=/`;
})
.catch(error => {
console.error('Error:', error);
});
In a real scenario you may want to check if the cookies exist first and only execute the snippet if not, to avoid too many api calls to those (free) services.
function getCookie(name) {
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
return match ? match[2] : null;
}
if (!getCookie('country_code') || !getCookie('city')) {
// fetch geodata and save to cookies
}