SoFunction
Updated on 2025-04-13

Several common ways to obtain user IP information on the front end

Preface

Getting the user's IP address on the front-end page is not a direct matter, because for privacy and security reasons, browsers usually do not directly provide the user's IP address to the front-end JavaScript code. However, there are some indirect methods to obtain the user's IP address. Here are a few common methods:

1. Use third-party services

Get the user's IP address by calling a third-party service. These services usually return the user's IP address information.

Sample code

async function getUserIP() {
  try {
    const response = await fetch('?format=json');
    const data = await ();
    ('User IP:', );
    return ;
  } catch (error) {
    ('Error fetching IP address:', error);
  }
}

getUserIP();

Commonly used third-party services

  • ipify
  • ipstack

2. Use the browser's WebRTC API

The WebRTC API can be used to obtain the user's IP address, but this method requires user authorization and may expose the user's local IP address.

Sample code

function getUserIP(callback) {
  const RTCPeerConnection =  ||  || ;
  if (!RTCPeerConnection) {
    callback('Not compatible with WebRTC');
    return;
  }

  const pc = new RTCPeerConnection({ iceServers: [] });
  const noop = () => {};

  ('');
  ().then(sdp => (sdp)).catch(noop);

   = ice => {
    if (!ice || ! || !) return;
    const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
    const ipMatch = (ipRegex);
    if (ipMatch) {
      callback(ipMatch[1]);
      ();
    }
  };
}

getUserIP(ip => {
  ('User IP:', ip);
});

3. Use the server to obtain the IP address

The safest and reliable way is to get the user's IP address through the server side and then pass the IP address to the front end.

Sample flow

  • Front-end request server

    async function getUserIP() {
      try {
        const response = await fetch('/api/get-ip');
        const data = await ();
        ('User IP:', );
        return ;
      } catch (error) {
        ('Error fetching IP address:', error);
      }
    }
    
    getUserIP();
    
  • Server-side processing(Take an example):

    const express = require('express');
    const app = express();
    
    ('/api/get-ip', (req, res) => {
      const ip = ['x-forwarded-for'] || ;
      ({ ip });
    });
    
    (3000, () => {
      ('Server is running on port 3000');
    });
    

Things to note

  • Privacy and security: To obtain the user's IP address, you must follow relevant privacy policies and laws and regulations to ensure that the user is aware and agree.
  • accuracy: The IP address obtained through a third-party service may be the IP address of the proxy server or CDN, rather than the actual IP address of the user.
  • Security: Avoid directly exposing the user's sensitive information on the front end to ensure the security of data transmission.

explain

  • Front-end page loading: Users access the front-end page.
  • Call third-party services to obtain IP: The front-end calls third-party services through AJAX request.
  • Send a request to a third-party service: The front-end sends a request to a third-party service to obtain the IP address.
  • Third-party service returns IP address: The third-party service returns the user's IP address.
  • Front-end processing IP address: The IP address returned by the front-end processing.
  • Display or use IP address: The front-end displays or uses the obtained IP address.

Using the WebRTC API

  • Front-end page loading: Users access the front-end page.
  • Create an RTCPeerConnection: Create an RTCPeerConnection object.
  • Create a data channel: Create a data channel.
  • Create an Offer: Create an offer.
  • Setting up a local description: Set the local description.
  • Listen to ICE candidates: Listen to ICE candidate events.
  • Extract IP address: Extract IP address from ICE candidates.
  • Front-end processing IP address: The front-end processed the extracted IP address.
  • Display or use IP address: The front-end displays or uses the obtained IP address.

Use the server to obtain IP

  • Front-end page loading: Users access the front-end page.
  • Call the server API to get the IP: The front-end calls the server API through AJAX request.
  • Send a request to the server: The front-end sends a request to the server.
  • Server gets IP address: The server obtains the user's IP address from the request header.
  • The server returns the IP address: The server returns the user's IP address.
  • Front-end processing IP address: The IP address returned by the front-end processing.
  • Display or use IP address: The front-end displays or uses the obtained IP address.

Through the above method, you can obtain the user's IP address on the front-end page and process it according to specific needs.

Summarize

This is the end of this article about several common methods for obtaining user IP information in front-end. For more related front-end content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!