1. Make sure the request is not from the local
If you test locally, the browser directly accesses localhost or 127.0.0.1, and the server will naturally only see the local IP. To test the real IP, you can:
- Another device (such as a cell phone or other computer) accesses your services.
- Deploy to a public network server and access it through a public network IP or domain name.
2. Correctly handle reverse proxy
If the service is deployed in a reverse proxy such as Nginx, make sure the proxy passes the client's IP address correctly. Here are the solutions to common problems:
(1) Enable proxy trust in Koa. The X-Forwarded-For header of the proxy does not trust by default, and needs to be enabled manually:
const Koa = require('koa'); const app = new Koa(); // Enable proxy trust (if deployed after reverse proxy) = true; // The key! Tell Koa to trust the header of the reverse proxy // Other middleware and routing...
(2) Extract the real IP from the request header to modify the routing code, and prioritize the extraction of IP from X-Forwarded-For, and process possible multiple IPs (such as multi-layer proxy):
('/get-ip', (ctx) => { // Extract client IP from X-Forwarded-For (handling multiple proxy situations) const forwardedIps = ('X-Forwarded-For') || ''; const clientIP = (',')[0]?.trim() || ; = { ip: clientIP }; });
(3) Check that some proxy servers (such as Nginx) may use X-Real-IP to pass the real IP, and you can additionally check:
const clientIP = ('X-Real-IP') || (',')[0]?.trim() || ;
3. Verify the reverse proxy configuration
If using Nginx, make sure the configuration contains the header that passes the IP:
location / { proxy_pass http://localhost:3000; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; }
Complete code example
const Koa = require('koa'); const Router = require('@koa/router'); const app = new Koa(); const router = new Router(); // Enable proxy trust (key!) = true; ('/get-ip', (ctx) => { // Try to extract the first IP from X-Forwarded-For (for reverse proxy) const forwardedIps = ('X-Forwarded-For') || ''; const clientIP = (',')[0]?.trim() || ('X-Real-IP') || ; = { ip: clientIP }; }); (()); (()); (3000, () => { ('Server is running on http://localhost:3000'); });
Test Method
- Local testing: Use curl or Postman to access your service from other devices.
- Public network test: After deploying to the server, access it through a browser or tool to observe whether the returned IP is consistent with your public network IP.
If the problem is still not resolved, please check
- Is = true enabled?
- Is the reverse proxy configuration correct?
- Is there any firewall or CDN interference?
This is the article about the Node koa server realization to obtain client IP. For more related Node to obtain client IP content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!