Search code examples
ipnext.js13react-server-components

How can I get the IP adress of a client in server component of the app directory in Nextjs 13?


For a personal project, I want to create a game. So if the user loose, he can’t access the game for 30 minutes, there’s no registration or anything like that I just want to store the IP in my database so I can check the last time the user loose. (I built this application to improve my knowledge of Nextjs and React components) But the fact is: I can’t access the client’s IP in the server component that contains my game.

To resume, how can I get the client’s IP inside a server component inside the 'app' directory?

I have to make an API call inside the client component to get the req object and then get the IP but this solution triggers me because it is not optimal for the user experience.


Solution

  • You can use the nextjs middleware to pass the ip address provided by your host to your general headers.

    After that, you would be able to access the ip address through your header in your server component.

    This could look like this:

    // middleware.ts
    import { NextResponse } from "next/server";
    import type { NextRequest } from "next/server";
    
    export function middleware(request: NextRequest) {
      // Clone the request headers so that we don't modify the original headers object
      const requestHeaders = new Headers(request.headers);
    
      // Check if the hosting platform provides the client's IP address and store it in a variable
      const ip = request.ip || "";
    
      // Add the client's IP address to the request headers using the 'x-forwarded-for' field
      requestHeaders.set("x-forwarded-for", ip);
    
      // Return a new request object with the updated headers using NextResponse.next()
      return NextResponse.next({
        request: {
          headers: requestHeaders,
        },
      });
    }
    
    // app/page.tsx
    
    import { headers } from "next/headers";
    
    export default function Home() {
      // Get the client's IP address from the request headers
      const ip = headers().get("x-forwarded-for");
    
      return (
        <main className={styles.main}>
          <div className={styles.description}>
            <p>
              IP Address:
              {` ${ip}` || " Not found"}
            </p>
            ...
          </div>
          ...
        </main>
      );
    }
    

    I deployed this example on Vercel and its working perfectly, I hope its helping you :)