Get the IP address of a user in Node.js
Last updated: December 21, 2022.
To get the IP address of a user of a Node.js website or app, you can simply call req.socket.remoteAddress
, where req
is the incoming request object.
Here is an example using a server created using Node’s native http module:
const http = require('http');
http.createServer(function (req, res) {
req.socket.remoteAddress; // returns user IP
res.end();
}).listen(3000);
Using Express.js
Express.js is an insanely popular library used to simplify the process of creating a server in Node.js.
If you have installed Express.js and imported it at the top of your script, you can use an even simpler syntax for detecting a user’s IP address: req.ip
!
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
req.iq; // Returns user IP
res.send('Response complete');
})
app.listen(port, () => {
console.log(`Listening on port ${port}`)
})