Caching responses to reduce API usage
If you look up IP address details when a user visits a page on your website, you might be looking up the same IP address multiple times in a row. Each of these requests will count towards your API quota.
Instead, you can cache the results - either on the client-side or server-side, depending on your application - to reduce API usage and latency for repeat traffic.
Choose one of the approaches below based on your application.
Client-side storage
When running in the browser, you can cache the results in localStorage or sessionStorage.
This is useful for websites and browser-based apps to avoid repeated lookups per visitor.
You can store the entire response, or only what you need (for example, country code).
async function getCountryWithSessionStorage() {
const cached = sessionStorage.getItem('iplocate_country_code');
if (cached) return cached;
const res = await fetch('https://iplocate.io/api/lookup?apikey=YOUR_API_KEY');
const data = await res.json();
const country = data.country_code;
sessionStorage.setItem('iplocate_country_code', country);
return country;
}
Server-side in-process cache
If your server runs as a single process (no clustering/forks), you can use a simple in-memory map to cache responses.
const cache = new Map();
function getCache(key) {
const hit = cache.get(key);
if (!hit) return null;
if (hit.expiresAt < Date.now()) {
cache.delete(key);
return null;
}
return hit.value;
}
function setCache(key, value, ttlMs) {
cache.set(key, { value, expiresAt: Date.now() + ttlMs });
}
async function lookupWithInProcessCache(client, ip) {
const key = `iplocate:${ip}`;
const cached = getCache(key);
if (cached) return cached;
const data = await client.lookup(ip);
setCache(key, data, 6 * 60 * 60 * 1000); // 6 hours
return data;
}
Server-side application cache (shared)
Use your framework’s caching layer to share cached results across processes/instances.
For example, in Rails:
def lookup_ip(ip)
key = "iplocate:lookup:#{ip.present? ? ip : 'self'}"
Rails.cache.fetch(key, expires_in: 6.hours) do
response = Faraday.get("https://iplocate.io/api/lookup/#{ip}", { apikey: ENV['IPLOCATE_API_KEY'] })
JSON.parse(response.body)
end
end
Other frameworks and approaches
- Node.js: Use a shared cache like Redis or Memcached via libraries such as
ioredisornode-cache-managerwith a Redis store. - Python (Django): Use the configured cache backend (
django.core.cache) with Redis or Memcached.
Need help with caching? Get in touch and we’ll help wherever we can.