How to Get Client IP Address in Node JS Application
In this article, we will explain to you how to get client IP address in node js application. sometimes we need to client ip address in node js, We will use get the real IP address in node js app. Let’s start with how to find out the IP address of the client in the node js.
We can easily get client ip address using the request-ip NPM package in node js application. This npm package retrieves a request’s IP address in node js.
Node Js Application Setup
First, we will open the command prompt and create the application in our directory. for this, you can follow the below command.
1 2 3 | mkdir my_node_app cd my_node_app npm init |
Install NPM Package
After the done setup node js application, we will install the express and request-ip npm package. so you can see the following npm command.
1 | npm install express request-ip --save |
Set up Node js Application
In this step, We will create a server.js file and set up the node js application using express.
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 | var express=require('express'); var requestIp = require('request-ip'); var app = express(); app.get('/',function(req,res){ var clientIp = requestIp.getClientIp(req); res.send("Ip Address: "+clientIp); res.end(); }); app.listen(3000,function(){ console.log("Express Started on Port 3000"); }); |
server.js
1 2 3 4 5 6 7 8 9 10 11 12 | var express=require('express'); var app = express(); app.get('/',function(req,res){ var idAddress = req.header('x-forwarded-for') || req.connection.remoteAddress; res.send("Ip Address: "+idAddress ); res.end(); }); app.listen(3000,function(){ console.log("Express Started on Port 3000"); }); |
Run Node js Application
we will run the node js application using the below command. so you can follow the below command.
1 | node server.js |
Now you can run the example using the below Url in the browser.
1 | http://localhost:3000/ |