This project demonstrates the use of Module Federation in Next.js 14, leveraging the @module-federation/nextjs-mf package for federating modules across applications.
-
Install all dependencies:
pnpm install:all
-
Start the application
pnpm run start
-
Access the apps at the following URLs:
- App router consumer:
http://localhost:5001
- Page router consumer:
http://localhost:4001
- App router consumer:
- page router consumer
- page router provider
- app router consumer
- app router provider
Each consumer imports components from two different sources:
- A component from a Next.js page router app.
- A component from a Next.js app router app.
On the page router side, you can use React.lazy
to import components, and they will be rendered server-side as expected. but for import a app router component, we need to use dynamic
from next/dynamic
and Suspense
to handle loading states.
However, SSR is currently not supported for Module Federation in the app router. Instead, to handle client-side rendering in the app router, we use loadRemote
from @module-federation/enhanced/runtime
to dynamically load federated modules. This process must happen in a client component, and the remote component is wrapped in a Suspense
to handle loading states.
For expose a MFE with a nextjs app router, we need to update the @modulefederation/nextjs-mf package to support the app router. Like here :
And remove on the nextjs-mf/dist/src/plugins/NextFederationPlugin/index.js
if (manifestPlugin?.appDirEnabled) {
throw new Error(
"App Directory is not supported by nextjs-mf. Use only pages directory, do not open git issues about this"
);
}