Next.js Discord

Discord Forum

How to get IP Address inside next auth callback authorize

Unanswered
iC0d3X posted this in #help-forum
Open in Discord
Hello,

how can I get IP Address inside the next auth authorize?

I tried with the Advanced initialization from the docs https://next-auth.js.org/configuration/initialization#advanced-initialization.

export async function POST(req: NextApiRequest, res: NextApiResponse) {
    console.log(req.headers["x-real-ip"] || req.socket.remoteAddress)
    return NextAuth(req, res, authOptions)
}

export async function GET(req: NextApiRequest, res: NextApiResponse) {
    console.log(req.headers["x-real-ip"] || req.socket.remoteAddress)
    return NextAuth(req, res, authOptions)
}


but it is always undefined. Also I get an error when trying to use next build:

Type 'NextApiRequest' is not assignable to type 'Request | NextRequest'.
Type 'NextApiRequest' is missing the following properties from type 'NextRequest': geo, ip, nextUrl, page, and 19 more.

Thanks in advance.

6 Replies

up
can u share more info with us? say does this sample middleware.ts get IP right?
https://github.com/tfutada/zenn-nextjs/blob/main/middleware.ts
export function middleware(request: NextRequest) {

    const clientIP = request.ip ?? "127.0.0.1";
    console.log(`MW: clientIP: ${clientIP}`);

    // The public IP address of the client that made the request.
    // If you are trying to use Vercel behind a proxy, we currently overwrite the
    // X-Forwarded-For
    //  header and do not forward external IPs.
    //  This restriction is in place to prevent IP spoofing.
    //  Please contact us if allowing Vercel to trust your X-Forwarded-For IP is a feature your Team needs (Enterprise only).
    const x_real_ip = request.headers.get('x-real-ip');
    const x_forwarded_for = request.headers.get('x-forwarded-for');

    console.log(`MW: x-real-ip: ${x_real_ip}`);
    console.log(`MW: x-forwarded-for: ${x_forwarded_for}`);
it helps isolate the problem by simplifying the codes.
Sorry mate, I was on a short vacation, that´s why I'm replying so late.

Oh so the local IP address is not shown in the headers. I thought request.ip would return the local IP address.

That`s probably why I got undefined every time, as I was accessing my application locally.

Thank you, I will try in a bit to deploy my application somewhere else than my local network and give you an update.
Yep, the local address is not shown. After deploying to production I get the Public IP address of the client that made the request.
Thanks man.