diff --git a/src/utils/getClientIp.ts b/src/utils/getClientIp.ts new file mode 100644 index 0000000..b6d0f7e --- /dev/null +++ b/src/utils/getClientIp.ts @@ -0,0 +1,33 @@ +import { NextRequest } from 'next/server'; + +/** + * Extract client IP address from Next.js request headers + * + * This function handles various proxy and forwarding scenarios: + * - Vercel's x-forwarded-for header (may contain multiple IPs) + * - x-real-ip header (direct client IP) + * - Fallback for development environments + * + * @param request - Next.js request object + * @returns Client IP address as a string, or 'unknown-ip' as fallback + */ +export function getClientIp(request: NextRequest): string { + // Check Vercel's forwarded IP header first + // In production, this is the most reliable source + const forwardedFor = request.headers.get('x-forwarded-for'); + if (forwardedFor) { + // x-forwarded-for may contain multiple IPs in format: "client, proxy1, proxy2" + // The first IP is the original client IP + return forwardedFor.split(',')[0].trim(); + } + + // Check for real IP header (used by some proxies and load balancers) + const realIp = request.headers.get('x-real-ip'); + if (realIp) { + return realIp; + } + + // Fallback to a default identifier for development environments + // or when headers are not available + return 'unknown-ip'; +}