typescriptintermediate
IP Geolocation Middleware
Extracts client IP and attaches geolocation data to the request using a lightweight lookup.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
Best for: REST API authentication
#jwt#express
typescriptintermediate
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Best for: API abuse prevention
#express#rate-limit
typescriptbeginner
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.
Best for: Express route error handling
#express#async
typescriptbeginner
Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.
Best for: API input validation
#express#zod