6

I have a nextjs project. I want to load two scripts using next/script inside _document.js.But when I place the Script tags into the body tag in _document.js, my scripts do not execute. I implemented according to the next/script guideline.What may be the issue here?

My code:

import { Html, Head, Main, NextScript } from "next/document";
import Script from "next/script";
export default function Document() {
 return (
   <Html>
     <Head>
       <link rel="preconnect" href="https://fonts.googleapis.com" />        
     </Head>
     <body>
       <Main />
       <NextScript />
         <Script
         strategy="beforeInteractive"
         src="src"
         type="text/javascript"
         charSet="UTF-8"
         data-domain-script="id"
       />
       <Script
         strategy="beforeInteractive"
         type="text/javascript"
         dangerouslySetInnerHTML={{
           __html: `
           some js code
     `,
         }}
       />
     </body>
   </Html>
 );
}

3
  • What Next.js version are you on? Commented Sep 30, 2022 at 8:07
  • I'm having same issue. Their example from the website doesnt even work. Commented Oct 19, 2022 at 18:53
  • You can use next/script in _app.js instead of _document.js now. See my answer below. Commented Nov 2, 2022 at 6:13

1 Answer 1

3

Initially in next/script api reference section, it was documented to use Script tags in _document.js with beforeInteractive strategy. But now their api reference has been updated and you must use Script tag with beforeInteractive strategy in pages/_app.js.

API Reference Link

Quote from next/script api reference

beforeInteractive scripts must be placed inside pages/_app.js and are designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side).

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like they changed the requirements again, so now you need to move beforeInteractive scripts back to pages/_document: nextjs.org/docs/api-reference/next/script#beforeinteractive

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.