DEV Community

Cover image for Lessons from opensource: How to check if your program has internet connectivity in Nodejs?
Ramu Narasinga
Ramu Narasinga

Posted on • Edited on

Lessons from opensource: How to check if your program has internet connectivity in Nodejs?

These lessons are picked from next.js/create-next-app open source code. In this article, you will learn how you could check if your program has access to internet in Nodejs.

https://github.com/vercel/next.js/blob/canary/packages/create-next-app/helpers/is-online.ts#L18

There could be numerous reasons as to why you want to check if you program has internet connectivity. One usecase in next.js/create-next-app is that the program checks it's online to install a npm command.

Install

export async function getOnline(): Promise<boolean> {
  try {
    await dns.lookup('registry.yarnpkg.com')
    // If DNS lookup succeeds, we are online
    return true
  } catch {
    // The DNS lookup failed, but we are still fine as long as a proxy has been set
    const proxy = getProxy()
    if (!proxy) {
      return false
    }

    const { hostname } = url.parse(proxy)
    if (!hostname) {
      // Invalid proxy URL
      return false
    }

    try {
      await dns.lookup(hostname)
      // If DNS lookup succeeds for the proxy server, we are online
      return true
    } catch {
      // The DNS lookup for the proxy server also failed, so we are offline
      return false
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Subscribe to my newsletter to get more lessons from opensource.

DNS package?

At the top of is-online.ts file, you will find below snippet:

import dns from 'dns/promises'
Enter fullscreen mode Exit fullscreen mode

he node:dns module enables name resolution. For example, use it to look up IP addresses of host names.

Although named for the Domain Name System (DNS), it does not always use the DNS protocol for lookups. dns.lookup() uses the operating system facilities to perform name resolution. It may not need to perform any network communication. To perform name resolution the way other applications on the same system do, use dns.lookup(). - Source

Conclusion:

A simple DNS lookup is used to detect if you are online when you run your NodeJs program. Now you know how to check if you got internet connectivity before you do some operations programatically and throw some error if you are offline.

If you are looking to improve/learn frontend, checkout my website: https://tthroo.com/ where I teach project based tutorials.

Get free courses inspired by the best practices used in open source.

About me:

Website: https://ramunarasinga.com/

Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/

Github: https://github.com/Ramu-Narasinga

Email: ramu.narasinga@gmail.com

Learn the best practices used in open source.

Top comments (0)