0
0
ExpressHow-ToBeginner · 3 min read

How to Get Request IP in Express: Simple Guide

In Express, you can get the client's IP address using req.ip or req.headers['x-forwarded-for'] if behind a proxy. Use app.set('trust proxy', true) to correctly get the IP when your app is behind a proxy or load balancer.
📐

Syntax

To get the IP address of a client in Express, use the req.ip property. If your app is behind a proxy, you should enable trust proxy with app.set('trust proxy', true) to get the correct IP from the X-Forwarded-For header.

  • req.ip: Returns the remote IP address of the request.
  • req.headers['x-forwarded-for']: Contains the original IP if behind a proxy.
  • app.set('trust proxy', true): Tells Express to trust the proxy headers.
javascript
app.set('trust proxy', true);

app.get('/', (req, res) => {
  const ip = req.ip;
  res.send(`Your IP is ${ip}`);
});
💻

Example

This example shows a simple Express server that returns the client's IP address in the response. It uses app.set('trust proxy', true) to handle cases where the app is behind a proxy.

javascript
import express from 'express';

const app = express();
app.set('trust proxy', true);

app.get('/', (req, res) => {
  const clientIp = req.ip;
  res.send(`Client IP address is: ${clientIp}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // When accessed, response shows: // Client IP address is: ::1 (or your actual IP)
⚠️

Common Pitfalls

Many developers forget to enable trust proxy when their app is behind a proxy or load balancer. This causes req.ip to return the proxy's IP instead of the client's real IP.

Also, relying only on req.connection.remoteAddress or req.socket.remoteAddress can give incorrect IPs in proxied environments.

javascript
/* Wrong way: Not trusting proxy */
app.get('/', (req, res) => {
  const ip = req.connection.remoteAddress;
  res.send(`IP: ${ip}`);
});

/* Right way: Trust proxy and use req.ip */
app.set('trust proxy', true);
app.get('/', (req, res) => {
  const ip = req.ip;
  res.send(`IP: ${ip}`);
});
📊

Quick Reference

Property/MethodDescription
req.ipGets the client IP address, respects proxy if trust proxy is enabled
req.headers['x-forwarded-for']Contains original IP chain if behind proxies
app.set('trust proxy', true)Enables Express to trust proxy headers for IP
req.connection.remoteAddressRaw socket IP, may be proxy IP, not reliable behind proxies

Key Takeaways

Use req.ip to get the client's IP address in Express.
Enable app.set('trust proxy', true) when behind proxies to get the real IP.
Avoid using req.connection.remoteAddress alone as it may return proxy IP.
Check req.headers['x-forwarded-for'] for original IPs in proxied setups.
Always test your app behind your actual deployment environment to confirm IP detection.