All articles
Next.jsWebpackCachingDebugging

Fixing "Cannot read properties of undefined (reading 'call')" in Next.js Dev

Next.js dev crashing in webpack.js with reading 'call'? A stale browser-cached chunk is a sneaky cause. How to prove it, fix it, and rule out the rest.

Tushar Pachouri11 min read

This error looks like a webpack bug, and the usual advice is to delete .next and restart. Sometimes that works. When it hit this site (Next.js 14, App Router), deleting .next and restarting changed nothing, because the stale code wasn't on the server at all. It was in the browser cache, and a header rule I had written myself put it there.

TL;DR

  • The crash means the client was told to load a webpack module id that none of the loaded chunks registered, so __webpack_modules__[id] is undefined and .call throws.
  • If clearing .next doesn't fix it, suspect the browser: a Cache-Control: immutable rule on /_next/static/(.*) also applies in next dev, where chunk file names are not content-hashed.
  • Fix: only send long-lived caching headers outside dev, then hard reload once (Ctrl+Shift+R, or DevTools "Disable cache").
  • Other common causes: running next build while next dev shares .next, stale HMR state, case-mismatched imports, a service worker caching dev chunks, and duplicate packages in a monorepo.

The symptom

In the browser, the Next.js dev overlay shows something like this (frame names vary between versions):

Text
Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'call')

Call Stack
options.factory
  webpack.js
__webpack_require__
  webpack.js
fn
  webpack.js
requireModule
  react-server-dom-webpack-client.browser.development.js
initializeModuleChunk
  react-server-dom-webpack-client.browser.development.js
Lazy

Firefox reports the same failure as TypeError: options.factory is undefined. It often comes with a second error, because the client tree fails during hydration:

Text
Error: There was an error while hydrating. Because the error happened outside
of a Suspense boundary, the entire root will switch to client rendering.

The terminal running next dev usually shows nothing wrong. Pages compile fine, which is a big clue on its own.

Why it happens

Here is the relevant part of the dev webpack runtime, simplified:

JavaScript
// Simplified from the webpack runtime Next.js serves in dev (webpack.js)
function __webpack_require__(moduleId) {
  var cachedModule = __webpack_module_cache__[moduleId];
  if (cachedModule !== undefined) return cachedModule.exports;

  var module = (__webpack_module_cache__[moduleId] = { id: moduleId, loaded: false, exports: {} });
  var execOptions = {
    id: moduleId,
    module: module,
    factory: __webpack_modules__[moduleId], // undefined if no loaded chunk registered this id
    require: __webpack_require__,
  };
  __webpack_require__.i.forEach(function (handler) {
    handler(execOptions);
  });
  module = execOptions.module;
  execOptions.factory.call(module.exports, module, module.exports, execOptions.require); // throws here
  module.loaded = true;
  return module.exports;
}

Every chunk file pushes its modules into a global array (self.webpackChunk_N_E in Next.js), and the runtime copies them into __webpack_modules__. If code asks for an id that no chunk provided, factory is undefined.

In the App Router, the server sends an RSC payload that says "render client component X from module id Y, which lives in chunks A and B". The browser loads A and B, then calls __webpack_require__(Y). So the error always means the same thing: the payload and the chunks the browser actually ran disagree. The real question is which side is stale.

The payload names module Y, but no chunk the browser ran registered it, so the factory is undefined.

The real case: an immutable header in dev

My next.config.mjs had a caching rule meant for production performance:

JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
  async headers() {
    return [
      {
        source: "/_next/static/(.*)",
        headers: [
          { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
        ],
      },
    ];
  },
};

export default nextConfig;

In production this does no harm. Production chunk names contain a content hash, so a changed file gets a new URL, and Next.js already sends this header for its static assets anyway. The rule bought nothing, but it didn't break anything.

headers() also runs in next dev, though, and dev chunks are not hashed. The page chunk is /_next/static/chunks/app/page.js before and after every edit. Here is what happened:

  1. I loaded the home page. The browser cached app/page.js with a one-year, immutable lifetime.
  2. I added a new client component, SpaceCanvas, to the page.
  3. The dev server rebuilt app/page.js with the new module and sent an RSC payload referencing it.
  4. On the next full load, the browser used its cached app/page.js without asking the server. That file predated SpaceCanvas.
  5. React asked webpack for the SpaceCanvas module id, nothing had registered it, and .call threw.

A normal reload doesn't help much here. Browsers generally revalidate the page itself on reload but reuse subresources that are still fresh, and "fresh for a year" is very fresh.

1. FIRST LOAD 2-3. EDIT, REBUILD 4-5. NEXT LOAD DEV SERVER BROWSER CACHE RESULT app/page.js v1 app/page.js v2 RSC payload app/page.js v1 app/page.js v1 app/page.js v1 sent to the browser now has SpaceCanvas renders SpaceCanvas immutable, one year still fresh, kept reused, no request No loaded chunk registered SpaceCanvas, so .call throws Dev chunks are not hashed: every version is /_next/static/chunks/app/page.js
The server rebuilt the chunk, but the browser kept serving its year-long cached copy.

Why deleting .next didn't help

rm -rf .next plus a restart rebuilds the server's output. The server was already correct. The stale file was in the browser's HTTP cache, which no server-side cleanup touches. That's the key insight: if a clean .next doesn't fix it, stop looking at the server.

Deleting .next only cleans the server; the stale chunk sits in the browser's HTTP cache.

Diagnosing it in the browser

You can confirm this in about a minute instead of guessing.

List missing client modules

After the error appears, paste this into the browser console. It reads client references from the RSC payload (self.__next_f) and checks which module ids were never registered by any loaded chunk:

JavaScript
(() => {
  const payload = (self.__next_f || [])
    .filter((entry) => entry[0] === 1 && typeof entry[1] === "string")
    .map((entry) => entry[1])
    .join("");

  // Client reference rows look like: 4:I["<module id>",["<chunk>", ...],"<export>"]
  // (older 13.x builds used an object form: 4:I{"id":"<module id>",...})
  const referenced = new Set();
  for (const match of payload.matchAll(/^[0-9a-f]+:I(\[.*\]|\{.*\})$/gm)) {
    try {
      const ref = JSON.parse(match[1]);
      referenced.add(String(Array.isArray(ref) ? ref[0] : ref.id));
    } catch {
      // ignore rows that aren't plain JSON
    }
  }

  const registered = new Set();
  for (const [, modules] of self.webpackChunk_N_E || []) {
    for (const id of Object.keys(modules || {})) registered.add(id);
  }

  const missing = [...referenced].filter((id) => !registered.has(id));
  console.table(missing.map((id) => ({ missing: id })));
  return { referenced: referenced.size, registered: registered.size, missing };
})();

In dev, module ids are readable paths, so the output points straight at the problem, something like (app-pages-browser)/./components/SpaceCanvas.tsx. The internal payload format isn't a public API and can change between versions, so treat this as a debugging aid, not something to ship.

Note: A module can be legitimately missing if its chunk simply hasn't loaded yet (for example behind a lazy boundary). Run the script after the crash, and focus on ids whose chunk was loaded.

Check what the server actually sends

Next, ask the server for the same chunk directly, bypassing the browser cache:

Terminal
# Response headers only
curl -s -D - -o /dev/null http://localhost:3000/_next/static/chunks/app/page.js

# Does the server's copy contain the module?
curl -s http://localhost:3000/_next/static/chunks/app/page.js | grep -c "SpaceCanvas"

On Windows PowerShell, use curl.exe so you get real curl instead of the Invoke-WebRequest alias:

PowerShell
curl.exe -s -D - -o NUL http://localhost:3000/_next/static/chunks/app/page.js
(curl.exe -s http://localhost:3000/_next/static/chunks/app/page.js | Select-String "SpaceCanvas").Count

If the server's copy contains the module but the browser's doesn't, and the headers include Cache-Control: public, max-age=31536000, immutable, you've found it. You can also check the Network tab: the chunk will show "(disk cache)" or "(memory cache)" instead of a 200 from the server.

The fix

Only apply long-lived caching headers outside of development:

Diff
+const isDev = process.env.NODE_ENV === "development";
+
 /** @type {import('next').NextConfig} */
 const nextConfig = {
   async headers() {
     return [
-      {
-        source: "/_next/static/(.*)",
-        headers: [
-          { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
-        ],
-      },
+      ...(isDev
+        ? []
+        : [
+            {
+              source: "/_next/static/(.*)",
+              headers: [
+                { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
+              ],
+            },
+          ]),
     ];
   },
 };

Since Next.js already sets this header for /_next/static in production, deleting the rule entirely is just as valid. I kept it production-only so the intent is explicit in the config.

Then restart the dev server (config changes need it) and hard reload once. The browser still holds the immutable copies, and the new config can't reach into its cache:

  • Ctrl+Shift+R (Cmd+Shift+R on macOS), or
  • DevTools, then Network, then tick "Disable cache" and reload, or
  • DevTools, then Application, then Storage, then "Clear site data" for localhost:3000.

Tip: If you prefer not to rely on NODE_ENV, next.config.mjs can export a function that receives the build phase. PHASE_DEVELOPMENT_SERVER is only set for next dev.

JavaScript
import { PHASE_DEVELOPMENT_SERVER } from "next/constants.js";

/** @returns {import('next').NextConfig} */
export default function config(phase) {
  const isDev = phase === PHASE_DEVELOPMENT_SERVER;

  return {
    async headers() {
      if (isDev) return [];
      return [
        {
          source: "/_next/static/(.*)",
          headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }],
        },
      ];
    },
  };
}

Other causes of the same error

The browser cache case is the sneaky one. These are the more common ones, and they all reduce to the same mismatch between the module ids being requested and the modules actually loaded.

Building while the dev server runs

next dev and next build both write to .next by default. Run a build in a second terminal while dev is running and the build overwrites files the dev server is serving. You'll see this error or its cousin, __webpack_modules__[moduleId] is not a function.

The simplest fix is to stop the dev server before building. If you build often, give dev its own output folder:

JavaScript
const isDev = process.env.NODE_ENV === "development";

/** @type {import('next').NextConfig} */
const nextConfig = {
  distDir: isDev ? ".next-dev" : ".next",
};

export default nextConfig;

Add .next-dev to .gitignore. With TypeScript, also add .next-dev/types/**/*.ts to the include array in tsconfig.json, next to the existing .next/types/**/*.ts entry. Recent Next.js releases have been moving toward isolating dev output by default, so check your version's docs before adding this.

Stale HMR state after config or branch changes

Switching git branches, changing next.config, upgrading packages, or editing tsconfig paths can leave the dev server's in-memory module graph out of sync with the files on disk. Stop the server, clear the caches, start again:

Terminal
rm -rf .next node_modules/.cache
npm run dev
PowerShell
Remove-Item -Recurse -Force .next, node_modules\.cache -ErrorAction SilentlyContinue
npm run dev

Then hard reload the browser tab. An old tab can still be holding a runtime from the previous server session.

Case-mismatched import paths

On Windows and macOS (case-insensitive file systems by default), these both resolve to the same file:

TSX
import { Button } from "./components/Button";
import { Button as Btn } from "./components/button";

Webpack treats them as two different module ids. You get duplicated module state at best, and client reference lookups that miss at worst. Webpack usually warns about it in the terminal:

Text
There are multiple modules with names that only differ in casing.

Fix every import to match the real file name. Turn on the TypeScript check so it can't come back:

JSON
{
  "compilerOptions": {
    "forceConsistentCasingInFileNames": true
  }
}

If you need to rename a file's casing, git on a case-insensitive file system won't always notice. Rename in two steps:

Terminal
git mv components/button.tsx components/button-tmp.tsx
git mv components/button-tmp.tsx components/Button.tsx

This bug often appears only on CI or Linux, where the wrong-case import fails outright with "Module not found".

A service worker caching dev chunks

A PWA setup (next-pwa, Workbox, or a hand-written service worker) can serve cached chunks no matter what the HTTP headers say. Disable the worker in development. For next-pwa, that looks like this:

JavaScript
import withPWA from "next-pwa";

const isDev = process.env.NODE_ENV === "development";

/** @type {import('next').NextConfig} */
const nextConfig = {};

export default withPWA({
  dest: "public",
  disable: isDev,
})(nextConfig);

Then remove the worker that's already installed. Use DevTools, Application, Service Workers, "Unregister", or run this in the console:

JavaScript
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map((r) => r.unregister()));
const keys = await caches.keys();
await Promise.all(keys.map((k) => caches.delete(k)));
console.log(`Removed ${registrations.length} service worker(s) and ${keys.length} cache(s)`);

Warning: Ports get reused. A service worker registered by a different project on localhost:3000 will happily intercept requests for this one.

Duplicate React or mismatched packages

In monorepos, a shared UI package can end up with its own copy of react, or be resolved through both a symlink and its real path. Either way webpack sees two module ids for what should be one module. Check what's installed:

Terminal
npm ls react react-dom next
# or
pnpm why react

If you see more than one version, force a single one. With npm, the $ syntax reuses the version from the root package.json dependencies:

JSON
{
  "overrides": {
    "react": "$react",
    "react-dom": "$react-dom"
  }
}

Make sure workspace packages list react as a peerDependency, not a dependency. If they ship untranspiled source, add them to transpilePackages in next.config so Next.js compiles them through one pipeline.

Debugging checklist

Work through these in order. Each step rules out a whole category:

  1. Fresh profile test. Open the page in an incognito window. If it works there, the problem is browser state: HTTP cache or a service worker.
  2. Check headers. curl -D - a chunk under /_next/static/chunks/. If you see immutable or a long max-age in dev, make that rule production-only.
  3. Run the console script. Find the missing module id, then check whether the server's copy of the chunk contains it.
  4. Service workers. Look in DevTools, Application, Service Workers. Unregister anything you don't expect.
  5. One process per .next. Make sure no build or second dev server is writing to the same folder.
  6. Clean restart. Stop the server, delete .next and node_modules/.cache, restart, then hard reload.
  7. Casing and duplicates. Look for the "differ in casing" warning and run npm ls react.

Wrap-up

Cannot read properties of undefined (reading 'call') is never really about .call. It means the code that asks for a module and the code that provides modules came from different builds. Deleting .next fixes only the cases where the stale side is on the server. When that doesn't work, look at the browser: cached chunks, service workers, and any caching headers you added that make sense for hashed production files but not for unhashed dev ones. A production optimisation leaking into dev is an easy mistake to make, and a two-line isDev check keeps it from happening again.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch