Enhance Your Web Application with GeoIP Lite A Comprehensive Guide with API Examples

Introduction to geoip-lite

The geoip-lite library is a lightweight Node.js module for GeoIP lookups. It allows users to query geographical information associated with IP addresses. This can be useful for a variety of applications such as website personalization, security checks, and analytic data gathering. In this article, we will explore the functionalities of geoip-lite and provide several API examples to get you started.

Installation

npm install geoip-lite

Initialization

const geoip = require('geoip-lite');

Basic Usage

Retrieve geolocation information of an IP address:

const ip = '207.97.227.239';
const geo = geoip.lookup(ip);
console.log(geo);

Output:

{ range: [ 347929344, 347932671 ],
  country: 'US',
  region: 'CA',
  eu: '0',
  timezone: 'America/Los_Angeles',
  city: 'San Francisco',
  ll: [ 37.7758, -122.4128 ],
  metro: 807,
  area: 1000 }

Check if IP is from an EU Country

const geo = geoip.lookup('207.97.227.239');
console.log(geo.eu === '1' ? 'EU IP' : 'Non-EU IP');

Get Country of the IP

const geo = geoip.lookup('207.97.227.239');
if (geo) {
  console.log(geo.country);
}

Get Latitude and Longitude

const geo = geoip.lookup('207.97.227.239');
if (geo) {
  console.log(geo.ll);
}

API Example: Express.js Application

Let’s create a simple Express.js application that uses geoip-lite to display the geolocation of visitors:

const express = require('express');
const geoip = require('geoip-lite');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  const geo = geoip.lookup(ip);
  
  res.send(`Your IP is: ${ip} 
Geolocation: ${JSON.stringify(geo)}`); }); app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });

Now, when you run this application and access it via your browser, it will show your IP address and its geolocation information.

Conclusion

The geoip-lite library is a powerful and lightweight tool that can significantly enhance the geolocation capabilities of your Node.js applications. Whether you are building a personalized user experience, performing security checks, or gathering analytics, the geoip-lite library offers a simple and effective way to retrieve geographical information from IP addresses.

Hash: 90ca59daa79144335514c88a6fa26cea428624a8fd32a7b4d9607cd1ae743b5b

Leave a Reply

Your email address will not be published. Required fields are marked *