Encountering a Module Federation integration error while setting up Next.js 14 with App Directory: NextFederationPlugin

Currently, I am in the process of developing a micro-frontend application using Next.js 14.2.5 in combination with Module Federation. To initiate this project, I utilized the following commands to create two separate applications:

npx create-next-app mf-host
npx create-next-app mf-widgets

In both these applications, I have adopted the app directory structure. Below is an overview of how I configured the next.config.mjs files for each individual application:

mf-widgets - next.config.mjs:

/** @type {import('next').NextConfig} */
import { NextFederationPlugin } from '@module-federation/nextjs-mf';

process.env.NEXT_PRIVATE_LOCAL_WEBPACK = true;

const nextConfig = {
  reactStrictMode: true,
  transpilePackages: ["ui"],
  webpack: (config, { isServer }) => {
    config.plugins.push(
      new NextFederationPlugin({
        name: 'widgets',
        filename: 'static/chunks/remoteEntry.js',
        exposes: {
          './TopNavigation': './components/topNavigation/TopNavigation',
        },
      })
    );
    return config;
  },
};

export default nextConfig;

mf-host - next.config.mjs:

/** @type {import('next').NextConfig} */
import { NextFederationPlugin } from '@module-federation/nextjs-mf';

process.env.NEXT_PRIVATE_LOCAL_WEBPACK = true;

const WIDGETS_APP_URL =
  process.env.NEXT_PUBLIC_WIDGET_APP_URL || 'http://localhost:3000';

const remotes = (isServer) => {
  const location = isServer ? 'ssr' : 'chunks';
  return {
    widgets: `widgets@${WIDGETS_APP_URL}/_next/static/${location}/remoteEntry.js`,
  };
};

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

export default nextConfig;

Upon attempting to launch the mf-widgets application, I encountered the following error message:

▲ Next.js 14.2.5 Local: http://localhost:3000 ✓ Starting... Error: App Directory is not supported by nextjs-mf. Use only pages directory, do not open git issues about this at NextFederationPlugin.validateOptions...

This error seems to indicate that nextjs-mf does not accommodate the app directory structure in Next.js 14. Is there a workaround to make it compatible with the app directory, or should I revert back to the pages directory paradigm? If so, could you provide guidance on how to go about it?

I attempted to rename the app directory to pages within my Next.js project. Following this adjustment, I anticipated normal functionality where upon accessing the deployment at localhost:3000 (a module federation host), the default page would load successfully. However, instead of seeing my application as expected, I was met with a 404 Page Not Found error.

Answer №1

If you run the command npx create-next-app temp-app and want to organize your Next.js project using a page structure that follows the traditional format for Next.js applications, here's how you can do it:

During the setup process, make sure to select the following options:

  • "Do you want to use the src/ directory?" - Choose No
  • "Do you want to use the App Router?" - Choose No

After setting up, I created my widgets within the components folder. This allowed me to seamlessly continue with developing my nextjs micro front end.

However, I've encountered an issue where webpack does not seem to work properly with the latest app router structure. Does anyone have any suggestions on how to navigate this situation and proceed with utilizing the most current nextjs routing structure alongside micro front ends?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there any advice for resolving the issue "In order to execute the serve command, you must be in an Angular project, but the project definition cannot be located"?

Are there any suggestions for resolving the error message "The serve command requires to be run in an Angular project, but a project definition could not be found."? PS C:\angular\pro\toitsu-view> ng serve The serve command requires to be ...

Ensure that data is properly filtered before being presented in the Angular 5 component

Currently, I am dealing with football data retrieved from an API. https://i.sstatic.net/MRSsH.jpg When I make a request to this API endpoint, all the available lists are displayed. My goal is to organize the list based on the game status, such as Finishe ...

Setting the default value for a useRef<HTMLInputElement> in ReactJs with Typescript

Is there a way to assign a number as the initial value on useRef<HTMLInputElement> without using useState<number>() since the field is a simple counter? Below is my TypeScript code: const MyComponent = () => { const productAmountRef = us ...

Having trouble with your start script crashing during your first Next.js project deployment on Heroku?

Seeking guidance as a beginner? My first next.js project works fine locally with no warnings and deploys successfully on Heroku. However, when I view the app, I encounter an error page prompting me to check my logs. I followed a tutorial posted here. You ...

Issue encountered when attempting to run "ng test" in Angular (TypeScript) | Karma/Jasmine reports an AssertionError stating that Compilation cannot be undefined

My development setup includes Angular with TypeScript. Angular version: 15.1.0 Node version: 19.7.0 npm version: 9.5.1 However, I encountered an issue while running ng test: The error message displayed was as follows: ⠙ Generating browser application ...

Is it possible to compile a TypeScript file with webpack independently of a Vue application?

In my Vue 3 + Typescript app, using `npm run build` compiles the app into the `dist` folder for deployment. I have a web worker typescript file that I want to compile separately so it ends up in the root of the `dist` folder as `worker.js`. Here's wha ...

Checking a sequence using a list of strings

I have an array containing a list of IDs: var listId: string[] = []; var newId: boolean; for (let i in data.chunk) { listId.push(data.chunk[i].aliases[0]); } My objective is to compare a new ID with the entire list. If the new ID is found in the list ...

Sending data to the NextJS Layout Component

I successfully imported the layout component into my _app.js file: Layout.js: const Layout = ({ children, webName, pageTitle }) => { return ( <div> <Head> <meta charSet='utf-8' /> <meta ...

I'm curious as to why my array is only being filled within the subscription function

When I call the GetAllMainStore() function, data is successfully retrieved from the API and the console indicates that "this.MainStoreArray" contains data. The problem arises when I attempt to access "this.MainStoreArray" outside of the GetAllMainStore() ...

Encountering Compilation Error When Using RxJS Observable with Angular 6 and Swagger Codegen

Encountering TypeScript compiler errors related to rxjs while working with Angular 6 and Swagger Codegen: Cannot find module 'rxjs-compat/Observable' Referenced the following link for assistance: https://github.com/ReactiveX/rxjs/blob/master/M ...

Error displaying PDF from AWS S3 link

I am working on a NextJS v14 project integrated with AWS Amplify, where I have multiple PDFs stored. My goal is to display them using the <Document /> component from the react-pdf library. However, I keep encountering this error: ./node_modules/canva ...

Tips for extracting and mapping a sub array from the category response JSON using SWR with MongoDB in a Next.js (Node.js) environment

Can anyone assist me with reading and mapping arrays inside JSON? Using Hook (useSWR / useCategories): import useSWR from "swr" const fetcher = (...args) => fetch(...args).then(res => res.json()) function useCategories () { const { data, erro ...

What is the best way to retrieve specific values from an ng-bootstrap modal?

I am working on a website that includes an ng-bootstrap modal. This modal contains two <select> elements with dynamic items, allowing the user to click on two buttons. One button simply closes the modal and sets the value of the Reactive Form to new ...

Error encountered with dynamic mapping router in Typescript

When using Typescript and react-router-dom, I encountered an issue while declaring an array to dynamically generate the child Route in Switch. The error message displayed: Conversion of type '{ routeMap: RouteProps<string, { [x: string]: string | u ...

A software piece producing a JSX element that generates a single function

Is it possible to create a JSX element or component that returns a single function as its child? For instance: interface ComponentChildrenProps { someProp: string; } const Component: React.FC<ComponentProps> = ({ children }): JSX.Element => { ...

Issue with Typescript: The 'remove' property is not found on the 'EventTarget' type

I keep seeing the error Type error: Property 'remove' is not recognized on type 'EventTarget'. <img onError={function(e) { e.target.remove(); }} src="../me.jpg" alt=""/> ...

Experiencing unexpected behavior with React Redux in combination with Next.js and NodeJS

I'm in the process of developing an application using Next.js along with redux by utilizing this particular example. Below is a snippet from my store.js: // REDUCERS const authReducer = (state = null, action) => { switch (action.type){ ...

"Creating a visual representation of models exchanged between the client and server through Rest

Currently, I am working on a project that involves client-server communication via rest API, with Angular 2 calling restful web services as the primary method. The client side is written in Typescript, which is a subset of JavaScript. My main challenge li ...

Is it possible for me to exclude generic parameters when they can be inferred from another source?

Imagine having a scenario like this: type RecordsObject<T, K extends keyof T> = { primaryKey: K; data: Array<T>; } where the type K is always derived from the type T. Oftentimes, when I try to declare something as of type RecordsObject, ...