network-monitor-js
v1.1.5
Published
A lightweight JS utility to monitor internet connectivity, online/offline, connection quality (2G/3G/4G/5G), ping latency and detect poor network conditions.
Downloads
678
Maintainers
Readme
network-monitor-js
🛰️ A lightweight JS utility to monitor internet connectivity, online/offline, connection quality (2G/3G/4G/5G), ping latency and detect poor network conditions.
✨ Features
- ✅ 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
- 🔧 Fully configurable via
NetworkMonitorConfig - 🪶 No dependencies, small footprint (~10KB gzipped)
📦 Install
NPM
npm install network-monitor-jsCDN
<script src="https://unpkg.com/network-monitor-js"></script>
<script>
const monitor = new NetworkMonitor();
monitor.subscribe(status => console.log(status));
</script>🔧 Setup
By default, the service pings /ping.txt every few seconds (depending on browser connection support). You can customize the ping URL to a different static file, endpoint or url:
import { NetworkMonitor } from 'network-monitor-js';
const monitor = new NetworkMonitor({
// Optional configurations:
pingUrl: '/your-api/ping',
poorConnectionLatency: 1800, // ms
// ...other configuration settings
});Additional Configurations:
Additional configuration settings can be provided to customize how network connection is monitored:
| Property | Description | Required? | Default |
| ----------------------------- | ----------- | -------- | ------- |
| pingUrl | The URL to ping when checking connectivity. This should point to a small, cacheable file (e.g. a static file, endpoint or url) | optional | /ping.txt |
| latencyThreshold | The latency threshold (in milliseconds) above which the connection is considered "slow" | optional | 1800 ms |
| slowConnectionTypes | List of effectiveType values that should be treated as slow connections | optional | ['slow-2g', '2g', '3g'] |
| pingIntervalMs | Default ping interval (in milliseconds) when the browser supports Network Information API | optional | 60000 (60 seconds) |
| fallbackPingIntervalMs | Default ping interval (in milliseconds) when the browser does NOT support Network Information API. As a result, this should ping much more frequently than pingIntervalMs. Many browsers E.g: Firefox, Safari, IE, etc and devices E.g: macOS, iOS, etc, will fallback to this as Network Information API is typically not supported on them | optional | 10000 (10 seconds) |
✅ Requirements for Ping Endpoint
Make sure your ping endpoint, url or file:
- Returns a
200or204response - Supports CORS (if it's on a different domain)
- Responds quickly
📚 Usage
import { NetworkMonitor } from 'network-monitor-js';
const monitor = new NetworkMonitor();
monitor.subscribe(status => {
console.log('Online:', status.online);
console.log('Latency:', status.latency);
console.log('Effective Type:', status.effectiveType);
console.log('Poor Connection:', status.poorConnection);
});🛠 API
new NetworkMonitor(config?: NetworkMonitorConfig)
config: (optional) Configuration settings to customize how the service detects poor or slow networks
subscribe(callback: (status: NetworkStatus) => void)
- Subscribes to real-time status updates
runManualCheck(callback?: (status: NetworkStatus) => void)
- Manually trigger a ping + status refresh and accepts an optional callback which returns the new status
status: NetworkStatus
- Returns the current status snapshot
📁 Assets (for default setup)
Ensure this file exists in your app as a static file if using the default ping path:
/ping.txtIf you prefer to ping a different static file / endpoint / url, you can change the default value as mentioned in the "📚 Usage" section:
const monitor = new NetworkMonitor({ pingUrl: '/your-api/ping' });🧠 Example UI
<div id="status-box"></div>
<script>
const monitor = new NetworkMonitor();
monitor.subscribe(status => {
document.getElementById('status-box').innerHTML = `
<p>✅ Online: ${status.online}</p>
<p>⏱️ Latency: ${status.latency ?? 'N/A'}ms</p>
<p>📶 Type: ${status.effectiveType ?? 'unknown'}</p>
<p>⚠️ Poor Connection: ${status.poorConnection}</p>
`;
});
</script>🧪 Development
# Run tests
npm run test🔒 License
Apache-2.0 © MadeByRaymond (Daniel Obiekwe)
❤️ Support
If you find this package helpful, you can support our projects here:
