Module Federation for React host and NextJS remote app example/comfiguration

Viewed 580

I didn't find an example for a react host with and nextjs remote app My host is working with a react remote app, now that I'm trying to add a nextjs remote app, it's not working:

  • Ports:

    • Host 3000
    • React remote 3001
    • NextJS Remote 3002
  • In my host react app I have the following, in the webpack.config.js file

plugins: [
    new ModuleFederationPlugin({
      name: 'react_container',
      filename: 'remoteEntry.js',
      remotes: {
        remote_react: 'remote_react@http://localhost:3001/remoteEntry.js', // <- This is working
        remote_nextjs: 'remote_nextjs@http://localhost:3002/_next/static/chunks/remoteEntry.js', // <- Not working :-(
      },
      exposes: {
        './react': 'react',
        './react-dom': 'react-dom',
      },
      shared: {
      },
    }),

And in the remote nextjs app in the next.config.js file

const { withFederatedSidecar } = require("@module-federation/nextjs-mf");

module.exports = withFederatedSidecar({
  name: "remote_nextjs",
  filename: "static/chunks/remoteEntry.js",
  exposes: {
    "./ExposedComponent": "./components/ExposedComponent",
  },
  shared: {
  },
})({
  // your original next.config.js export
});
  • And finally, in the App.jsx of the host , I'm trying to consume the remote components like
import RemoteNav from 'remote_react/Nav'; // <- Working 
import ExposedComponent from 'remote_nextjs/ExposedComponent'; // <- Not working

The error I'm getting its 404 from http://localhost:3000/_next/static/chunks/components_ExposedComponent_js.js

enter image description here

Thanks

1 Answers

From the webpack config of the host, I can see that the next JS app is running on port 3002.

You are getting 404 error for next JS remote bundles when the host is trying to fetch the bundles from next JS server, it is hitting port 3000 instead of 3002. This is because the next.config.js does not have the updated publicPath.

Add the following in the place where it says //your original next.config.js export in the next.config.js file

webpack: (config) => {
  config.output.publicPath = "http://localhost:3002/_next/";
  return config;
}

This will set the publicPath of your next JS app to port 3002 and fetch the bundles correctly.

Related