skip to Main Content

I would like to dynamically render a script in next.js depending on the page url. My code in page/app.tsx

        <Head>
          <script
          id="script"
          src="www.cookie.com"
          data-cbid={typeof window !== 'undefined' && window.location.href.includes('localhost') ?
          "XXXXXXXXX" : "YYYYYYYYYY"}
          data-blockingmode="auto"
          type="text/javascript"
          async>
        </script>
      <Head>

However, my problem is that next.js knows too late what domain it is on and always returns me "YYYYYYYYYY" because the condition is always wrong. Is there any way to solve this problem?

2

Answers


  1.  const [isLocalhost, setIsLocalhost] = useState(false);
    
      useEffect(() => {
        setIsLocalhost(window.location.href.includes('localhost'));
      }, []);
    

    after that conditionally render like that :

     <Head>
            <script
              id="script"
              src="www.cookie.com"
              data-cbid={isLocalhost ? "XXXXXXXXX" : "YYYYYYYYYY"}
              data-blockingmode="auto"
              type="text/javascript"
              async
            ></script>
          </Head>
    
    Login or Signup to reply.
  2. You can use the useRouter hook for next.js to use the current url:
    use-router

    Then use the ‘isReady’ parameter to wait for the object to be ready to use client side.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search