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

Error: Shared module react doesn't exist in shared scope default #1104

Closed
gdunix opened this issue Jul 4, 2023 · 37 comments
Closed

Error: Shared module react doesn't exist in shared scope default #1104

gdunix opened this issue Jul 4, 2023 · 37 comments
Labels
help wanted Extra attention is needed nextjs-mf nextjs-mf package identifier RSC

Comments

@gdunix
Copy link

gdunix commented Jul 4, 2023

Getting this error when trying to use the new app router with @module-federation/nextjs-mf

Server Error
Error: Shared module react doesn't exist in shared scope default

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
ensureExistence
file:///Users/georgiosntounis/Documents/test-projects/next-mfe/.next/server/webpack-runtime.js (881:68)

Here is what I have in my next.config.js file

const NextFederationPlugin = require("@module-federation/nextjs-mf");

const remotes = () => {
  return {
    "my_components": `my_components@http://localhost:8082/remoteEntry.1.0.0.js`,
  };
};

const nextConfig = {
  webpack(config, { isServer }) {
      config.plugins.push(
        new NextFederationPlugin({
          name: "host",
          filename: "static/chunks/remoteEntry.js",
          remotes: remotes(),
          shared: {},
        })
      );
    return config;
  },
};

module.exports = nextConfig;
@yspychala
Copy link
Contributor

AFAIK, App dir isn’t supported yet. But I read it was planed after the release of v7.

@gpatatoukas
Copy link

Great to hear there's a plan in place! Any chance you could ballpark when we might see a solution? Also, is there a quick fix we can use in the meantime?

@yspychala
Copy link
Contributor

I’m not a maintainer so I cannot speak in their names. You may follow some issues that are already talking about this: #619 and #799 (comment)

@ScriptedAlchemy
Copy link
Member

yes RSC will get support eventually. With v7 now done, if the community wants to help (i know a few were interested in trying a few things) - im happy for extra hands.

First step i need is a PR of my repo using and breaking with app dir, then ill see what needs to be done to make it not error haha.

@ll-shiyi
Copy link

ll-shiyi commented Jul 5, 2023

Same issue, any solution here?

@ScriptedAlchemy ScriptedAlchemy added nextjs-mf nextjs-mf package identifier RSC help wanted Extra attention is needed labels Jul 5, 2023
@jmilind1234
Copy link

I'm also getting same error as that @gdunix is facing. Did anyone found solution? @ScriptedAlchemy @yspychala @gpatatoukas

@giovanniantonaccio
Copy link

@ScriptedAlchemy do you mean a PR creating a new example in this repo?

@nameofname
Copy link
Contributor

@ScriptedAlchemy I was just working on this... you can use my repo, created a branch which shows the issue clearly :
https://github.com/nameofname/next-module-federation/tree/nameofname/app-router-error/mfe2

Inside the dir mfe2/src there are 2 directories, app and pages-bak ... both are bare bones examples of app router and pages router. I tested locally and if I run npm run dev from within mfe2 then I will encounter the error.

If I mv app app-bak && mv pages-bak pages then cd.. && npm run dev then the error will go away.

nameof ~/github/next-module-federation/mfe2 (nameofname/app-router-error) # npm run dev

> [email protected] dev
> rm -rf .next; next dev -p 3002

- ready started server on 0.0.0.0:3002, url: http://localhost:3002
[nextjs-mf]: automaticAsyncBoundary is deprecated
[nextjs-mf]: automaticAsyncBoundary is deprecated
(node:18010) [DEP_WEBPACK_MODULE_ID] DeprecationWarning: Module.id: Use new ChunkGraph API
(Use `node --trace-deprecation ...` to show where the warning was created)
- event compiled client and server successfully in 240 ms (107 modules)
- wait compiling...
- event compiled client and server successfully in 112 ms (107 modules)
- wait compiling /page (client and server)...
- event compiled client and server successfully in 1677 ms (478 modules)
- error Error: Shared module react doesn't exist in shared scope default
    at ensureExistence (/Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:800:68)
    at /Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:878:13
    at /Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:863:20
    at webpack/sharing/consume/default/react (/Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:915:74)
    at /Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:959:56
    at Array.forEach (<anonymous>)
    at __webpack_require__.getEagerSharedForChunkId (/Users/nameof/github/next-module-federation/mfe2/.next/server/webpack-runtime.js:928:36)
    at /Users/nameof/github/next-module-federation/mfe2/.next/server/app/page.js:1869:72
    at Object.<anonymous> (/Users/nameof/github/next-module-federation/mfe2/.next/server/app/page.js:1882:3)
    at Module._compile (node:internal/modules/cjs/loader:1149:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1203:10)
    at Module.load (node:internal/modules/cjs/loader:1027:32)
    at Module._load (node:internal/modules/cjs/loader:868:12)
    at Module.require (node:internal/modules/cjs/loader:1051:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at requirePage (/Users/nameof/github/next-module-federation/mfe2/node_modules/next/dist/server/require.js:156:12)
    at /Users/nameof/github/next-module-federation/mfe2/node_modules/next/dist/server/load-components.js:71:84
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async loadComponentsImpl (/Users/nameof/github/next-module-federation/mfe2/node_modules/next/dist/server/load-components.js:71:26)
    at async DevServer.findPageComponentsImpl (/Users/nameof/github/next-module-federation/mfe2/node_modules/next/dist/server/next-server.js:772:36) {
  digest: undefined
}
- wait compiling /_error (client and server)...
- event compiled client and server successfully in 478 ms (573 modules)

@marcelongf
Copy link

@ScriptedAlchemy You still want some error examples related to app dir? I've been trying to import remotes within the app dir for a while now but without any success... I can hand you some examples

@ScriptedAlchemy
Copy link
Member

Yes please, really the main blocker beyond getting v7 done and starting a new job, historically it was i didnt have the time to reproduce some cases to work against, so instead of diverting time from v7 to see what needed to be done, i delayed the efffort till later. If you have a repo thats nice and broken, thats about 50% of the effort :)

@nameofname
Copy link
Contributor

@ScriptedAlchemy I created an example of this error happening in a fork of module-federation-examples.
In this commit I tried to take the page layout files you had and re-work them into an app dir.

Steps :

  • cd into module-federation-examples/nextjs-ssr/shop
    • run npm run dev
  • cd into module-federation-examples/nextjs-ssr/checkout
    • run npm run dev
  • cd into module-federation-examples/nextjs-ssr/home
    • run npm run build

... the same error occurs :

[nextjs-mf]: automaticAsyncBoundary is deprecated
(node:34832) [DEP_WEBPACK_MODULE_ID] DeprecationWarning: Module.id: Use new ChunkGraph API
(Use `node --trace-deprecation ...` to show where the warning was created)
[nextjs-mf]: automaticAsyncBoundary is deprecated
- info Creating an optimized production build  
- info Compiled successfully
- info Linting and checking validity of types  
- info Collecting page data ..Error: Shared module react doesn't exist in shared scope default
    at ensureExistence (/Users/nameof/projects/module-federation-examples/nextjs-ssr/home/.next/server/webpack-runtime.js:1263:68)
    at Function.<anonymous> (/Users/nameof/projects/module-federation-examples/nextjs-ssr/home/.next/server/webpack-runtime.js:1341:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Promise.all (index 0)
    at async Promise.all (index 1)
    at async loadComponentsImpl (/Users/nameof/projects/module-federation-examples/nextjs-ssr/home/node_modules/next/dist/server/load-components.js:80:26)
    at async /Users/nameof/projects/module-federation-examples/nextjs-ssr/home/node_modules/next/dist/build/utils.js:1006:32
    at async Span.traceAsyncFn (/Users/nameof/projects/module-federation-examples/nextjs-ssr/home/node_modules/next/dist/trace/trace.js:103:20)

> Build error occurred
Error: Failed to collect page data for /
    at /Users/nameof/projects/module-federation-examples/nextjs-ssr/home/node_modules/next/dist/build/utils.js:1156:15
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  type: 'Error'
}
- info Collecting page data .npm ERR! Lifecycle script `build` failed with error: 
npm ERR! Error: command failed 
npm ERR!   in workspace: [email protected] 
npm ERR!   at location: /Users/nameof/projects/module-federation-examples/nextjs-ssr/home 

@Muskos
Copy link

Muskos commented Jul 27, 2023

Hi @ScriptedAlchemy
You don't need any complex examples.
https://github.com/Muskos/nextjs-mf-app-folder
Here is just the Nextjs app with @module-federation/nextjs-mf plugin and one page in the app folder. You can reproduce it here.

@ll-shiyi
Copy link

I try to run this project: https://github.com/Muskos/nextjs-mf-app-folder
same error shows:
Error: Shared module react doesn't exist in shared scope default

Have you tested it yourself?

Hi @ScriptedAlchemy You don't need any complex examples. https://github.com/Muskos/nextjs-mf-app-folder Here is just the Nextjs app with @module-federation/nextjs-mf plugin and one page in the app folder. You can reproduce it here.

@arnoBruynseels
Copy link

arnoBruynseels commented Jul 31, 2023

Same issue here.

As mentioned in this comment it will hopefully be fixed in v7.1.

Here is the changelog.

@dylan-reniers-digitalum
Copy link

@arnoBruynseels @ScriptedAlchemy is there a beta version we could use for testing?

@hemanthkatam
Copy link

facing same issue here

  • error Error: Shared module react doesn't exist in shared scope default
    at ensureExistence (C:\practice\mfa-poc\ea-header.next\server\webpack-runtime.js:950:68)
    at C:\practice\mfa-poc\ea-header.next\server\webpack-runtime.js:1028:13
    at C:\practice\mfa-poc\ea-header.next\server\webpack-runtime.js:1013:20
    can anyone help me here

@marcelino-borges
Copy link

Same here

Is there any update on this?

I was migrating a whole project to the new "app" routing, but then started to face this error ='(

@ttdat2510
Copy link

+1 same here...

@dvynograd
Copy link

+1 here.

Has anybody found a workaround for the app router with nextjs 13.4 with module-federation

@sscotth
Copy link

sscotth commented Sep 1, 2023

we will likely implement it first in modernjs.dev, then see how to backport it to next. If it can be

#1183 (comment)

@vincentarck
Copy link

any update friend ? please let me know, currently having same trouble.
and i found this thread, about paid one nextjs-mf, whats the diffrence from free one ? https://www.privjs.com/packages/%40module-federation%2Fnextjs-mf?pkg=@module-federation/nextjs-mf

@bernardonascimento
Copy link

bernardonascimento commented Sep 11, 2023

+1

@sscotth
Copy link

sscotth commented Sep 11, 2023

any update friend ? please let me know, currently having same trouble. and i found this thread, about paid one nextjs-mf, whats the diffrence from free one ? https://www.privjs.com/packages/%40module-federation%2Fnextjs-mf?pkg=@module-federation/nextjs-mf

https://github.com/module-federation/module-federation-examples/discussions/978

@ScriptedAlchemy
Copy link
Member

Open to PRs for this longstanding issue. Modern.js will support RSC before Next.js due to its open-source priority. It's easier to implement in Modern.js, which has an unparalleled Developer Experience (DX) for Micro Frontends (MFE). The focus is on releasing the internal version to the open-source community, offering a meta-framework for microfrontends and horizontal scaling—something unmatched in my consulting experience with other companies' in-house MFE or MFP efforts.

Planning a fork of Module Federation to release an enhanced version with broad support for TypeScript (TS), Hot Module Replacement (HMR), Server-Side Rendering (SSR), dynamic loading, automatic route stitching, middleware, and more. For details, see issue #1170.

Challenges with Next.js are significant; it's not designed for module federation. Enhancements are often complex or nearly impossible. For an in-depth understanding, refer to the InvertedContainerRuntimeModule on GitHub.

"Container Inversion" involves a complete overhaul of webpack's JSONP and dependency management systems. Despite its complexity, it has solved other architectural issues, especially with circular or nested remotes. This will be integrated into V1.5 of the forked federation. RSPack.dev plans to implement V1.5 in Rust by Q1, offering native support for Module Federation. Concurrently, I'll work with the Modern.js team to reorganize their internal fork and decouple it from our internal deployment infrastructure.

There's overlap between the needs of Modern.js and Next.js. Bytedance has solved many issues at scale, and my recent Next.js workarounds have led to beneficial patterns. These will be integrated into my module-federation ecosystem with web-infra-dev.

I'm currently integrating the node federation specification for Modern.js as we perfect SSR and backend integrations. Plans are underway to use federation in CI, build management, and Infrastructure as Code, necessitating a memory-efficient server solution.

Timeline predictions: RSC support in Next.js is at least 6 months away. If urgently needed, our consulting/pro services branch can fund it. Modern.js will likely have RSC Federation support 2-3 weeks after RSC itself is supported. Unless a breakthrough or business case allows for resource reallocation, the timeline remains uncertain. Expect more insights in 1-2 months.

URLs:

@dhalbrook
Copy link
Contributor

I'm seeing this error and we're not using the app directory and are still on Next 12.

It will take a bit of time to get a sample repo together, but I'll work on it shortly. In the meantime, We're using the following:

"@module-federation/nextjs-mf": "6.7.1",
"@module-federation/typescript": "2.4.2",
"@module-federation/utilities": "^3.0.0"

and loading the remote via "importRemote".

What is super odd is that the S3-hosted remote works against my local Next instance in production mode, but when I run it on one our QA instances it throws this exception when attempting to load the remote (the remote returns 200 in both cases). We're only using client side rendering FWIW. My local box is compiling using OSX whereas our CI is Linux. The remote was compiled on my local instance before being uploaded to the S3 bucket. Does the OS have any effect on the webpack artifacts produced? I can't imagine it does, but I can't account for any other differences (other than my local running on http and the qa server running https).

I'm not sure it's helpful, but when I was using next/dynamic in the remote, the error message referenced not being able to load that module, until I changed it to use React.lazy.

@ScriptedAlchemy
Copy link
Member

Suspense swallows the error. You should try v7 or 8 and see how that works. 6 is old and quite

@dhalbrook
Copy link
Contributor

We are still on React 17 and Next 12. Switching to nextjs-mf 7.x causes new and different issues, one being webpack trying to dynamically load a bunch of node modules (Critical dependency: the request of a dependency is an expression) and then ultimately blowing up during SSR (RangeError: Maximum call stack size exceeded at RegExp.exec () at retrieveSourceMapURL).

@EliakimGama
Copy link

Hello, I'm facing the same issue

** Server Error**
Error: Shared module react-dom doesn't exist in shared scope default
This error occurred while generating the page. Any console logs will be displayed in the terminal window.

I'm using Next.js 13, is there any solution available?

@ScriptedAlchemy
Copy link
Member

use v8 prerelease. #1530
next tag on npm.
no RSC progress but less bugs

@wanbinkimoon
Copy link

wanbinkimoon commented Nov 7, 2023

I'm using v "@module-federation/nextjs-mf": "next", which translate into 8.0.1-4 and still experiencing the same error

Screenshot 2023-11-07 at 21 17 36

@ScriptedAlchemy
Copy link
Member

use "canary" tags

@bkirova
Copy link

bkirova commented Dec 12, 2023

For me the solution was to wrap the NextFederationPlugin plugin in `if (!options.isServer) like in this example:

https://github.com/module-federation/module-federation-examples/blob/77715463a47233b8db7f1403e3865aa1de5acf52/nextjs-v13/home/next.config.js#L5

and add the following aliases in the same if condition:

  config.resolve.alias["react/jsx-runtime"] = path.join(
    __dirname,
    "/node_modules/react/jsx-runtime.js"
  );
  config.resolve.alias["react/jsx-dev-runtime"] = path.join(
    __dirname,
    "/node_modules/react/jsx-dev-runtime.js"
  );
  config.resolve.alias["react"] = path.join(
    __dirname,
    "/node_modules/react/index.js"
  );

@rahimimo
Copy link

Which version did you use? @bkirova For my case the page blinks and it is empty even if with your solution.

@bkirova
Copy link

bkirova commented Dec 14, 2023

"next": "13.5.6"
"react": "^18.2.0"
"react-dom": "^18.2.0"

Something very important is that i am using the "pages" directory instead of the new "app" directory! This might be also part of why this setup is working.

This is my entire next.config.js (I am also using experimental imports from Framer)

/** @type {import('next').NextConfig} */
const { NextFederationPlugin } = require("@module-federation/nextjs-mf");
const path = require("path");
const nextConfig = {
  reactStrictMode: true,
  distDir: "build",
  webpack(config, options) {
    if (!options.isServer) {
      config.resolve.alias["react/jsx-runtime"] = path.join(
        __dirname,
        "/node_modules/react/jsx-runtime.js"
      );
      config.resolve.alias["react/jsx-dev-runtime"] = path.join(
        __dirname,
        "/node_modules/react/jsx-dev-runtime.js"
      );
      config.resolve.alias["react"] = path.join(
        __dirname,
        "/node_modules/react/index.js"
      );

      config.plugins.push(
        new NextFederationPlugin({
          name: "DreamComponents",
          filename: "static/chunks/remoteEntry.js",
          exposes: {
            "./components": "./src/components/index.ts",
          },
          shared: {},
        })
      );
    }

    return config;
  },
  experimental: {
    urlImports: [
      "https://framer.com/m/",
      "https://framerusercontent.com/",
      "https://ga.jspm.io/",
      "https://jspm.dev/",
      "https://rive.app/",
      "https://boosters.flowbase.co/",
    ],
  },
};

module.exports = nextConfig;

I hope this helps. @rahimimo

@rahimimo
Copy link

Thanks a lot! @bkirova . I have already got it working with pages directory my issue was getting it to working with the AppRouter. @ScriptedAlchemy I have tried the latest canary but still it did not work. Is it supposed to work now with the app router and there is something wrong with my code or it is still not supposed to work?
I am getting errors like app-index.js:128 Uncaught TypeError: (0 , _react.use) is not a function

@ScriptedAlchemy
Copy link
Member

#2002

@Ashin2052
Copy link

Ashin2052 commented Feb 12, 2024

"next": "13.5.6"
"react": "^18.2.0"
"react-dom": "^18.2.0"

Something very important is that i am using the "pages" directory instead of the new "app" directory! This might be also part of why this setup is working.

This is my entire next.config.js (I am also using experimental imports from Framer)

/** @type {import('next').NextConfig} */
const { NextFederationPlugin } = require("@module-federation/nextjs-mf");
const path = require("path");
const nextConfig = {
  reactStrictMode: true,
  distDir: "build",
  webpack(config, options) {
    if (!options.isServer) {
      config.resolve.alias["react/jsx-runtime"] = path.join(
        __dirname,
        "/node_modules/react/jsx-runtime.js"
      );
      config.resolve.alias["react/jsx-dev-runtime"] = path.join(
        __dirname,
        "/node_modules/react/jsx-dev-runtime.js"
      );
      config.resolve.alias["react"] = path.join(
        __dirname,
        "/node_modules/react/index.js"
      );

      config.plugins.push(
        new NextFederationPlugin({
          name: "DreamComponents",
          filename: "static/chunks/remoteEntry.js",
          exposes: {
            "./components": "./src/components/index.ts",
          },
          shared: {},
        })
      );
    }

    return config;
  },
  experimental: {
    urlImports: [
      "https://framer.com/m/",
      "https://framerusercontent.com/",
      "https://ga.jspm.io/",
      "https://jspm.dev/",
      "https://rive.app/",
      "https://boosters.flowbase.co/",
    ],
  },
};

module.exports = nextConfig;

I hope this helps. @rahimimo

Does this configuration works with ssr? I mean when option.isServer true or when we need module federation with ssr?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed nextjs-mf nextjs-mf package identifier RSC
Projects
None yet
Development

No branches or pull requests