javascriptreactjsgoogle-chromenext.jswebapi

How to handle errors coming from nextjs's router.refresh?


I'm having a page that getting refreshed every few seconds using router refresh

    const router = useRouter()

    ...

    useEffect(() => {
        interval = setInterval(() => {
            router.refresh()
        }, REFRESH_RATE_MIL)
        return () => {
            clearInterval(interval)
        }
    }, []);

The problem is, when the machine is entering to hydration (sleep mode or closing the screen and wait a few minutes) The app crashes with net::ERR_NETWORK_IO_SUSPENDED, causing the whole application to crash.

I'm using Mac Ventura 13 and Chrome Version 127.0.6533.72 (arm64)

I tried few things to solve it:

  1. Add user idle detection to clear the interval - that doesn't solve the case when you close the lid (screen) of the machine.
  2. catch the router refresh using try catch clauses
  3. read the nextjs docs and the router.refresh (" Refresh the current page. refresh(): void;") to try to figure out if there is any option/callback I can use to catch it.
  4. Searched MDN and googled if there is any way to detect the ERR_NETWORK_IO_SUSPENDED ( and then prevent the router.refresh trigger)
  5. searched next issues for issues related to 'router.refresh error handling' or ERR_NETWORK_IO_SUSPENDED
  6. looked stackoverflow for related questions. I found this old one

** I want to use the router refresh because of the caching ability and the fact that it preserves the component's state

Any ideas of how to address this?


Solution

  • If I understand your question, I believe that a combination of document.visibilityState and navigator.onLine may be able to help you here.

    if (navigator.onLine  && document.visibilityState === 'visible')
    

    Something similar to this around the router.refresh() will ensure that both possible things that could be causing the issues are checked for and the refresh hopefully does not cause a crash.