Next.js Discord

Discord Forum

Getting IP

Answered
Spectacled Caiman posted this in #help-forum
Open in Discord
Spectacled CaimanOP
What is the best way to get the users IP? Because when I host on Vercel it no longer returns the end-users IP ( when I request [ifconfig.me](https://ifconfig.me/all.json) ) I need to get users ip once in my next-auth signIn function and another time in a page function like this:

export default async function Redirect({ params: { code } }: Props) {
  const data = await db.url.findFirst({
    where: {
      code,
    },
  });

  if (!data) return redirect("/error?message=Redirect+url+was+not+found");

  if (!data.active)
    return redirect("/error?message=Redirect+url+has+been+temporally+disabled");

    await db.url.update({
        where: {
            code: code as string
        },
        data: {
            analytics: {
                push: {
                    url: 'ok'
                }
            }
        }
    })

  redirect(data.redirectUrl);
}

3 Replies

Common paper wasp
Hey, this code works for me on nextjs 14 and vercel.

function getIpAddress(request: NextRequest) {
  const headers = new Headers(request.headers);

  return headers.get('x-forwarded-for') ?? '0.0.0.0';
}
Answer
Spectacled CaimanOP
Thank you! I'm using both methods now and they both get the job done :sunglasses_1: