How to Get IP Address Using Express.js

When building a web application with Express.js, it’s often useful to capture the IP address of the client making the request. This can be for analytics, logging, or security purposes. Fortunately, Express.js makes it quite simple to retrieve this information.

Step-by-Step Guide

1. Install Express

Before we begin, make sure you have Node.js and npm installed on your system. If not, you can download them from nodejs.org.

Next, create a new project and install Express:

Bash
mkdir express-ip-demo
cd express-ip-demo
npm init -y
npm install express
Expand

2. Create a Simple Express Server

Now that Express is installed, let’s create a basic server to handle client requests.

Create a file named app.js:

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

// Create a route to capture IP address
app.get('/', (req, res) => {
  // Get the client's IP address
  const clientIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  
  res.send(`Your IP address is: ${clientIp}`);
});

// Start the server on port 3000
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
Expand

3. Get the IP Address

In the code above, we are using the following method to retrieve the IP address:

JavaScript
const clientIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  • req.headers['x-forwarded-for']: This is useful when your app is behind a proxy (like in production environments).
  • req.connection.remoteAddress: This gets the raw IP address when the request is made directly to your server without any proxie

4. Test Your App

Now run the app with:

Bash
node app.js

Visit http://localhost:3000 in your browser or use a tool like curl to send a request:

Bash
curl http://localhost:3000

You should see your IP address displayed as part of the response.

Conclusion

With just a few lines of code, you can easily retrieve the client’s IP address in an Express.js application. This can be a useful feature for many web applications that need to track or log user activity.

That’s it! Happy coding!

Leave a Comment

Scroll to Top