jpk
jpk

Reputation: 510

NextJs - External synchronous scripts are forbidden

I am using nextJs version 11.x

When trying to include an external script like below, getting an error when executing the yarn build.

<Head>
<link rel="stylesheet" type="text/css" href="http://www.externalsite.com/style.css" />
<script src="https://www.websote.com/viewer.min.js"></script>
</Head>

Error :

./pages/_app.js
63:17  Error: External synchronous scripts are forbidden. See: https://nextjs.org/docs/messages/no-sync-scripts.  @next/next/no-sync-scripts

I am using eslint.

So, how can we include this external js ?

Upvotes: 13

Views: 17860

Answers (5)

Mahadi Hassan
Mahadi Hassan

Reputation: 1016

For nextjs, Instead of using use imported from next/script.

An example is given below :

import Script from 'next/script';

Use async or defer

<Script src="https://third-party-script.js" async />
<Script src="https://third-party-script.js" defer />

Upvotes: 1

tenhill
tenhill

Reputation: 136

Modify ESLint configuration file, disable the no-sync-scripts rule mentioned by the error message works.

{
  "extends": "next/core-web-vitals",
  "rules": {
    "@next/next/no-sync-scripts": "off"
  }
}

Upvotes: 5

Yilmaz
Yilmaz

Reputation: 49293

If you are using <script></script> inside _document.js use async or defer keyword

        <script
            defer
            src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
            integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
            crossOrigin="anonymous"
       ></script>

          <script
            async
            src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
            integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
            crossOrigin="anonymous"
          ></script>

If in your component, use this

import Script from 'next/script'

Upvotes: 3

jpk
jpk

Reputation: 510

Resolved the problem.

It was happening because of eslint strict configuration. Now I changed this to Base.

Modified content in this file .eslintrc

Earlier the value was

   {
   "extends": "next/core-web-vitals"
   }

Now changed the content to

 {
 "extends": "next"
 }

Thanks for the Help

Upvotes: 20

Vladick Kapkan
Vladick Kapkan

Reputation: 129

import Script from 'next/script'

const Home = () => {
    return (
      <div class="container">
        <Script src="https://third-party-script.js"></Script>
        <div>Home Page</div>
      </div>
    )
}

export default Home

Upvotes: 12

Related Questions