I have a React app https://codesandbox.io/p/sandbox/q6l8jp that uses the react-use-is-online npm package to check online and offline status. The package works perfectly, displaying appropriate messages for online and offline states. However, when I try to reload my browser while offline, my app fails to render and shows the browser’s default "no internet" page instead.
I would like to load my app and display a custom error message even when there is no internet connection. For example, YouTube continues to render its app even when offline. How can I achieve this?
2
Answers
I resolved this issue using a service worker and PWA setup. This allows the app to display a custom offline message, even when the browser is refreshed without an internet connection. Here's how it works:
Service Worker & PWA:
The service worker caches essential files and a custom offline page, so it can serve this content when the user is offline. Note that service workers only function in production build environments, so this may not work during local development.
Error Handling:
Implement an error boundary to catch JavaScript errors and display a fallback UI. Ensure all critical resources and the custom offline page are cached. Otherwise, if the requested page isn't cached, the default "no internet" page will still appear.
Result: With this setup, the app displays a custom offline message instead of the browser's default offline page, similar to how YouTube handles offline scenarios.
enter image description here
[1]: https://i.sstatic.net/AJPlEDe8.png
I tried to load https://www.youtube.com/ in an offline state, and saw that it was a static resource returned via service worker, which means that offline caching was done, I guess, to give the user a better experience, which should belong to the pwa level.
Your website is able to display customized information during normal use with the network turned off, because the required resources have already been downloaded and the logic is executing normally.
If you try to refresh your website with the network closed, and request resources without offline caching and disconnected from the network, it’s impossible to request any content, let alone execute your judgment logic!