Skip to content
Crafzo
Menu

For developers

How to Get the User IP Address in Next.js App Router

A developer guide to reading the real client IP in Next.js 14 App Router using headers(), middleware, and edge runtime considerations.

Updated
Reading time
2 min read

Read proxy headers on the server

In the App Router, read request headers from server components, route handlers, or server actions when the runtime provides them. A simple helper can start with `const list = headers().get("x-forwarded-for"); const ip = list?.split(",")[0]?.trim();` and fall back to `x-real-ip` or platform-specific headers.

Do not expect browser-side code to know the real public IP without calling a server or lookup service. The client sees its network APIs, while the server sees the connection metadata and proxy headers.

Middleware and route handlers

Middleware can inspect `request.headers.get("x-forwarded-for")`, `request.headers.get("x-real-ip")`, or provider headers before rewriting, redirecting, or adding request context. Keep middleware light because it runs on every matched request.

In an App Router API route, use `export async function GET(request: Request) { const forwarded = request.headers.get("x-forwarded-for"); return Response.json({ ip: forwarded?.split(",")[0]?.trim() ?? null }); }`. Validate and normalize the value before storing or enforcing rules.

Platform differences

Vercel, Cloudflare, load balancers, and reverse proxies may set different headers such as `x-forwarded-for`, `x-real-ip`, `cf-connecting-ip`, or vendor-specific equivalents. Document which proxy you trust and which header wins.

If you deploy behind multiple proxies, only trust forwarded headers from infrastructure you control. For manual verification, compare the captured IP with Crafzo and confirm the location and ISP match expectations.

Frequently asked questions

Keep reading