Track Online Status & Connection Quality with JavaScript – Network Monitor

Category: Javascript | August 13, 2025
AuthorMadeByRaymond
Last UpdateAugust 13, 2025
LicenseApache-2.0
Tags
Views103 views
Track Online Status & Connection Quality with JavaScript – Network Monitor

network-monitor-js is a lightweight JavaScript utility that helps you monitor a user’s internet connection status.

This library tracks online/offline status, measures ping latency, identifies network types (2G through 5G), and detects poor connection conditions.

It goes beyond the browser’s basic navigator.onLine to provide a more realistic picture of the user’s connectivity.

This helps you build more resilient web experiences, like disabling a “Save” button when a user is offline or deferring large asset downloads on a slow connection.

Key Features:

  • Detects if the user is truly online or offline.
  • Measures round-trip network latency with a periodic ping.
  • Identifies the effective network type, such as 5g, 4g, or slow-2g.
  • Flags connections it deems “poor” based on type and latency.
  • Emits status updates whenever connectivity changes.
  • Contains no dependencies and has a minimal footprint (~1KB gzipped).

How to use it:

1. Install network-monitor-js and import it into your project.

# NPM
$ npm install network-monitor-js
import { NetworkMonitor } from 'network-monitor-js';

2. Or directly load the JavaScript from a CDN into your document:

<script src="https://unpkg.com/network-monitor-js"></script>

3. Initialize the monitor and subscribe to its updates. You need to place a lightweight file at /ping.txt in your application’s public directory. This file can be empty. The library requests this file to measure latency.

Available status properties:

  • online (boolean): Current online/offline status
  • latency (number|null): Ping latency in milliseconds
  • effectiveType (string): Network type (‘5g’, ‘4g’, ‘3g’, ‘slow-2g’)
  • poorConnection (boolean): True if connection is poor quality
const monitor = new NetworkMonitor();
monitor.subscribe(status => {
  document.getElementById('test-id').innerHTML = `
    <p>Online: ${status.online}</p>
    <p>Latency: ${status.latency}ms</p>
    <p>Type: ${status.effectiveType || 'unknown'}</p>
    <p>Poor Connection: ${status.poorConnection}</p>
  `;
});

4. All available options:

  • Ping URL: A configurable URL used to check network connectivity. Defaults to /ping.txt and is not required.
  • Latency Threshold: The time in milliseconds that defines a “slow” connection. The default is 1800 ms, but can be changed.
  • Slow Connection Types: A list of connection types (like ‘2g’ or ‘3g’) that are flagged as slow. This list can be modified.
  • Ping Interval (Supported API): The time in milliseconds between pings for browsers that support the Network Information API. The default is 60 seconds.
  • Fallback Ping Interval (Unsupported API): The ping frequency for browsers that lack support for the Network Information API, such as Safari or Firefox. The default is 10 seconds.
const monitor = new NetworkMonitor({
  pingUrl: "/ping.txt",
  latencyThreshold: 1800,
  slowConnectionTypes: ['2g', 'slow-2g', '3g'],
  pingIntervalMs: t60000,
  fallbackPingIntervalMs: 10000
});

5. More API methods:

  • subscribe(callback): Registers a function to call with the NetworkStatus object whenever the connection state changes.
  • runManualCheck(callback?): Triggers an immediate check instead of waiting for the next interval. It accepts an optional callback that receives the new status.
  • status: A property that returns the last known NetworkStatus object snapshot without triggering a new check.

FAQs

How is this better than just using navigator.onLine?
navigator.onLine only tells you if the device is connected to a network (like a LAN or router), not if that network can reach the internet. This library confirms connectivity by actually making a web request, which is a much more reliable signal.

Can I use this in Node.js?
No. This is a client-side library that depends on browser-specific APIs like navigator, window, and fetch.

Q: What happens if my ping endpoint is unreachable?
A: The library will mark the connection as offline and continue monitoring. I recommend using a reliable endpoint or implementing a fallback ping URL for production applications.

Q: Can I use this library with service workers?
A: Yes, but you’ll need to handle the ping requests within the service worker context. The library works best in the main thread where it can access the Navigator Connection API.

Changelog:

v1.0.15 (08/13/2025)

  • Detects online/offline status
  • Measures latency via periodic ping
  • Tracks network type (e.g. 4g, 3g, 2g, slow-2g)
  • Flags poor network connections
  • Emits changes when network status updates
  • No dependencies, small footprint (~10KB gzipped)
  • Fully configurable via NetworkMonitorConfig

You Might Be Interested In:


Leave a Reply