skip to Main Content

I need to import a pure javascript script in my next js app like this :

import Script from "next/script";


<Component {...pageProps} />
 <Script
        id="raychat-widget"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
                window.RAYCHAT_TOKEN = "Token";
                (function () {
                    const d = document;
                    const s = d.createElement("script");
                    s.src = "https://widget-react.raychat.io/install/widget.js";
                    s.async = true;
                    d.getElementsByTagName("head")[0].appendChild(s);
                })();`,
        }}
  />

But I get the error :

ReferenceError: d is not defined

error-image

How can I import this pure javascript script in next js ?

2

Answers


  1. Chosen as BEST ANSWER

    I solved the error by removing some other code misplaced in another file, so this code actually works.

    import Script from "next/script";
    
    
    <Component {...pageProps} />
     <Script
            id="raychat-widget"
            strategy="afterInteractive"
            dangerouslySetInnerHTML={{
              __html: `
                    window.RAYCHAT_TOKEN = "Token";
                    (function () {
                        const d = document;
                        const s = d.createElement("script");
                        s.src = "https://widget-react.raychat.io/install/widget.js";
                        s.async = true;
                        d.getElementsByTagName("head")[0].appendChild(s);
                    })();`,
            }}
      />
    

  2. In Next.js, you cannot directly use browser-specific APIs like document because the code runs both on the server and the client, and document is only available on the client side. To execute this script only on the client side, you can use Next.js’s built-in useEffect hook or componentDidMount lifecycle method to ensure that it runs after the component is mounted on the client side.

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