In Next.js, retrieving the client's IP address from the server side typically involves handling HTTP requests within API routes. Next.js's API routes feature enables you to create JavaScript files in the /pages/api directory to handle HTTP requests. Here is an example demonstrating how to retrieve the client's IP address within Next.js API routes:
-
Create an API route file: Create a new file in the
pages/apidirectory, such asget-ip.js. -
Write the logic to retrieve the IP address: In this file, you can access request information, including the client's IP address, via the
reqobject. However, it is important to note that directly retrieving the IP address from thereqobject may be impacted by proxies (such as NGINX or other reverse proxy software). In such cases, the IP address may be stored in theX-Forwarded-ForHTTP header.
Here is a concrete implementation example:
javascriptexport default function handler(req, res) { let ipAddress; // Attempt to retrieve IP address from X-Forwarded-For header const xForwardedFor = req.headers['x-forwarded-for']; if (xForwardedFor) { ipAddress = xForwardedFor.split(',')[0]; // Multiple IP addresses may be provided; use the first one } else { // If no X-Forwarded-For header, directly obtain the connected IP address ipAddress = req.socket.remoteAddress; } // Return IP address to the client res.status(200).json({ ip: ipAddress }); }
- Test the API route:
You can access
http://localhost:3000/api/get-ipto view the results of this API route, which should return the client's IP address accessing the API.
With the above code, you can retrieve and process the client's IP address on the server side. This method is highly useful for handling user authentication, logging, and location-related features.