Logo Vincent
Back to all posts

Node.js Web Server in Practice: Getting the Public IP

Node.js

Preface

In Node.js server development, there are scenarios where you need to get the public IP.

However, the default method for getting the IP in Node.js can only retrieve the local IP,

not the public one. This article explains how to get the public IP.

Getting the Public IP on the Server

Getting the public IP on the server side is fairly straightforward.

In Node.js, you can use the following method:

request.connection.remoteAddress;

However, if you are using a reverse proxy like nginx,

the method above will only return the proxy’s IP.

You can modify the nginx configuration as follows:

location / {
  proxy_pass http://127.0.0.1:9001;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;  # This line.
}

Then retrieve the actual IP via req.headers:

req.headers['x-real-ip'];

qiao-z

qiao-z is a minimalist Node.js web server framework.

https://qiao-z.vincentqiao.com/#/

In qiao-z, you can easily get the public IP:

req.ip;

qiao-get-ip

There is also a packaged npm module, qiao-get-ip: https://code.insistime.com/#/qiao-get-ip

Usage is simple:

const { getIP } = require('qiao-get-ip');

const ip = await getIP();

It sends requests to the following services,

with a default timeout of 200ms, and returns the fastest response

to get the public IP:

Summary

1. How to get the public IP on a Node.js server

2. Using qiao-z to build a server and get the public IP via req.ip, https://qiao-z.vincentqiao.com/#/api/req?id=reqip

3. Using qiao-get-ip to get the public IP, https://code.insistime.com/#/qiao-get-ip

© 2026 Vincent. All rights reserved.