EN
Express.js - get client IP address from request / req
4 points
In this short article, we would like to show how to get a client IP address from a request (req
argument) in Express.js server application.

Steps:
- Integrate below code with your web site,
- Run your Express.js server application,
- Open one of the following addresses in the web browser:
http://localhost:3000/client-ip-address
for localhost development,https://my-domain.com:3000/client-ip-address
for production.
index.js
file:
xxxxxxxxxx
1
const express = require('express');
2
3
const {getRequestIpAddress} = require('./request-utils');
4
5
const port = 3000;
6
const app = express();
7
8
app.get('/client-ip-address', (req, res) => {
9
const ip = getRequestIpAddress(req);
10
response.send(`Client IP Address: ${ip}`);
11
});
12
13
app.listen(port, () => {
14
console.log(`Server is listening at ${port} port.`);
15
});
request-utils.js
file:
xxxxxxxxxx
1
const IP_HEADERS = [
2
'Forwarded',
3
'Forwarded-For',
4
'X-Forwarded',
5
'X-Forwarded-For', // may contain multiple IP addresses in the format: 'client IP, proxy 1 IP, proxy 2 IP' - we use first one
6
'X-Client-IP',
7
'X-Real-IP', // Nginx proxy, FastCGI
8
'X-Cluster-Client-IP', // Rackspace LB, Riverbed Stingray
9
'Proxy-Client-IP',
10
'CF-Connecting-IP', // Cloudflare
11
'Fastly-Client-Ip', // Fastly CDN and Firebase hosting header when forwared to a cloud function
12
'True-Client-Ip', // Akamai and Cloudflare
13
'WL-Proxy-Client-IP',
14
'HTTP_X_FORWARDED_FOR',
15
'HTTP_X_FORWARDED',
16
'HTTP_X_CLUSTER_CLIENT_IP',
17
'HTTP_CLIENT_IP',
18
'HTTP_FORWARDED_FOR',
19
'HTTP_FORWARDED',
20
'HTTP_VIA',
21
'REMOTE_ADDR'
22
23
// you can add more matching headers here ...
24
];
25
26
const getRequestIpAddress = request => {
27
const headers = request.headers;
28
for (const header of IP_HEADERS) {
29
const value = headers[header];
30
if (value) {
31
const parts = value.split(/\s*,\s*/g);
32
return parts[0] ?? null;
33
}
34
}
35
const client = request.connection ?? request.socket ?? request.info;
36
if (client) {
37
return client.remoteAddress ?? null;
38
}
39
return null;
40
};
41
42
module.exports = {
43
getRequestIpAddress
44
};
Note:
IP_HEADERS
are useful to get a client IP address when we use some other application that may cover our server, e.g.VirtualServers
, load balancers, etc.