Next 11 and adding Script tags not working. No scripts are rendered

Viewed 8466

I added my google tag manager to _app.js file, and its not showing. None of the scripts I am loading via the new "Script" tag are working.

  <Head>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
    <Script
      src={`https://cdn.somelink.coom/${process.env.COOKIE_KEY}/block.js`}
      strategy="beforeInteractive"
    />
    <Script
      src="https://cdn.somelink.com/scripttemplates/stub.js"
      strategy="beforeInteractive"
    />
    <Script
      src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GOOGLE_KEY}`}
      strategy="afterInteractive"
    />

These are not working. Nothing is downloaded in the network tab etc. Nothing shows up on the page. Any thoughts?

Reminder: this is in the _app.js file.

Note: My pages are static generated.

2 Answers

next/script should not be wrapped in next/head

Ref.: Script Component

Do something like this:

import Script from "next/script";

const App = ({ Component, pageProps }) => (
  <>
    <Script
      id="scriptAfterInteractive"
      src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
    />
    {/* eslint-disable-next-line react/jsx-props-no-​spreading */}
    <Component {...pageProps} />
  </>
);

export default App;

In addition to the requirement that Script (next/script) not be wrapped in Head (next/head), I think it should also not be a child of Body within a custom _document.tsx if you are not passing strategy="beforeInteractive" as mentioned in the docs.

I was unable to load a Cloudflare analytics script when placing it within Body in _document.tsx, but it loaded successfully as a sibling to Component in _app.tsx.

Related