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

Adding any script to root layout (or layout or page) causing an error in clean next 13 repo #42519

Closed
1 task done
madaher-dev opened this issue Nov 5, 2022 · 9 comments · Fixed by #43334
Closed
1 task done
Assignees
Labels
area: app App directory (appDir: true) bug Issue was opened via the bug report template. Script (next/script) Related to Next.js Script Optimization.

Comments

@madaher-dev
Copy link

madaher-dev commented Nov 5, 2022

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
Platform: win32
Arch: x64
Version: Windows 10 Home
Binaries:
Node: 16.13.1
npm: N/A
Yarn: N/A
pnpm: N/A
Relevant packages:
next: 13.0.1
eslint-config-next: 13.0.1
react: 18.2.0
react-dom: 18.2.0

What browser are you using? (if relevant)

Chrome 106.0.5249.119

How are you deploying your application? (if relevant)

next dev -p 5000

Describe the Bug

Tried adding google analytics tag script to root layout file as follows:

import { Providers } from "./providers";
import localFont from "@next/font/local";
import Script from "next/script";

const Archivo = localFont({
  src: "./fonts/Archivo-Regular.ttf",
  weight: "400",
});

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </head>
      <body style={{ margin: 0, padding: 0 }}>
        <Providers>
          <section
            style={{
              backgroundColor: "red",
              height: "50px",
            }}
            className={Archivo.className}
          >
            The is the App Top Header - Will Apear in all pages
          </section>
          <section>{children}</section>
        </Providers>
      </body>
      <Script
        strategy="lazyOnload"
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
      />

      <Script strategy="lazyOnload">
        {`
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
        page_path: window.location.pathname,
        });
    `}
      </Script>
    </html>
  );
}

but gets the following error as soon as the page gets hydrated

Unhandled Runtime Error
ChunkLoadError: Loading chunk amp failed.
(missing: http://localhost:5000/_next/static/chunks/amp.js)
Call Stack
__webpack_require__.f.j
file:///C:/Users/sanit/Desktop/next13/.next/static/chunks/webpack.js (875:29)
<unknown>
/_next/static/chunks/webpack.js (155:40)
Array.reduce
<anonymous>
__webpack_require__.e
file:///C:/Users/sanit/Desktop/next13/.next/static/chunks/webpack.js (154:67)
fn.e
/_next/static/chunks/webpack.js (397:50)
self.__next_chunk_load__
node_modules\next\dist\client\app-index.js (31:33)
preloadModule
node_modules\next\dist\compiled\react-server-dom-webpack\client.js (83:0)
resolveModule
node_modules\next\dist\compiled\react-server-dom-webpack\client.js (650:0)
processFullRow
node_modules\next\dist\compiled\react-server-dom-webpack\client.js (735:0)
processBinaryChunk
node_modules\next\dist\compiled\react-server-dom-webpack\client.js (789:0)

also in the console i see

amp-dev.js?5ccf:7 Uncaught TypeError: Cannot read properties of null (reading 'textContent')
    at eval (amp-dev.js?5ccf:7:49)
    at ./node_modules/next/dist/client/dev/amp-dev.js (amp.js:106:1)
    at options.factory (webpack.js:722:31)
    at __webpack_require__ (webpack.js:37:33)
    at __webpack_exec__ (amp.js:703:61)
    at amp.js:704:37
    at webpackJsonpCallback (webpack.js:1410:39)
    at amp.js:9:61

i noticed that when i run the project with next build and then next start i only get the console warning

Expected Behavior

The page should load normally and the script called.

Link to reproduction

https://github.com/madaher-dev/next13.git

To Reproduce

Follow docs to install clean next 13 project
create app directory and page and root layout
import next/script to root layout
use any script in the root template html

@madaher-dev madaher-dev added the bug Issue was opened via the bug report template. label Nov 5, 2022
@madaher-dev madaher-dev changed the title Adding any script to root layour or layout or page causing an error in clean next 13 repo Adding any script to root layout (or layout or page) causing an error in clean next 13 repo Nov 5, 2022
@balazsorban44
Copy link
Member

I am unable to reproduce this, given the repo you linked to. Everything loads fine. Have you been able to resolve the issue? Otherwise, this might be OS/Browser-specific. 🤔

@balazsorban44 balazsorban44 added type: needs investigation Script (next/script) Related to Next.js Script Optimization. area: app App directory (appDir: true) labels Nov 6, 2022
@madaher-dev
Copy link
Author

madaher-dev commented Nov 6, 2022

I am unable to reproduce this, given the repo you linked to. Everything loads fine. Have you been able to resolve the issue? Otherwise, this might be OS/Browser-specific. 🤔

Yes i can confirm. I just cloned the repo as is and ran npm i and npm run dev and directly get the error are soon as i open the browser.
I tried it on Edge same thing. I will try it on a different OS when am at the office tomorrow
See screenshot below
https://www.linkpicture.com/q/Screenshot-2022-11-06-101006.png

@nevsky118
Copy link

I get the same error when embedding the script in the root layout. Here is the repo https://github.com/nevsky118/my-app
Screenshot with error https://i.imgur.com/nvmUwB1.png

Chrome Version 107.0.5304.88 (Official Build) (64-bit)

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Home
Binaries:
  Node: 16.15.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant packages:
  next: 13.0.2
  eslint-config-next: 13.0.2
  react: 18.2.0
  react-dom: 18.2.0

@madaher-dev
Copy link
Author

madaher-dev commented Nov 7, 2022

We tried in the office on a Mac and it works fine. seems to me a 64bit issue?

 Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 22.1.0: Sun Oct  9 20:15:52 PDT 2022; root:xnu-8792.41.9~2/RELEASE_ARM64_T8112
    Binaries:
      Node: 18.9.1
      npm: 8.19.1
      Yarn: N/A
      pnpm: N/A
    Relevant packages:
      next: 13.0.1
      eslint-config-next: 13.0.1
      react: 18.2.0
      react-dom: 18.2.0

warn  - Latest canary version not detected, detected: "13.0.1", newest: "13.0.3-canary.0".
        Please try the latest canary version (npm install next@canary) to confirm the issue still exists before creating a new issue.
        Read more - https://nextjs.org/docs/messages/opening-an-issue

@madaher-dev
Copy link
Author

I tried updating and got same behavior
Operating System:
Platform: win32
Arch: x64
Version: Windows 10 Home
Binaries:
Node: 16.13.1
npm: N/A
Yarn: N/A
pnpm: N/A
Relevant packages:
next: 13.0.2
eslint-config-next: 13.0.2
react: 18.2.0
react-dom: 18.2.0

@rafma0
Copy link

rafma0 commented Nov 9, 2022

I got similar errors trying in my RootLayout

<Script id='consolehi'>
  {'console.log(\'hi\')'}
</Script>

console

Uncaught TypeError: Cannot read properties of null (reading 'textContent')
Uncaught ChunkLoadError: Loading chunk amp failed.
Warning: An error occurred during hydration. The server HTML was replaced with client content in <#document>.
Uncaught Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.

also I if add strategy='beforeInteractive' eslint complains about using this strategy outside pages/_document.js

in my case I was trying to add a simple script for dark mode, so it won't flash the screen, and I ended doing for now

<script dangerouslySetInnerHTML={{
  __html: `const theme = localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
  document.documentElement.setAttribute('data-theme', theme)`
}}

it works but dev mode complains about dom being different between server and client, I guess it won't happen using next/script after it gets fixed?

info

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Pro
Binaries:
  Node: 18.4.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant packages:
  next: 13.0.3-canary.2
  eslint-config-next: 13.0.2
  react: 18.2.0
  react-dom: 18.2.0

@igierard
Copy link

I'm experiencing a similar issue. It doesn't happen when I build from WSL but it does happen when I build from windows (both PowerShell and git bash). So it seems this might be a windows only issue.

Unfortunately building in WSL from a /mnt/ directory doesn't allow for filesystem update events so no hot reloading or file updates after the next initially loads the file so it isn't really a development option.

@pogran
Copy link

pogran commented Nov 18, 2022

do this problem is still active?

@kodiakhq kodiakhq bot closed this as completed in #43334 Nov 25, 2022
kodiakhq bot pushed a commit that referenced this issue Nov 25, 2022
On Windows `cunkGroup.name` is `app\layout` rather than `app/layout`. This causes it to get the wrong chunks in `flight-manifest.json` for `next/script` in this case:
```json
"chunks": ["webpack:webpack", "amp:amp"],
```
After checking for backslash:
```json
"chunks":["app\\layout:app\\layout"],
```

fixes #42519

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
@github-actions
Copy link
Contributor

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Dec 25, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area: app App directory (appDir: true) bug Issue was opened via the bug report template. Script (next/script) Related to Next.js Script Optimization.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants