next.js: [NEXT-3982] ChunkLoadError: Loading chunk app/layout failed. (timeout: http://localhost:3000/_next/static/chunks/app/layout.js)

Link to the code that reproduces this issue

https://github.com/Intellyse/next-js-bug

To Reproduce

  1. clone project
  2. npm install
  3. npm run dev
  4. open the page and you can see chrome console output: Uncaught SyntaxError: Invalid or unexpected token
  5. same minutes you can see error:Uncaught ChunkLoadError: Loading chunk app/layout failed. image

Current vs. Expected behavior

  1. First time open the page is error but you refresh page is work!
  2. I expected is work all the time

Provide environment information

Operating System:
  Platform: wls ubutnu
  Arch: arm64
  Version: wls version 2
Binaries:
  Node: 20.9.0
  npm: 10.1.0
Relevant Packages:
  next: 14.2.3 // I tried also last canary version (15.0.0-canary.10).
  eslint-config-next: 14.2.3
  react: 18.2.0
  react-dom: 18.0.0
  typescript: 5.4.5
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Webpack

Which stage(s) are affected? (Select all that apply)

next dev (local)

Additional context

The error seems happen randomly, and we have this issue also in production. It seems related with something with webpack

__webpack_require__.f.j = function (chunkId, promises) {
  // JSONP chunk loading for javascript
  var installedChunkData = __webpack_require__.o(installedChunks, chunkId)
    ? installedChunks[chunkId]
    : undefined;
  if (installedChunkData !== 0) {
    // 0 means "already installed".

    // a Promise means "currently loading".
    if (installedChunkData) {
      promises.push(installedChunkData[2]);
    } else {
      if ("webpack" != chunkId) {
        // setup Promise in chunk cache
        var promise = new Promise(function (resolve, reject) {
          installedChunkData = installedChunks[chunkId] = [resolve, reject];
        });
        promises.push((installedChunkData[2] = promise));

        // start chunk loading
        var url = __webpack_require__.p + __webpack_require__.u(chunkId);
        // create error before stack unwound to get useful stacktrace later
        var error = new Error();
        var loadingEnded = function (event) {
          if (__webpack_require__.o(installedChunks, chunkId)) {
            installedChunkData = installedChunks[chunkId];
            if (installedChunkData !== 0) installedChunks[chunkId] = undefined;
            if (installedChunkData) {
              var errorType = event && (event.type === "load" ? "missing" : event.type);
              var realSrc = event && event.target && event.target.src;
              error.message =
                "Loading chunk " + chunkId + " failed.\n(" + errorType + ": " + realSrc + ")";
              error.name = "ChunkLoadError";
              error.type = errorType;
              error.request = realSrc;
              installedChunkData[1](error);
            }
          }
        };
        __webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
      } else installedChunks[chunkId] = 0;
    }
  }
};

the error rise at line: var error = new Error();

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 21
  • Comments: 23 (2 by maintainers)

Commits related to this issue

Most upvoted comments

Dear Vercel Team,

I would like to once again register my concern about a critical error that continues to occur in Next.js 15 environments, and request a position from the technical team.

Error context:

Today I was able to reproduce the problem consistently by following these steps:

  • npm run dev (development environment)

  • I kept the application inactive

  • After ~5 minutes of inactivity, the error occurs spontaneously:

Error Screenshot

Image

Technical details:

  • Next.js 15.2.0

  • Local development environment

  • No user action involved

There are already several similar reports in the community, but so far we have not had any official feedback. I would like to understand:

If there is a recommended temporary workaround

If there is a hotfix planned

If we need to provide more technical information

I would greatly appreciate an update on the case, as this is significantly impacting our production flow.

Has anyone found a definitive solution for the chunk loading issue?

I’ve been looking into this problem, which seems to have started in version 13.3.4 of Next.js, and it continues to affect all subsequent versions, including the pre-release version 15.0.0.canary.

Some people suggest that removing the .next folder clears the cache and temporarily fixes the issue, but this solution isn’t viable for production environments, where such an approach could cause more problems. Others have implemented workarounds like forcing a page reload when the error is detected, but these are not ideal solutions either.

So far, I haven’t seen anyone in the community find a solid fix, and it seems like the newer versions of Next.js aren’t addressing this issue, possibly because it’s considered an “old” bug that started in version 13.3.4. We know it’s related to Webpack, but is there any viable alternative to Webpack for production environments at the moment?

Auto-detecting and reloading failed chunks in my global layout.tsx worked for me. Not sure its the ideal solution but seems to resolve the problem.

<script dangerouslySetInnerHTML={{
          __html: `
            // Track failed chunks
            window.__failedChunks = new Set();

            // Retry loading failed chunks
            function retryLoadChunk(url, maxRetries = 3) {
              if (window.__failedChunks.has(url)) return;
              
              let retries = 0;
              const loadScript = () => {
                if (retries >= maxRetries) {
                  window.__failedChunks.add(url);
                  return;
                }

                retries++;
                const script = document.createElement('script');
                script.src = url;
                script.async = true;
                script.onerror = () => {
                  setTimeout(loadScript, 1000 * retries);
                };
                document.head.appendChild(script);
              };

              loadScript();
            }

            // Handle errors and retry chunk loading
            window.onerror = function(msg, url, lineNo, columnNo, error) {
              if (url?.includes('/_next/') && 
                  (msg.includes('chunk') || msg.includes('Syntax'))) {
                retryLoadChunk(url);
              }
              return false;
            };

            // Handle script load failures
            window.addEventListener('error', function(event) {
              if (event.target?.tagName === 'SCRIPT') {
                const src = event.target.src;
                if (src.includes('/_next/')) {
                  retryLoadChunk(src);
                  event.preventDefault();
                }
              }
            }, true);
          `
        }} />

I have also encountered this issue.

I can confirm that I am also seeing this error with 15.1.3. Adding the --turbo option to the next dev command resolves it for me.

I have this issue as well, it’s quite frustrating. Hopefully, it will be resolved soon.

We’ve ran the reproduction but don’t see the error that’s being reported. Can you clarify with the customer by getting a full stacktrace of the error in question? is there any reproducible steps you can provide?

@swarnava this happen when you using cloudflare in product

We’ve ran the reproduction but don’t see the error that’s being reported. Can you clarify send a full stacktrace of the error in question? is there any reproducible steps you can provide?