#client side route interceptors / guards

1 messages · Page 1 of 1 (latest)

viscid beaconBOT
#

Hi @turbid quarry. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, there isn't a direct built-in way to implement client-side route interceptors or guards in Next.js App Router as of version 14.2. However, there are some approaches you can consider to achieve a similar effect for your use case of showing a confirmation modal before leaving a form:

  1. Using the beforeunload event:
    You can use the browser's beforeunload event to show a confirmation dialog when the user attempts to leave the page. This approach is described in the Vercel guide on leave page confirmation dialogs:

    useEffect(() => {
      if (!pending) return;
      function beforeUnload(e: BeforeUnloadEvent) {
        e.preventDefault();
      }
      window.addEventListener('beforeunload', beforeUnload);
      return () => {
        window.removeEventListener('beforeunload', beforeUnload);
      };
    }, [pending]);
    

    This approach will show a browser-native confirmation dialog when the user tries to close the tab or navigate away from the page.

  2. Custom modal with Parallel Routes:
    While not exactly a route guard, you can use Parallel Routes and Intercepting Routes to create a modal-like experience for confirming navigation. This is described in the Next.js documentation on Parallel Routes for modals. However, this approach is more suited for showing modals as part of your application's navigation flow, rather than intercepting all navigation attempts.

It's worth noting that there have been discussions and feature requests related to this functionality:

#
  1. Github Issue: Docs: How to conditionally stop navigation - This issue was closed, but it mentions that router events were removed in version 13 with the "app" directory, and there hasn't been a direct replacement.

  2. Github Issue: Server Action blocks navigation to Parallel / Intercepting Route (Modal) - This discussion touches on the challenges of combining server actions with navigation, which is related to your use case.

Currently, there isn't a built-in solution in Next.js App Router for implementing client-side route guards or interceptors in the way you're describing. You may need to combine the beforeunload event listener with custom state management to achieve the desired behavior of showing a modal before leaving a form.

If you need more advanced routing control, you might have to consider using a third-party routing solution or wait for potential future updates to Next.js that may address this use case.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: