How to detect an active internet connection in JavaScript apps?
Tags: javascript, react, internet, api
Published: 2023-06-28 17:51:09

**Introduction**
In today's interconnected world, understanding and adapting to the network connectivity status of web browsers are vital for delivering optimal user experiences. This article explores two key features that facilitate this process: the property [Navigator.onLine](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine) and [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API). By leveraging these capabilities, web developers can make informed decisions, dynamically adjust content delivery, and provide real-time feedback to users based on their network connectivity.

**Navigator.onLine Property: Checking Browser Connectivity**
The Navigator.onLine property serves as a convenient method to determine the online status of a web browser. This property returns a boolean value, where true indicates that the browser is online, and false indicates that it is offline. Updates to the onLine property occur whenever the browser's ability to connect to the network changes. For instance, if a user follows links or a script requests a remote page, the onLine property will accurately reflect the corresponding status.
It's important to note that different browsers may implement this property differently, resulting in varying behavior and potential false positives or false negatives. 

**Network Information API: Enhanced Connectivity Insights**
> Check [mdn web docs](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) for browser compatibility

To gain deeper insights into the user's network connection, developers can utilize the Network Information API in conjunction with the onLine property. The Network Information API provides information about the system's connection, including general connection types such as 'wifi', 'cellular', and more. Accessing this API through the Navigator.connection property allows developers to obtain detailed information about the connection type and tailor their applications accordingly.
For instance, by combining the onLine property with the Network Information API, developers can dynamically adjust content delivery based on the user's connection capabilities. They can selectively preload resources for faster connections, deliver low-definition content for slower connections, or provide offline-friendly interfaces when the browser is offline.

**Listening for Network State Changes**
In addition to retrieving the current online status, developers can monitor changes in the network state by listening to the online and offline events. These events are triggered when the browser's connectivity status changes. By subscribing to these events, developers can execute specific actions or update the user interface based on the browser's online or offline status.

**Implementing Real-Time Network State Updates**

```
// Check you are online or not
if (navigator.onLine) {
  console.log("online");
} else {
  console.log("offline");
}

// To see changes in the network state, use addEventListener
window.addEventListener("offline", (e) => {
  console.log("offline");
});

window.addEventListener("online", (e) => {
  console.log("online");
});

```

_If you have a React app you can use this hook._

> `navigator.connection` maybe does not work on your browser check [mdn web docs](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) for browser compatibility

```
import { useEffect, useState } from "react";

const useNetworkInformation = () => {
  const [networkState, setNetworkState] = useState({
    isOnline: navigator.onLine,
    effectiveType: "",
    downlink: 0,
    rtt: 0,
  });

  useEffect(() => {
    const updateNetState = () => {
      const connection = navigator.connection;
      if (connection) {
        setNetworkState({
          isOnline: navigator.onLine,
          effectiveType: connection.effectiveType,
          downlink: connection.downlink,
          rtt: connection.rtt,
        });
      }
    };
    window.addEventListener("load", updateNetState);
    window.addEventListener("online", updateNetState);
    window.addEventListener("offline", updateNetState);

    return () => {
      window.removeEventListener("load", updateNetState);
      window.removeEventListener("online", updateNetState);
      window.removeEventListener("offline", updateNetState);
    };
  }, []);

  return networkState;
};

export default useNetworkInformation;
```

**Conclusion**
Understanding and adapting to the network connectivity status of web browsers are paramount for delivering optimal user experiences. The Navigator.onLine property provides a straightforward approach to determine the browser's online or offline status, although careful consideration is required due to browser-specific behaviors. To gain deeper insights and tailor content delivery based on connection types, developers can leverage the Network Information API through the Navigator.connection property. By combining these features and listening for network state changes, developers can create dynamic and responsive applications that provide an exceptional browsing experience across diverse network environments.