How do you detect if the user is online or offline?
The browser exposes network status through the Navigator API and events.
navigator.onLine — a boolean for the current state.
online / offline events — fire on window when connectivity changes.
Caveat: onLine only means a network connection exists, not that the internet (or your server) is actually reachable.
// Check current status
console.log(navigator.onLine); // true or false
// Listen for changes
window.addEventListener('online', () => {
console.log('Back online!');
syncPendingData(); // Sync queued offline actions
});
window.addEventListener('offline', () => {
console.log('Gone offline');
showOfflineBanner();
});
// Reliable check: ping your server
async function isReallyOnline() {
try {
const response = await fetch('/api/health', {
method: 'HEAD',
cache: 'no-cache'
});
return response.ok;
} catch {
return false;
}
}navigator.onLine gives the current status. Event listeners react to changes.
The fetch-based check verifies actual server connectivity (navigator.onLine may report 'online' when connected to WiFi with no internet). The HEAD request is lightweight (no body).
navigator.onLine for basic check, events for reactive updates. Know the limitation: onLine means 'network connected' not 'internet accessible.' The server ping for reliable detection shows production awareness.