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:
mkdir express-ip-demo
cd express-ip-demo
npm init -y
npm install express
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
:
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');
});
3. Get the IP Address
In the code above, we are using the following method to retrieve the IP address:
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:
node app.js
Visit http://localhost:3000
in your browser or use a tool like curl
to send a request:
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!