Get client IP address and user agent in Node.js

CK CK 3788 
Created at  
1,530 0 0

To get the client IP address and user agent in a Node.js application, you can use the http or express package.

 

1) Using Express

If you’re using Express, it’s straightforward:

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

app.get('/', (req, res) => {
    // Get the client's IP address
    const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

    // Get the client's User-Agent
    const userAgent = req.headers['user-agent'];

    res.send(`IP Address: ${ip}, User-Agent: ${userAgent}`);
});

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

 

2) Using the HTTP Module

If you’re using the built-in http module:

const http = require('http');

const server = http.createServer((req, res) => {
    // Get the client's IP address
    const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

    // Get the client's User-Agent
    const userAgent = req.headers['user-agent'];

    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(`IP Address: ${ip}, User-Agent: ${userAgent}`);
});

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

Notes

  • req.headers['x-forwarded-for'] is often used to get the real IP address of the client, especially when behind a proxy or load balancer.
  • req.connection.remoteAddress will give you the direct IP address from the connection.
  • The User-Agent is available in req.headers['user-agent'].

Make sure to handle the case where x-forwarded-for might contain a list of IPs (comma-separated), with the client’s IP being the first one in the list.

Tags Express Remote Address User IP Address User-Agent express() http x-forwarded-for Facebook X
Comments 0
Similar posts
  1. Node.js external modules
    429
  2. When to use #EXT-X-DISCONTINUITY in HLS?
    1,428
  1. forEach method in JavaScript when working with arrays
    665
  2. CRC32B function code in Javascript
    1,838
  3. Node.js-based Web Server supporting multiple path
    598
  4. A simple Javascript class example with static method for Node.js
    660
  5. Setting a Common Path for require() in Node.js
    993
  6. Import all JS files in a specific folder for Node.js programming
    1,724
  7. A simple example to access a PostgreSQL database in Node.js
    1,100
  8. Node.js code example to access Google BigQuery
    1,181
  9. Investigation on package.js for Node.js source code
    819
  10. Using MySQL in Node.js
    479
  11. A Node.js script that checks if a module is installed before requiring it
    770
  12. Worker Threads and Mutual Exclusion in Node.js
    461
  13. Using a module in the external class itself without creating an instance in Node.js
    349
  14. Multi-threaded Web Server based in Node.js
    864
  15. A basic HTTP server based in Node.js
    538
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,013
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    251
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  16. TPU & GPU Cluster Management Tools
    245
  17. The Concept of Scaffolding in AI Agents
    234
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    222
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    221
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  30. Understanding Data Lineage
    262