Next.js Discord

Discord Forum

UseRouter and Retriving cookies in Next.js

Unanswered
African Slender-snouted Crocodil… posted this in #help-forum
Open in Discord
Avatar
African Slender-snouted CrocodileOP
Just got into some issues, the company that I work one, wanted a simple single page website, and since I was interested into starting Next.js I've made the app using Next.js, but I started getting into some issues
Using router from useRouter and then using router.push, it force a fully reload page not like useNavigate from React this issue forced me to create the whole app within a single page ( Page.tsx ) and using component to form Page.tsx which was not that bad because it was a SIMPLE app, it's still pretty clean and fine. but still, can I useRouter to not fully reload the page like in React useNavigate?
And the issue came when I had to connect the app to Facebook pixel and tiktok pixel to retrieve some data from cookie and I had to useEffect to retrieve the cookie, I wonder is there a way to do the following inside Next.js without client ?

1 Reply

Avatar
African Slender-snouted CrocodileOP
 
useEffect(() => {
    function getTikTokClickId(): string | null {
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get('ttclid');
    }
    function getFacebookClickId(): string | undefined {
      const urlParams = new URLSearchParams(window.location.search);
      const fbclid = urlParams.get('fbclid');
      if (fbclid) {
        // If fbclid is available, format the fbc parameter
        const version = 'fb';
        const subdomainIndex = 2;
        const creationTime = Math.floor(Date.now() / 1000);
        return `${version}.${subdomainIndex}.${creationTime}.${fbclid}`;
      }
    }
    const ttclid = getCookie('ttclid') || getTikTokClickId();
    const fbclid = getCookie('_fbc') || getFacebookClickId();
    setFbclid(fbclid);
    setTtclid(ttclid);
    // Setting CampaignData
    setDataToBeSent((prevData: any) => ({
      ...prevData,
      campaign: {
        fbclid: fbclid || 'No provided fbclid',
        ttclid: ttclid || 'No provided ttclid',
        provider: searchParams.utm_source || 'No source provided',
        name: decodeURIComponent(
          searchParams.utm_campaign || 'No campaign name provided'
        ).replace(/{{|}}/g, ''),
        aid: decodeURIComponent(searchParams.aid || 'No aid provided').replace(
          /{{|}}/g,
          ''
        ),
      },
    }));
  }, []);