Example CodeFeaturedHow-ToNodejs

How to Check Internet Connection in Node.js: Methods and Examples

3 Mins read
Node.js Internet Checks Made Easy: Code Snippets & Best Practices

Node.js Guide to Detect Internet Connectivity Programmatically

Node.js powers everything from web apps to microservices and IoT systems. One common task developers face is checking internet connectivity to ensure APIs, services, or external resources are reachable. In this article, we’ll explore multiple methods to check internet access in Node.js, covering basic checks to more robust implementations.


Why Check Internet Connection in Node.js?

Detecting internet availability in Node.js can help:

  • Prevent failed API calls due to no connectivity
  • Provide better user experience with offline warnings
  • Schedule retries or fallbacks when the internet is down
  • Log or alert admins for connectivity issues in services

Unlike front-end apps that use browser-based checks, Node.js requires programmatic solutions, often with libraries or direct system calls.


Method 1: Using dns Module to Resolve a Domain

Node.js comes with a built-in dns module that can resolve domain names. If the DNS lookup fails, there’s likely no internet connection.

Example:

javascriptCopyEditconst dns = require('dns');

function checkInternetDNS(callback) {
  dns.lookup('google.com', (err) => {
    if (err && err.code == "ENOTFOUND") {
      callback(false);
    } else {
      callback(true);
    }
  });
}

checkInternetDNS((isConnected) => {
  console.log("Internet Connected:", isConnected);
});

Pros:

  • Lightweight
  • No external requests
  • Built-in module

Cons:

  • DNS may be cached locally
  • Doesn’t check HTTP connectivity

Method 2: Using http or https to Ping a Web Resource

Another reliable approach is to perform a simple HTTP(S) request to a known URL like https://www.google.com.

Example:

javascriptCopyEditconst https = require('https');

function checkInternetHTTP(callback) {
  const req = https.get('https://www.google.com', (res) => {
    callback(true);
  });

  req.on('error', () => {
    callback(false);
  });

  req.setTimeout(5000, () => {
    req.destroy();
    callback(false);
  });
}

checkInternetHTTP((isConnected) => {
  console.log("Internet Connected:", isConnected);
});

Pros:

  • Confirms real internet access
  • Checks both DNS and HTTP connectivity

Cons:

  • Slightly slower (depends on server response)
  • Relies on external domain uptime

Method 3: Using the is-online NPM Package

For a cleaner, abstracted solution, the is-online package is a great choice. It checks multiple factors like DNS, connectivity, and more.

Installation:

bashCopyEditnpm install is-online

Usage:

javascriptCopyEditconst isOnline = require('is-online');

(async () => {
  const online = await isOnline();
  console.log("Internet Connected:", online);
})();

Pros:

  • Very easy to use
  • Actively maintained
  • Checks DNS and network interfaces

Cons:

  • Requires installing external package

Method 4: Using System Commands (e.g., Ping)

You can use Node’s child_process module to run system-level ping commands.

Example (Unix-based systems):

javascriptCopyEditconst { exec } = require('child_process');

function checkInternetPing(callback) {
  exec('ping -c 1 google.com', (error, stdout, stderr) => {
    callback(!error);
  });
}

checkInternetPing((isConnected) => {
  console.log("Internet Connected:", isConnected);
});

Pros:

  • Useful when no internet-dependent packages are allowed
  • Works even with basic environments

Cons:

  • OS-specific (ping -c for Unix, ping -n for Windows)
  • Slower than native methods

Best Practices

1. Avoid Hardcoding IPs

Using domain names (like google.com) ensures DNS is also functioning properly. Hardcoded IPs might give false positives.

2. Use Timeouts

Always set a timeout for network checks to avoid indefinite waiting in slow networks.

3. Retry Logic

If the first check fails, try again after a short delay before concluding a disconnection.

4. Don’t Block the Event Loop

Use asynchronous methods to avoid freezing your application during the check.


Use Case: Retry on Internet Reconnect

Here’s a basic utility that checks every 10 seconds and triggers an action once internet returns:

javascriptCopyEditconst isOnline = require('is-online');

async function waitForInternet() {
  let online = await isOnline();
  while (!online) {
    console.log("Waiting for internet...");
    await new Promise(res => setTimeout(res, 10000));
    online = await isOnline();
  }
  console.log("Internet is back!");
}

waitForInternet();

This can be integrated into applications that depend on internet availability (e.g., download managers, sync tools).


Bonus: Monitor Network Changes in Real-Time (Advanced)

Node.js doesn’t natively support real-time detection of network changes like frontend apps. However, you can create a listener using polling with intervals:

javascriptCopyEditconst isOnline = require('is-online');

let lastStatus = null;

setInterval(async () => {
  const currentStatus = await isOnline();
  if (currentStatus !== lastStatus) {
    console.log(`Internet status changed: ${currentStatus ? 'Online' : 'Offline'}`);
    lastStatus = currentStatus;
  }
}, 5000);

Conclusion

Checking internet connectivity in Node.js can be as simple or as advanced as needed. For lightweight applications, built-in DNS or HTTPS requests are enough. For production-grade applications, using packages like is-online offers reliability and simplicity.

Whether you’re building a CLI tool, backend microservice, or IoT controller, implementing internet checks ensures your app behaves predictably when the network fails.


Summary of Methods:

MethodApproachProsBest For
dns.lookup()Lightweight DNS checkFast, built-inBasic connectivity checks
https.get()Real HTTP requestConfirms full accessRobust online verification
is-onlineNPM packageEasy, smart detectionProduction-level monitoring
pingSystem commandNo external dependencyScript-based automation

Leave a Reply

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