Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

next/script in _app.js creates duplicate script tags in document after moving between pages #26860

Closed
williamtetlow opened this issue Jul 2, 2021 · 11 comments · Fixed by #27218
Labels
bug Issue was opened via the bug report template.

Comments

@williamtetlow
Copy link

What version of Next.js are you using?

11.0.1

What version of Node.js are you using?

16.1.0

What browser are you using?

Chrome, Safari

What operating system are you using?

macOS

How are you deploying your application?

next export

Describe the Bug

When I add inline script tags to _app.js they are then added to the document and ran multiple times when navigating between pages.

This is causing problems with GTM as it's throwing errors that it has already been registered.

Expected Behavior

There should only be one script tag in the document per next/script and it should run once instead of every time navigation occurs.

To Reproduce

https://github.com/williamtetlow/nextjs-multiple-script-tags

  1. Start app
  2. Click link through to page
  3. Click link back to index
  4. See in console that scripts using next/script are ran multiple times
  5. See in HTML there are duplicate script tags with same content

Screenshot 2021-07-02 at 10 08 47

Screenshot 2021-07-02 at 10 07 15

@williamtetlow williamtetlow added the bug Issue was opened via the bug report template. label Jul 2, 2021
@awareness481
Copy link
Contributor

Your reproduction repo is just the create-next-app starter template. Any chance you could update it with the reproduction of the bug?

@williamtetlow
Copy link
Author

@awareness481 sorry just pushed commit

@awareness481
Copy link
Contributor

I couldn't reproduce the script running more than once per navigation, but I could reproduce having multiple script elements after multiple navigations, both for dev and production environments.

image

No idea if that's intended or not.

@williamtetlow
Copy link
Author

williamtetlow commented Jul 2, 2021

@awareness481 should have maybe worded the issue differently. It's not that I see the script running more than once per navigation but that it runs again when you navigate to another page.

In this example I do load index -> go to page -> go back to index and you can see by using script tag in Head that it only runs once but runs once per navigation using script tag.

Screenshot 2021-07-02 at 10 07 15

@williamtetlow williamtetlow changed the title next/script in _app.js creates next/script in _app.js has duplicate script tags in document after moving between pages Jul 2, 2021
@williamtetlow williamtetlow changed the title next/script in _app.js has duplicate script tags in document after moving between pages next/script in _app.js creates duplicate script tags in document after moving between pages Jul 2, 2021
@atulmy
Copy link

atulmy commented Jul 8, 2021

Even I'm facing this issue.

@wedneyyuri
Copy link

wedneyyuri commented Jul 11, 2021

While this behavior is not changed, we can do this kind of workaround

EDIT: See my message below.

App.tsx

export default function MyApp({ Component, pageProps }) {
    return <>
        <Script dangerouslySetInnerHTML={{
            __html: (`
                (function () {
                    var id = 'gtaginit';
                    if (window[id]) { return; }

                    window.dataLayer = window.dataLayer || [];
                    window.gtag = function gtag(){dataLayer.push(arguments);}
                    gtag('js', new Date());
                    gtag('config', '${GA_TRACKING_ID}');

                    window[id] = true;
                })();
            `)
        }} />
        <Script src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`} />
        <Component {...pageProps} />
    </>
}

@wedneyyuri
Copy link

wedneyyuri commented Jul 11, 2021

Okay, thinking better there's no reason to load this kind of script this way. Using React Hooks this code can be much cleaner:

// gtag.ts
const initialize = () => {
  window.dataLayer = window.dataLayer || [];
  window.gtag = function gtag() { window.dataLayer.push(arguments); }
  gtag('js', new Date());
  gtag('config', GA_TRACKING_ID);
};

// app.tsx
export default function MyApp({ Component, pageProps }) {
    useEffect(initialize, []); // this code will run only once

    return <>
        <Script src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`} />
        <Component {...pageProps} />
    </>
}

@atulmy
Copy link

atulmy commented Jul 11, 2021

I revered to using good old <script> tag for simplicity until this gets resolved.

janicklas-ralph added a commit to janicklas-ralph/next.js that referenced this issue Jul 16, 2021
@kodiakhq kodiakhq bot closed this as completed in #27218 Jul 16, 2021
kodiakhq bot pushed a commit that referenced this issue Jul 16, 2021
…onent (#27218)

Fixes inline scripts being duplicated when used with `next/script` component

## Bug

- [x] fixes #26860 
- [x] Integration tests added


## Documentation / Examples
 Updated docs to indicate that `id` is needed for inline scripts
@khanh-le-otsv
Copy link

khanh-le-otsv commented Aug 12, 2021

This is happening with next 11.1.0 for when I use beforeInteractive scripts in nextjs _app.tsx page. It was working fine with 11.0.1 for me.

@khanh-le-otsv
Copy link

Since those scripts are private, I cannot make that example here but I can see that the scripts get executed multiple times thus lead to the error.

flybayer pushed a commit to blitz-js/next.js that referenced this issue Aug 19, 2021
…onent (vercel#27218)

Fixes inline scripts being duplicated when used with `next/script` component

## Bug

- [x] fixes vercel#26860 
- [x] Integration tests added


## Documentation / Examples
 Updated docs to indicate that `id` is needed for inline scripts
@balazsorban44
Copy link
Member

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@vercel vercel locked as resolved and limited conversation to collaborators Jan 27, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Issue was opened via the bug report template.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants