UNPKG

current-geo-location

Version:

Get user country, countryCode , StateCode , State, City, ZipCode and latitude , longitude using IP-API.

28 lines (20 loc) 1.31 kB
const axios = require("axios"); const https = require("https"); /** * Fetches location details based on the user's IP address. * @returns {Promise<Object>} A promise that resolves to an object containing country, region (state), city, lat, and lon. */ async function getUserLocation() { try { const agent = new https.Agent({ rejectUnauthorized: false // Disable SSL verification }); const response = await axios.get("https://ipwho.is", { httpsAgent: agent }); const { ip , continent , continent_code , country , country_code , region , region_code , city , latitude , longitude , postal , calling_code , capital , borders , flag , timezone } = response.data; const todayDate = new Date(timezone?.current_time).toISOString().split('T')[0]; return { ip , continent , continentCode : continent_code , country : country , countryCode : country_code, stateCode: region_code , state: region , dialCode : calling_code , countryCapital : capital , countryBorders : borders , flag , city , zip : postal , latitude, longitude , timeZoneAbbreviations : timezone?.abbr , todayDate : todayDate }; } catch (error) { throw new Error("Failed to fetch location data."); } } module.exports = getUserLocation;