---
title: "Knowing when the user goes offline"
description: "navigator.onLine plus the online and offline events give you reactive connectivity in a few lines. Here's a status pill and a slide-in toast built on them, with the one caveat worth knowing."
date: "2026-05-29"
tags: ["javascript", "web-api", "network", "frontend"]
---

A nice touch in any app that saves or syncs: tell people the moment they drop
offline, and again when they come back. [Bilal Hussain](https://x.com/BilliCodes/status/1838447290891055172)
showed how little it takes. Tap the button to see it (the toast slides in
bottom-right):

## The whole API

`navigator.onLine` is a boolean you can read whenever you want, and the window
fires `online` and `offline` events when it changes. Read once, subscribe to
both, done:

```ts
let online = navigator.onLine;

window.addEventListener("online", () => setOnline(true));
window.addEventListener("offline", () => setOnline(false));
```

In React that's a tiny hook: set state from `navigator.onLine` on mount, update
it from the two events, and clean up the listeners. From there a pill shows the
current state and a toast slides in whenever it flips, then dismisses itself
after a few seconds.

## The caveat

`onLine` tells you the device has a network interface that's up, not that the
internet is actually reachable. Sit behind a captive wifi portal, or have a
router with no upstream, and it'll happily report `true` while nothing loads.

So use it for what it's good at: the obvious, instant cases like airplane mode
or a pulled cable. When you genuinely need to know the server is reachable,
back it up with a real request (a small fetch to your API, retried with
backoff). `onLine` is the cheap first signal, not the final word.

Inspired by [Bilal Hussain](https://x.com/BilliCodes/status/1838447290891055172).
Grab the component on the [Network Status](/components/network-status) page.
