Skip to main content

How to check if there is an active internet connection in Node.js

How to check if there is an active internet connection in Node.js

How to check if there is an active internet connection in Node.js

Although the probabilities that your user does something important on your system, an action that couldn't be easily repeated, exactly on the moment where the internet stops working is pretty low, but it happens. In this moment your user would immediately blame on your system (and more if you didn't designed something to create a temporal backup of the information on the browser). On those cases, it's pretty important to check when there's an active connection before doing something important, just to prevent a bad time.

In this article we'll show you how to check if there's an active internet connection in Node.js using 2 open source modules.

A. Using internetAvailable module

Internet Available is an useful module to verify if there's an active internet connection with Node.js easily. To install this module in your project, execute the following command on your terminal:

npm install internet-available

This module has been written by Our Code World. This library relies on the dns-socket module used to resolve a DNS address from a domain. But, why use an extra module if Node.js already provides a Look Up DNS address method by default? Great question ! You are right, Node.js provides already a method that allow you to achieve this, however it doesn't provide any way to limit the execution time of the script. Therefore, we use this extra module that makes everything easier and it does it really well. For more information check the documentationor visit the official repository at Github here.

To check if there's an available internet connection with this module, you can do it quickly using the following code:

var internetAvailable = require("internet-available");

internetAvailable().then(function(){
    console.log("Internet available");
}).catch(function(){
    console.log("No internet");
});

As you can see it's pretty easy and functional. In case you need to, it can be customized to set a maximum execution time for the verification and a total of attempt that can be made, in case that the task takes more than needed:

var internetAvailable = require("internet-available");

// Set a timeout and a limit of attempts to check for connection
internetAvailable({
    timeout: 4000,
    retries: 10,
}).then(function(){
    console.log("Internet available");
}).catch(function(){
    console.log("No internet");
});

If the timeout period expires, it means that there isn't an available connection.

As previously mentioned, internetAvailable resolves a DNS address from a domain, namely google.com. If you don't want to use this domain for the verification, you can simply change it in the settings. The following example shows how to use the ourcodeworld.com domain instead of the google domain. The host and port can be changed, however we'll use the default ones:

var internetAvailable = require("internet-available");

// Make it with a different verification address
internetAvailable({
    domainName: "ourcodeworld.com",
    port: 53,
    host: '8.8.8.8'
}).then(() => {
    console.log("Internet available");
}).catch(() => {
    console.log("No internet");
});

Alternatively, if there's something special with the domain you want to use, you can change the DNS port of verification and the host address as it uses by default the Google Public DNS.

B. Using isOnline module

isOnline is a module that , unlike internetAvailable, works in Node.js and the browser (with browserify/webpack) and allows you to verify if there's an active internet connection. In the browser you have navigator.onLine, but it's useless as it only tells you if there's a local connection, and not whether the internet is accessible.

To install this module in your project, execute the following command on the terminal:

npm install is-online

This module execute some requests to different free services, all of them run in parallel:

  • Retrieve icanhazip.com via HTTPS
  • Query myip.opendns.com on OpenDNS (Node.js only)
  • Retrieve Apple's Captive Portal test page (Node.js only)

When any of them succeed, the returned Promise is resolved to true and therefore we can deduce that there's an internet connection. For more information about this library, please visit the official repository at Github here.

To check if there's internet with this module, use the following code (in the browser and with Node.js):

const isOnline = require('is-online');
 
isOnline().then(online => {
    if(online){
        console.log("We have internet");
    }else{
        console.log("Houston we have a problem");
    }
});

This library allows you to set a timeout in the same way the previous library does on its options. Besides, you can choose which Internet Protocol version to use. This is an advanced option that is usually not neccessary to be set, but it can prove useful to specifically assert IPv6 connectivity:

const isOnline = require('is-online');
 
isOnline({
    // Break on 5 seconds
    timeout: 5000,
    // v4 or v6
    version: "v4"
}).then(online => {
    if(online){
        console.log("We have internet");
    }else{
        console.log("Houston we have a problem");
    }
});

Happy coding !

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...