Detect ISP in Node.js

In this tutorial, I am going to show you how to detect ISP (Internet Service Provider) in Node.js.

To achieve this task, I am going to use the axios module to send a request to the IPinfo API. The IPinfo API returns several details like ISP information, IP address, hostname, location etc in JSON formatted data. But in this tutorial, we are only going to retrieve the ISP and print it in the console.

Let’s first install the Axios module via the npm:

npm install axios

Now below is our simple JavaScript code for Node.js:

const axios = require('axios');

async function checkISP() {
    const response = await axios.get('https://ipinfo.io');
    const data = response.data;
    console.log(`ISP is: ${data.org}`);
}

checkISP();

In the above program, we first created a constant axios and load the axios module. Inside the async function, we have requested the API call to the URL https://ipinfo.io.

Next, I store the returned data in the constant data and then print the org object from the data which is the ISP or Internet Service Provider.

Error handling

The above code doesn’t have an error-handling system. But suppose the IPinfo API URL doesn’t work at the moment. In that situation, you would like to handle the error by using try...catch statement as shown in the example below:

const axios = require('axios');

async function checkISP() {
  try {
    // Get request to IPinfo API
    const response = await axios.get('https://ipinfo.io');

    // Parse from JSON returned data
    const data = response.data;
    console.log(`ISP is: ${data.org}`);
  } catch (error) {
    console.error('Error while fetching the ISP information:', error.message);
  }
}

checkISP();

Now if the API doesn’t work for a specific moment, in that time the error will be handled properly and a proper message will be shown in the console.

2 responses to “Detect ISP in Node.js”

  1. Takeshi Nairo says:

    Do you have any node.js example for ip2location.io?

  2. Faruque Ahamed Mollick says:

    Currently not, but I am going to write a tutorial on detecting location using the ip2location API.

Leave a Reply

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