How to detect referring page url in nextjs

917 Views Asked by At

In a page, I redirect user to an external link using router.push('destination-url').

I need to check if the user has clicked back from the page that I already redirected them to or not. If the user is coming form an external link, they must not visit this page again (preventing duplicate redirect to the same destination).

In other words: I need to redirect the user to an external link only if they came from an specific internal page.

useEffect(() => {
  if (window) {
    if (router.isReady) {

      // --- HERE I NEED TO CHECK IF USER CLICKED BACK FROM THE EXTERNAL URL THAT I ALREADY REDIRECTED THEM TO ---

      getLinkAddress({id: router.query.id, price: router.query.price}).then((r1) => {
        if (r1.link_address) {
          setFound(true);
          router.push(r1.link_address).then();
        } else {
          setFound(false);

          setTimeout(() => {
            router.back();
          }, 3000);
        }
      });
    }
  }

  return () => { };
}, [router.query]);
1

There are 1 best solutions below

0
Baki On

You can maybe try this:

useEffect(() => {
  if (window && router.isReady) {

    const redirectedFlag = sessionStorage.getItem('redirectedFlag');

    if (!redirectedFlag) {

      getLinkAddress({ id: router.query.id, price: router.query.price }).then((r1) => {
        if (r1.link_address) {
          setFound(true);

          sessionStorage.setItem('redirectedFlag', 'true');

          router.push(r1.link_address).then();
        } else {
          setFound(false);

          setTimeout(() => {
            router.back();
          }, 3000);
        }
      });

    } else {
      console.log("User is coming back from the external link");
    }
  }

  return () => { };
}, [router.query]);