Real-time network connectivity detection for modern web applications
A lightweight, reliable solution for monitoring network connectivity in your applications
Instantly detect network changes with event-driven monitoring
Built with TypeScript for better developer experience and type safety
Minimal footprint with minimal dependencies for optimal performance
npm install offline-detector
Simple setup with default configuration
import { createOfflineDetector } from 'offline-detector';
const detector = createOfflineDetector({
onOnline: () => console.log('Back online!'),
onOffline: () => console.log('Gone offline!')
});
detector.start();
Custom network verification, debouncing, and native events
import { createOfflineDetector } from 'offline-detector';
const detector = createOfflineDetector({
onOnline: () => {
// Sync pending data
},
onOffline: () => {
// Show offline indicator
},
stateChangeDebounceDelay: 1000,
networkVerification: {
enabled: true,
url: 'https://api.example.com/health',
requestTimeout: 5000,
interval: 30000,
maxFailures: 3
},
nativeEvents: {
enabled: true
}
});
detector.start();
Custom hook for React applications with automatic cleanup
import { useEffect, useState } from 'react';
import { createOfflineDetector } from 'offline-detector';
function useOfflineDetector() {
const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
const detector = createOfflineDetector({
onOnline: () => setIsOnline(true),
onOffline: () => setIsOnline(false),
networkVerification: {
enabled: true,
interval: 5000,
maxFailures: 2
}
});
detector.start();
setIsOnline(detector.isOnline());
return () => detector.destroy();
}, []);
return isOnline;
}
// Usage in component
function App() {
const isOnline = useOfflineDetector();
return (
<div>
<h1>My App</h1>
{!isOnline && (
<div className="offline-banner">
You're currently offline
</div>
)}
</div>
);
}