blog
contact
hire me

Next.js Loads script tags but it doesnt execute them

nextjs

Had another question on my website today about Next.js and custom scripts. This one bothered me a while ago too and I had a similar hack to the dev reaching out.

I had placed an “Immediately Invoked Function” inside a useEffect on my _app.js page.

Don’t Do This

useEffect(() => {
  var Tawk_API = Tawk_API || {},
    Tawk_LoadStart = new Date();
  (function () {
    var s1 = document.createElement("script"),
      s0 = document.getElementsByTagName("script")[0];
    s1.async = true;
    s1.src = "https://embed.tawk.to/60...";
    s1.charset = "UTF-8";
    s1.setAttribute("crossorigin", "*");
    s0.parentNode.insertBefore(s1, s0);
  })();
}, []);

This was to have a chatbox on my, on every page.

Placing the code inside the Head module that’s built into Next now produces an error and provides a solution by using the Script module…which is also built-in.

This makes life a lot simpler. We can now create a separate file, paste our 3rd party script and link to it using the Script module.

Do This

pages/
public/
├─ chatbot/
│ ├─ script.js

Then using this script across the entire app

import Script from "next/script";

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Script type="text/javascript" src="/chatbot/script.js" />
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;