DEV Community

Ondev Webs
Ondev Webs

Posted on

Complete Guide to Tracking Website Visitors: IP Addresses, Devices, and City

To track visitors' IP addresses, device information, and city, you can use a combination of server-side and client-side technologies. Here's a brief overview of how you can do it:

Server-side tracking: When a user visits your website, their browser sends a request to your server. You can log the IP address of the user in your server logs or a database. Here's an example code in Node.js using the Express framework:

javascript

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

app.use((req, res, next) => {
  const ip = req.ip;
  // log IP address to database or server logs
  console.log('IP address:', ip);
  next();
});
Enter fullscreen mode Exit fullscreen mode

This code logs the user's IP address to the console. You can modify it to save the IP address to a database or server logs.

Client-side tracking: To track the user's device information and city, you can use JavaScript to gather information from the user's browser and send it to your server. Here's some example code using the Geolocation API to get the user's city:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    const lat = position.coords.latitude;
    const long = position.coords.longitude;
    const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${YOUR_API_KEY}`;
    fetch(apiUrl)
      .then(response => response.json())
      .then(data => {
        const city = data.name;
        // send city to server
        console.log('City:', city);
      })
      .catch(error => console.error(error));
  });
}
Enter fullscreen mode Exit fullscreen mode

This code uses the OpenWeatherMap API to get the user's city based on their latitude and longitude. You can modify it to use a different API or database to get the city information.

To track the user's device information, you can use the navigator.userAgent property in JavaScript to get information about the user's browser, operating system, and device. Here's an example:

const userAgent = navigator.userAgent;
console.log('User agent:', userAgent);
Enter fullscreen mode Exit fullscreen mode

This code logs the user's user agent string to the console. You can parse the string to extract information about the user's device.

It's important to note that tracking user information requires user consent and compliance with privacy regulations. Make sure to inform users about what information you are collecting and why, and provide them with an opt-out option.

Top comments (0)