How to Create a Middleware to Retrieve X-REAL-IP and X-Forwarded-For in HTTP Calls with Node.js and Express

Tiempo de lectura: 2 minutos

html
Copy code

In Node.js, you can use middlewares in Express.js to customize the handling of HTTP requests before or after they reach the routes. In this tutorial, you will learn how to create a middleware that extracts the X-REAL-IP and x-forwarded-for headers from incoming HTTP calls in your Express application.

Prerequisites:

  1. Node.js installed on your system.
  2. Basic knowledge of Node.js and Express.

Step 1: Set Up Your Environment
Make sure you have Node.js installed on your system. You can download it from the official Node.js website.

Step 2: Create an Express Application
Create a basic Express application in a JavaScript file (e.g., app.js):

const express = require('express');
const app = express();

// ... Configure your routes and application logic here

app.listen(3000, () => {
  console.log('Express server is running on port 3000');
});

Step 3: Create a Middleware
Create a middleware that will act as your interceptor. This middleware takes three arguments: req, res, and next. The third argument, next, represents the next function that will be executed after the middleware performs its task.

function realIpMiddleware(req, res, next) {
  // Extract the X-REAL-IP header if present
  const realIp = req.get('x-real-ip');

  // Extract the X-FORWARD header if present
  const forwardHeader = req.get('x-forwarded-for');

  // Assign the values to variables if present
  if (realIp) {
    req.ip = realIp;
  }

  if (forwardHeader) {
    req.forwarded = forwardHeader;
  }

  // Call the next middleware or route in the request handling chain
  next();
}

In this example, we are extracting the X-REAL-IP and x-forwarded-for headers if they are present in the request and assigning them to the req.ip and req.forwarded properties. Then, we call next() to continue with the next middleware or route.

Step 4: Use the Middleware
Use the middleware in your Express application before your routes:

app.use(realIpMiddleware);

// ... Configure your routes after the middleware

Step 5: Create a Sample Route
Add a sample route to test the middleware:

app.get("/", (req, res) => {
  // Access the ip and forwarded properties if they have been assigned correctly
  const realIp = req.ip;
  const forwardHeader = req.forwarded;

  res.json({ "x-real-ip": realIp, "x-forwarded-for": forwardHeader });
});

Step 6: Run Your Application
Run your Express applicationhtml
Copy code

Step 6: Run Your Application
Run your Express application:

node app.js

Step 7: Test Your Middleware
Make a request to your Express application and verify that the X-REAL-IP and x-forwarded-for headers are correctly extracted and displayed in the response.

Conclusion:
You’ve learned how to create a middleware in Node.js and Express to obtain the X-REAL-IP and x-forwarded-for headers from incoming HTTP calls. Middlewares allow you to customize the handling of HTTP requests and perform additional tasks before or after a request is handled by your Express application. You can adapt this approach to work with other headers or perform other customization tasks according to your specific needs.

html
Copy code

Conclusion:
You’ve learned how to create a middleware in Node.js and Express to obtain the X-REAL-IP and x-forwarded-for headers from incoming HTTP calls. Middlewares allow you to customize the handling of HTTP requests and perform additional tasks before or after a request is handled by your Express application. You can adapt this approach to work with other headers or perform other customization tasks according to your specific needs.

Leave a Comment