How to get the IP address of a client in Node.js
Sep 18, 2022, Originally published at techvblogs.com ・2 min read
What is an IP Address?
An Internet Protocol(IP) address also known as a logical address is given by the internet service provider(ISP) which uniquely identifies a system over the network. IP address keeps on changing from time to time.
A small node.js module to retrieve the request’s IP address. It looks for specific headers in the request and falls back to some defaults if they do not exist.
The user IP is determined in the following order:
X-Client-IP
X-Forwarded-For
(Header may return multiple IP addresses in the format: “client IP, proxy 1 IP, proxy 2 IP”, so we take the first one.)CF-Connecting-IP
(Cloudflare)Fastly-Client-Ip
(Fastly CDN and Firebase hosting header when forwarded to a cloud function)True-Client-Ip
(Akamai and Cloudflare)X-Real-IP
(Nginx proxy/FastCGI)X-Cluster-Client-IP
(Rackspace LB, Riverbed Stingray)X-Forwarded
,Forwarded-For
andForwarded
(Variations of #2)req.connection.remoteAddress
req.socket.remoteAddress
req.connection.socket.remoteAddress
req.info.remoteAddress
If an IP address cannot be found, it will return null
.
How to get the IP address of a client in Node.js
To get the IP address of a client, We will use the request-ip package in node.js.
Step 1: Create Node JS App
Execute the following command to create the node js app:
mkdir node-ip
cd node-ip
npm init -y
Step 2: Install Express and request-ip library
Execute the following command to install express and request-ip. Usually, We will use express as our web server.
npm install express
npm install request-ip --save
Step 3: Create a Server.js File
Create a file named server.js in your project root directory and add the following code to that file:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Step 4: Import request-ip package into node application
const express = require('express')
const requestIp = require('request-ip')
const app = express()
const port = 3000
app.get('/', (req, res) => {
var clientIp = requestIp.getClientIp(req)
res.send(`Your IP Address is ${clientIp}.`)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Step 5: Start Development Server
Execute the following command to run the development server:
node server.js
After running the above command and open http://localhost:3000
in your browser.
Thank you for reading this article.