Tapu Das
Tapu Das

Reputation: 411

next script does not work inside _document.js file nextjs

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>
 );
}

Upvotes: 6

Views: 4986

Answers (1)

Tapu Das
Tapu Das

Reputation: 411

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).

Upvotes: 3

Related Questions