or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Request IP

1

2

Request IP is a small Node.js module for retrieving a request's IP address from HTTP requests. It systematically checks various HTTP headers and connection properties to determine the client's real IP address, handling proxy configurations, CDN scenarios, and various web server environments.

3

4

## Package Information

5

6

- **Package Name**: request-ip

7

- **Package Type**: npm

8

- **Language**: JavaScript/Node.js

9

- **Installation**: `npm install request-ip`

10

11

## Core Imports

12

13

```javascript

14

const requestIp = require('request-ip');

15

```

16

17

For ES modules (using dynamic import):

18

19

```javascript

20

const requestIp = await import('request-ip');

21

```

22

23

## Basic Usage

24

25

```javascript

26

const requestIp = require('request-ip');

27

28

// Inside middleware handler

29

const ipMiddleware = function(req, res, next) {

30

const clientIp = requestIp.getClientIp(req);

31

console.log('Client IP:', clientIp);

32

next();

33

};

34

35

// As Connect/Express middleware

36

app.use(requestIp.mw());

37

38

app.use(function(req, res) {

39

const ip = req.clientIp;

40

res.end(ip);

41

});

42

```

43

44

## Architecture

45

46

Request IP uses a prioritized header checking approach:

47

48

- **Header Priority System**: Checks headers in a specific order based on reliability and common proxy configurations

49

- **Fallback Strategy**: Falls back to connection-level IP detection when headers are unavailable

50

- **Framework Support**: Works with Express, Connect, Fastify, and other Node.js web frameworks

51

- **Middleware Integration**: Provides both functional API and middleware factory pattern

52

53

## Capabilities

54

55

### Client IP Detection

56

57

Core functionality for extracting client IP addresses from HTTP request objects.

58

59

```javascript { .api }

60

/**

61

* Determine client IP address from request object

62

* @param {Object} req - HTTP request object

63

* @returns {string|null} Client IP address or null if not found

64

*/

65

function getClientIp(req);

66

```

67

68

**Usage Example:**

69

70

```javascript

71

const requestIp = require('request-ip');

72

73

// Basic usage

74

const ip = requestIp.getClientIp(req);

75

if (ip) {

76

console.log('Client IP:', ip);

77

} else {

78

console.log('Unable to determine client IP');

79

}

80

```

81

82

### X-Forwarded-For Header Parsing

83

84

Specialized function for parsing X-Forwarded-For headers which may contain multiple IP addresses.

85

86

```javascript { .api }

87

/**

88

* Parse x-forwarded-for headers to extract first valid IP

89

* @param {string} value - The header value to be parsed

90

* @returns {string|null} First known IP address, if any

91

* @throws {TypeError} When value is not a string

92

*/

93

function getClientIpFromXForwardedFor(value);

94

```

95

96

**Usage Example:**

97

98

```javascript

99

const requestIp = require('request-ip');

100

101

// Parse X-Forwarded-For header manually

102

const forwardedHeader = req.headers['x-forwarded-for'];

103

if (forwardedHeader) {

104

const ip = requestIp.getClientIpFromXForwardedFor(forwardedHeader);

105

console.log('Parsed IP:', ip);

106

}

107

108

// Handle multiple IPs in header

109

const multipleIps = "203.0.113.195, 70.41.3.18, 150.172.238.178";

110

const firstValidIp = requestIp.getClientIpFromXForwardedFor(multipleIps);

111

// Returns: "203.0.113.195"

112

```

113

114

### Middleware Factory

115

116

Creates Express/Connect middleware that automatically adds client IP to request objects as a computed property.

117

118

```javascript { .api }

119

/**

120

* Create middleware that adds client IP to request object as a computed property

121

* @param {Object} [options] - Configuration options

122

* @param {string} [options.attributeName='clientIp'] - Property name to add to request

123

* @returns {Function} Middleware function (req, res, next) => void

124

* @throws {TypeError} When options is not an object

125

* @note Uses Object.defineProperty with getter - IP is computed on each access

126

*/

127

function mw(options);

128

```

129

130

**Usage Examples:**

131

132

```javascript

133

const requestIp = require('request-ip');

134

const express = require('express');

135

const app = express();

136

137

// Default usage - adds req.clientIp

138

app.use(requestIp.mw());

139

140

app.get('/', (req, res) => {

141

res.send(`Your IP is: ${req.clientIp}`);

142

});

143

144

// Custom attribute name

145

app.use(requestIp.mw({ attributeName: 'userIp' }));

146

147

app.get('/user', (req, res) => {

148

res.send(`User IP: ${req.userIp}`);

149

});

150

151

// Note: The IP property is computed on each access via getter

152

// Multiple accesses to req.clientIp will re-run getClientIp(req)

153

```

154

155

## Header Priority Order

156

157

The `getClientIp` function checks headers in the following priority order:

158

159

1. `x-client-ip` - Standard header used by Amazon EC2, Heroku, and others

160

2. `x-forwarded-for` - Load-balancers (AWS ELB) or proxies (parsed via `getClientIpFromXForwardedFor`)

161

3. `cf-connecting-ip` - Cloudflare

162

4. `fastly-client-ip` - Fastly CDN and Firebase hosting

163

5. `true-client-ip` - Akamai and Cloudflare

164

6. `x-real-ip` - Default nginx proxy/FastCGI

165

7. `x-cluster-client-ip` - Rackspace LB and Riverbed Stingray

166

8. `x-forwarded` - Alternative forwarded header

167

9. `forwarded-for` - Alternative forwarded header

168

10. `forwarded` - RFC 7239 forwarded header

169

11. `x-appengine-user-ip` - Google Cloud App Engine

170

12. Connection fallbacks: `req.connection.remoteAddress`, `req.socket.remoteAddress`, etc.

171

13. `cf-pseudo-ipv4` - Cloudflare IPv6 fallback

172

14. `req.raw` - Fastify framework support

173

174

## Error Handling

175

176

```javascript { .api }

177

// TypeError exceptions

178

class TypeError extends Error {

179

// Thrown by getClientIpFromXForwardedFor when value is not a string

180

// Thrown by mw when options is not an object

181

}

182

```

183

184

**Error Examples:**

185

186

```javascript

187

const requestIp = require('request-ip');

188

189

try {

190

// This will throw TypeError: Expected a string, got "number"

191

requestIp.getClientIpFromXForwardedFor(123);

192

} catch (error) {

193

console.error('Invalid input:', error.message);

194

}

195

196

try {

197

// This will throw TypeError: Options must be an object!

198

const middleware = requestIp.mw("invalid");

199

} catch (error) {

200

console.error('Invalid options:', error.message);

201

}

202

```

203

204

## Platform Support

205

206

- **Node.js**: All versions (compiled from ES6 source)

207

- **Web Frameworks**: Express, Connect, Fastify, and others

208

- **Cloud Platforms**: AWS, Google Cloud, Azure, Heroku

209

- **CDNs**: Cloudflare, Fastly, Akamai

210

- **Reverse Proxies**: Nginx, Apache, HAProxy