DEV Community

Daniel Igel
Daniel Igel

Posted on

3 ways to use IP geolocation in your web app: personalization, server-side detection, and log enrichment

IP geolocation shows up in three distinct scenarios: personalizing content for a visitor's country, detecting locale in server-side middleware without touching the frontend, and enriching analytics logs with geographic context. All three use the same API.

1. Content personalization — resolve country and timezone, then adapt the response:

const res = await fetch(
  `https://api.sprytools.com/v1/geo/api/v1/geo?ip=${clientIp}`,
  { headers: { 'x-api-key': process.env.SPRYTOOLS_API_KEY } }
);
const { countryCode, timezone } = await res.json();
// redirect /de for DE, show timezone-aware timestamps, etc.
Enter fullscreen mode Exit fullscreen mode

Fields: country, countryCode, region, city, latitude, longitude, timezone, isp, as.

2. Server-side locale detection — read the caller's IP from the proxy header in your own middleware and pass it explicitly:

// Next.js middleware / Express before-routes / edge function
const clientIp = req.headers.get('x-forwarded-for')?.split(',')[0].trim();

const { countryCode } = await fetch(
  `https://api.sprytools.com/v1/geo/api/v1/geo?ip=${clientIp}`,
  { headers: { 'x-api-key': process.env.SPRYTOOLS_API_KEY } }
).then(r => r.json());
Enter fullscreen mode Exit fullscreen mode

That gives you the country before rendering, without pulling a geo database into your own build.

3. Batch log enrichment — resolve up to 50 IPs in one request to annotate event logs without N+1 calls:

const { results } = await fetch('https://api.sprytools.com/v1/geo/api/v1/geo/batch', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': process.env.SPRYTOOLS_API_KEY,
  },
  body: JSON.stringify({ ips: logEntries.map(e => e.ip) }),
}).then(r => r.json());
Enter fullscreen mode Exit fullscreen mode

Lookups run against a locally hosted MaxMind GeoLite2-City database — no per-call latency from an external provider.

Free key: 100 calls/day, no credit card — https://sprytools.com/apis/geo/

Which of these three use cases first pushed you to add geolocation to your app?

Top comments (0)