How to load script dynamically before any other scripts in nextjs _app.js?

585 Views Asked by At

I have a nextjs project. I want to implement oneTrust CMP solution for my domain. I am required to place oneTrust scripts before any other scripts In the _app.js file and I want to check if the sub-domain is 'X' then I do not want to load the scripts. I have implemented this using useEffect.I have initially set load = true and in useEffect for domain 'X' I have set load = false. In the code I load the sciprts if the load is set to true. But for domain 'X' my scripts are stil loading.

My Code:

function MyApp({ Component, pageProps }) {
   const [load, setLoad] = useState(true);
   useEffect(() => {
    if (window != undefined) {
       // console.log(window.location);
       const paths = window.location.host;
       if (paths.includes("X")) {
         setLoad(false);
       }
     }
   }, []);
  return (
    <Fragment>
      <Head>
        
      </Head>
      {load ? (
        <>
          <Script
            strategy="beforeInteractive"
            src="src"
            type="text/javascript"
            charSet="UTF-8"
            data-domain-script="some-id"
          ></Script>
          <Script
            id="test"
            strategy="beforeInteractive"
            type="text/javascript"
            dangerouslySetInnerHTML={{
              __html: `
           js code
      `,
            }}
          />
        </>
      ) : (
        ""
      )}

      Some other scripts....
      <Component {...pageProps} />
    </Fragment>
  );
}

What am I doing wrong here? and will my oneTrust script execute before other scripts in this manner?

1

There are 1 best solutions below

0
Tapu Das On

For those with the same question, I solved the problem. You can add getInitialProps to your _app.js file and add your host detection code there.

rest of the _app.js code
MyApp.getInitalProps = async(context)=>{
const url = context.ctx.req.headers.host;
// pass the url data to your component
  return { data: url };
}
export default MyApp