Next.js Discord

Discord Forum

get ip address NextRequest

Answered
Savannah posted this in #help-forum
Open in Discord
SavannahOP
Hi guys, i try to get the user ip but it always returning me ::1, someone know what am i doing wrong ?

i tried 2 codes :

first one :

import {NextRequest, NextResponse} from "next/server";
import {cookies} from "next/headers";

export function POST(req: NextRequest, res: any){
    let ip = req.headers.get('X-Forwarded-For')
    console.log('ip', ip)
    return NextResponse.json({test: 'test'})
}


second one :
import {NextRequest, NextResponse} from "next/server";

export function POST(req: NextRequest, res: any){
    const headers = new Headers(req.headers)
    let ip = headers.get('x-forwarded-for') ?? '0.0.0.0'
    console.log('ip', ip)
    return NextResponse.json({test: 'test'})
}
Answered by B33fb0n3
try it on a real server. Like vercel or whereever you host. Then the ip will automatically change to the correct one
View full answer

13 Replies

@B33fb0n3 you only tried it on localhost?
SavannahOP
yep
try it on a real server. Like vercel or whereever you host. Then the ip will automatically change to the correct one
Answer
@B33fb0n3 When you will try it? [thinkingfish](https://cdn.discordapp.com/emojis/813518806193405973.webp?size=48&quality=lossless&name=thinkingfish)
SavannahOP
before, i'm trying another issue with mapbox (and GeolocateControl), but i don't find, i'll try asap, why ? ^^
ah sounds great. Let me know if that works 👍
@B33fb0n3 ah sounds great. Let me know if that works 👍
SavannahOP
yeah, sure
Southern rough shrimp
your code seems correct, are you doing the freecodecamp stuff?
btw just a tip, if you proxy it can be different, cloudflare has a different header etc
for cloudflare its CF-Connecting-IP
@Southern rough shrimp your code seems correct, are you doing the freecodecamp stuff?
::1 is just a loop back address in ipv6. Because of that I asked if he tested it only on localhost. So if he's on a real server, the address shouldn't be ::1