Skip to content

Instantly share code, notes, and snippets.

@z4nr34l
Created April 10, 2024 08:49
Show Gist options
  • Save z4nr34l/10da389a90f8656e8f5456761fda1503 to your computer and use it in GitHub Desktop.
Save z4nr34l/10da389a90f8656e8f5456761fda1503 to your computer and use it in GitHub Desktop.
Simple function to fetch users real IP address in nextjs app on vercel including cloudflare proxy
/**
* The fallback IP address to use if the real IP address cannot be determined.
*/
const FALLBACK_IP_ADDRESS = '0.0.0.0';
/**
* Returns the real IP address of the client.
* @param request - The incoming request.
* @param cfProxy - Whether the client is behind a Cloudflare proxy.
* @returns The real IP address of the client.
*/
function realIP(request: NextRequest, cfProxy = false): string {
const headers = request.headers;
/**
* Cloudflare only headers.
*/
if (cfProxy && headers.has('cf-connecting-ip')) {
return headers.get('cf-connecting-ip');
}
if (headers.has('x-real-ip')) {
return headers.get('x-real-ip');
}
if (headers.has('x-forwarded-for')) {
return headers.get('x-forwarded-for');
}
if (headers.has('x-vercel-forwarded-for')) {
return headers.get('x-vercel-forwarded-for');
}
if (headers.has('x-vercel-proxied-for')) {
return headers.get('x-vercel-proxied-for');
}
/**
* The fallback IP address.
*/
return request.ip ?? FALLBACK_IP_ADDRESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment