typescriptintermediate

IP Geolocation Middleware

Extracts client IP and attaches geolocation data to the request using a lightweight lookup.

typescript
import { Request, Response, NextFunction } from 'express';

interface GeoData {
  ip: string;
  country?: string;
  city?: string;
}

function getClientIp(req: Request): string {
  const forwarded = req.headers['x-forwarded-for'];
  if (typeof forwarded === 'string') return forwarded.split(',')[0].trim();
  return req.socket.remoteAddress || '0.0.0.0';
}

export function geoMiddleware() {
  return async (req: Request & { geo?: GeoData }, res: Response, next: NextFunction) => {
    const ip = getClientIp(req);
    try {
      const response = await fetch(`https://ipapi.co/${ip}/json/`);
      const data = await response.json();
      req.geo = { ip, country: data.country_name, city: data.city };
    } catch {
      req.geo = { ip };
    }
    next();
  };
}

Use Cases

  • Content localization
  • Region-based access control

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.