Get Visitor's IP
Answered
Giant panda posted this in #help-forum
Giant pandaOP
How can i get Visitors IP and automatic choose the language for him using his IP Location
Answered by riský
does something like this work?
// **page.client.tsx**
"use client"
// imports
export default function Page() {
const [ip, setIp] = useState(null);
useEffect(async () => {
setIp(await getIp())
}, []);
//...
// **action.ts**
"use server"
import { headers } from 'next/headers'
export async function getIp() {
return headers().get("x-forwarded-for")
}ip will be undefined during ssr, but when page loaded and the new req it should exist19 Replies
@Giant panda How can i get Visitors IP and automatic choose the language for him using his IP Location
are you using vercel, cloudflare, or custom (vercel makes this easier)
if vercel, you can see the many headers they expose: https://vercel.com/docs/edge-network/headers#request-headers
@riský are you using vercel, cloudflare, or custom (vercel makes this easier)
Giant pandaOP
vercel
well hosting on vercel
and using cloudflare
nice and same
to get the IP, you can use
i don't think there is a language thing tho (but the ip to country exists :))
x-forwarded-for and for the country x-vercel-ip-countryi don't think there is a language thing tho (but the ip to country exists :))
@riský to get the IP, you can use `x-forwarded-for` and for the country `x-vercel-ip-country`
i don't think there is a language thing tho (but the ip to country exists :))
Giant pandaOP
Can you give me a Code Example?
something like this should show your ip (but bascly just use next/headers)
import { headers } from 'next/headers'
export default function ShowIP() {
const ip = headers().get("x-forwarded-for")
return (
<p>{ip}</p>
)
}so you try to make it a server action? i can work with this
does something like this work?
// **page.client.tsx**
"use client"
// imports
export default function Page() {
const [ip, setIp] = useState(null);
useEffect(async () => {
setIp(await getIp())
}, []);
//...
// **action.ts**
"use server"
import { headers } from 'next/headers'
export async function getIp() {
return headers().get("x-forwarded-for")
}ip will be undefined during ssr, but when page loaded and the new req it should existAnswer
alternatively, you can make a server component page which uses same header thing and passes that into page props
Giant pandaOP
alr thanks lemme try
Thanks it works perfectly
yay!
yeah so the thing i changed was effectivly just useEffect because you can't use serevre actions on server render, but nice too see it works 🙂