Introduction to Forwarded
The forwarded
module is an important middleware for Node.js that allows you to extract the forwarded address from HTTP headers. This is particularly useful in applications where you need to determine the originating IP address of a client when the server is behind a proxy or load balancer.
Installation
npm install forwarded
How to Use Forwarded Module
The following example demonstrates how to use the forwarded
module to extract the original client IP address:
Basic Usage
const http = require('http');
const forwarded = require('forwarded');
const server = http.createServer((req, res) => {
const addresses = forwarded(req);
res.end(`Client IP: ${addresses[0]}`);
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Example with Express
const express = require('express');
const forwarded = require('forwarded');
const app = express();
app.use((req, res, next) => {
const addresses = forwarded(req);
console.log(`Client IP: ${addresses[0]}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Express server running on port 3000');
});
API Reference
forwarded(req)
This is the only API function provided by forwarded
.
const addresses = forwarded(req);
Arguments:
req
: The HTTP request object.
Returns:
- An array of IP addresses. The first IP address is the original client IP.
Full Example
Below is a full example of a Node.js application utilizing the forwarded
module to determine the client’s IP address:
const http = require('http');
const forwarded = require('forwarded');
const server = http.createServer((req, res) => {
const addresses = forwarded(req);
res.setHeader('Content-Type', 'text/plain');
res.end(`Client IP list: ${addresses.join(', ')}`);
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
With this setup, you can accurately determine the original client IP address through the forwarded
module, which is integral for logging, security, and more.
Hash: 8e12cac141092888b455b1042ce0f135b93f62d14079f9ac5799b4808829b581