Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isOnline

Checks if the browser is currently online.

TypeScript
Copied!
1/**
2 * Checks if the browser is currently online.
3 *
4 * @returns True if online, false otherwise.
5 */
6export function isOnline(): boolean {
7  return typeof navigator !== 'undefined' && navigator.onLine;
8}
  • Simple and Lightweight

    Provides a minimal and direct check with no dependencies or overhead.

  • Cross-Browser Support

    Relies on the widely supported navigator.onLine property available in most modern browsers.

  • Safe Environment Guard

    Includes a check for navigator to ensure it doesn't throw in non-browser or SSR contexts.

Tests | Examples

TypeScript
Copied!
1test('isOnline - returns true when navigator.onLine is true', () => {
2  Object.defineProperty(navigator, 'onLine', {
3    configurable: true,
4    get: () => true,
5  });
6  expect(isOnline()).toBe(true);
7});
8
9test('isOnline - returns false when navigator.onLine is false', () => {
10  Object.defineProperty(navigator, 'onLine', {
11    configurable: true,
12    get: () => false,
13  });
14  expect(isOnline()).toBe(false);
15});

Common Use Cases

  • Conditional Network Requests

    Skip API calls or display warnings when the device is offline.

  • Offline-First Applications

    Detect connectivity to trigger data sync or fallback to local storage.

  • Real-Time Status Indicators

    Show users their current online/offline status with UI indicators.

  • Form Submission Guard

    Prevent users from submitting forms when no connection is available.

Codebase: Utilities -> Network -> isOnline | Yevhen Klymentiev