Sling Academy
Home/Node.js/Node.js: How to get location from IP address (3 approaches)

Node.js: How to get location from IP address (3 approaches)

Last updated: February 19, 2024

Introduction

Disclosure and examination of visitor data, notably geographical location, are crucial in many web and network applications. Understanding your users’ locations can help tailor content, enforce security measures, and provide location-specific services. One simple piece of data, the IP address, can be utilized to uncover such geographical information. This tutorial explains how to retrieve location information from an IP address using Node.js, progressing from basic methods to more advanced approaches.

In Node.js, extracting geolocation data from an IP address involves interacting with various APIs or employing specific libraries designed for this purpose. As Node.js is JavaScript-based, it fits well within the asynchronous, event-driven nature needed for handling HTTP requests to APIs or utilizing libraries for the IP geolocation task.

Prerequisites

To follow along, ensure you have the following:

  • Node.js installed on your machine. You can download it from the official Node.js website.
  • Basic understanding of Node.js and JavaScript.
  • An IP address to test. You can use your public IP as a start.

Method 1: Utilizing a Free IP Geolocation API

The simplest method to get started with obtaining location from an IP address in Node.js is by using a free IP geolocation API. For this tutorial, we’ll use http://ip-api.com/json/. This API provides various details like country, region, city, and more based on the IP address provided.

First, let’s write a basic script to make a request to this API:

const http = require('http');

const ip = 'YOUR_IP_HERE'; // Replace with your IP address
const url = `http://ip-api.com/json/${ip}`;

http.get(url, (res) => {
  let data = '';
  res.on('data', (chunk) => {
    data += chunk;
  });
  res.on('end', () => {
    console.log(JSON.parse(data));
  });
}).on('error', (err) => {
  console.error('Error: ' + err.message);
});

Running this script in your Node.js environment should display the geolocation information of the IP in the console.

Method 2: Using the ‘geoip-lite’ Library

For those preferring a server-side solution without making external API calls, ‘geoip-lite’ is a lightweight library that allows you to look up location information based on IP addresses. First, install it:

npm install geoip-lite

Then, use the following code to get the location data:

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

const ip = 'YOUR_IP_HERE'; // Replace with your IP address
const location = geoip.lookup(ip);

console.log(location);

This will give you direct access to the country, region, and city information without relying on external services.

Method 3: Building a Full-fledged Application

Let’s take a step further by creating a more comprehensive application using Express.js framework and integrating IP location functionality within. This approach offers greater flexibility, especially if you are building a larger project that may require rate limiting, caching, or other advanced features.

First, install Express.js:

npm install express

Create an application that responds with the IP location data:

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

app.get('/location/:ip', (req, res) => {
  const ipLocation = geoip.lookup(req.params.ip);
  if (!ipLocation) {
    return res.status(404).send('Location not found for the given IP.');
  }
  res.json(ipLocation);
});

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

This script sets up a basic server that can receive an IP address as a parameter in the URL and respond with its location. It’s a quick and effective way to integrate IP location services into any Node.js-based application.

Advanced Considerations

While using free APIs or open-source libraries can be straightforward, they come with limitations such as request limits, outdated databases, or lack of precision. For production environments, you might consider a subscription-based service that offers more detailed data, higher limits, and technical support. Ensure the usage complies with user privacy and data protection regulations applicable in your jurisdiction.

Conclusion

Node.js offers multiple pathways for obtaining geolocation information from IP addresses, ranging from free APIs to comprehensive, server-side libraries. Whether your project is small and requires a quick implementation or is a larger application that needs a more robust solution, Node.js has the tools and libraries to support your goals. Efficiently utilizing geolocation data can unlock a myriad of possibilities for enhancing user experiences, tightening security, and offering personalized content.

Next Article: NodeJS: Declaring types when using dotenv with TypeScript

Previous Article: Node.js: How to convert byte arrays to images

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates
  • ExpressJS: How to pass variables to Pug templates