How To: Configure Remote Module at Runtime in Next.js with Module Federation

How To: Configure Remote Module at Runtime in Next.js with Module Federation

·

2 min read

Problem

There can be times when you want to load a module from another application but you don't have the necessary information at build time to be able to do that. For example, if you're Next.js application is running in a Kubernetes (k8) cluster and you're getting the remote URL via an environment variable which gets populated by k8 then the value would probably be coming in as undefined and that's because the value is not available during build time.

Solution

So, how can one solve this problem? You guessed it right, by configuring remote modules at run time.

Note: you need to have @module-federation/nextjs-mf package installed in your Next.js application as a pre-requisite.

The below code block serves the purpose of allowing you to provide information about the remote module at runtime:

import { injectScript } from '@module-federation/nextjs-mf';

async function loadRemoteModule() {
  try {
    return injectScript({
      url: `${process.env.REMOTE_APP_URL}/remoteEntry.js`,
      global: 'remoteAppName'
    })
      .then(container => container.get("./remoteModulePath"))
      .then(loader => loader());
  } catch (error) {
    console.error('Failed to load remote module:', error);
    return null;
  }
}

Note: You can further modify the above code block to make it more configurable by taking in the values as function parameters so you can dynamically update and modify the behaviour and settings of the remote module based on the specific requirements and needs of your application.

Lastly, in addition to the above example, I would highly recommend exploring the various utilities and functionalities available in the package's repo. These utilities not only provide valuable insights into the inner workings of the package but also offer a comprehensive understanding of its capabilities. By delving into the repository, you will uncover a wealth of knowledge that can greatly enhance your understanding and utilization of this powerful tool. So, take the time to dive into the repository and unlock the full potential of this package!