// Advertisement

NextJS Module Federation Quickstart Guide

published on 28 April 2024

NextJS Module Federation is a powerful approach for building scalable and efficient micro-frontends using Next.js. It allows you to divide your application into smaller, independent modules that can be developed, deployed, and maintained separately, enabling:

  • Dynamic code loading: Load only the necessary code when needed
  • Independent deployments: Deploy modules separately without affecting the entire application
  • Shared dependencies: Reduce overall bundle size and improve page load times

By following this guide, you'll learn how to:

  1. Install Required Packages

    • Install @module-federation/nextjs-mf package
  2. Configure Host Application

    • Set up next.config.js to enable Module Federation
    • Configure NextFederationPlugin with options
  3. Set up Remote Module

    • Create a new NextJS application for the remote module
    • Configure next.config.js to expose desired modules
  4. Consume Remote Modules

    • Configure Host application to consume remote modules
    • Use dynamic imports to load remote modules
  5. Manage Shared Dependencies

    • Understand and configure shared dependencies
    • Avoid code duplication and optimize performance
  6. Test Module Federation Setup

    • Test locally and troubleshoot common issues
  7. Deploy Federated Modules

    • Deployment options: Server-side rendering (SSR) or Client-side rendering (CSR)
    • Prepare for deployment and upload to a CDN or cloud provider

By integrating Module Federation into your NextJS project, you can break down large applications into smaller, independent modules, enabling faster development cycles, improved collaboration, and a more scalable architecture.

Getting Started with Module Federation

Before you start using Module Federation with Next.js, make sure you have the necessary foundation in place. Here's a checklist to get you started:

Familiarity with Next.js and Module Federation Concepts

Next.js

Take some time to understand the core concepts of Next.js, including:

  • Server-side rendering
  • Static site generation
  • API routes

Also, familiarize yourself with Module Federation and its benefits in enabling micro-frontends architecture.

Node.js and npm Installation

Node.js

Make sure you have Node.js (version 14 or higher) and npm installed on your development machine. You can verify this by running node -v and npm -v in your terminal.

Create a New Next.js Project

Create a new Next.js project using npx create-next-app or yarn create next-app. This will give you a solid foundation to build upon.

Install Required Packages

Install the @module-federation/nextjs-mf package using npm or yarn. This package provides the necessary plugins and utilities to enable Module Federation in your Next.js application.

By following these steps, you'll be well-prepared to integrate Module Federation into your Next.js project and start building scalable and efficient micro-frontends.

In the next section, we'll dive deeper into the configuration process, covering the necessary steps to set up your Host application and Remote modules.

Step 1: Install Required Package

Installing @module-federation/nextjs-mf

To integrate Module Federation into your Next.js project, you need to install the @module-federation/nextjs-mf package. This package provides the necessary plugins and utilities to enable Module Federation in your Next.js application.

Installation Options:

Method Command
npm npm install @module-federation/nextjs-mf
yarn yarn add @module-federation/nextjs-mf

Verify the Installation:

After installing the package, you can verify that it's been installed correctly by checking the node_modules directory in your project root. You should see the @module-federation directory with the nextjs-mf package inside.

By installing the @module-federation/nextjs-mf package, you've taken the first step towards enabling Module Federation in your Next.js project. In the next section, we'll dive deeper into configuring your Host application.

Step 2: Configure Host Application

Setting up next.config.js in the Host Application

Now that you've installed the @module-federation/nextjs-mf package, it's time to configure your Host application to enable Module Federation. In this step, you'll update your next.config.js file to import the NextFederationPlugin and configure it with the required options.

Importing NextFederationPlugin

Add the following code to your next.config.js file to import the NextFederationPlugin:

const { NextFederationPlugin } = require('@module-federation/nextjs-mf');

Configuring NextFederationPlugin

Configure the NextFederationPlugin with the required options using the following example:

module.exports = {
  webpack: (config, options) => {
    config.plugins.push(
      new NextFederationPlugin({
        name: 'host',
        filename: 'static/chunks/remoteEntry.js',
        remotes: {
          remote: 'remote@http://localhost:3001/_next/static/chunks/remoteEntry.js',
        },
        exposes: {
          // Expose modules from the Host application
        },
        shared: {
          // Shared dependencies between the Host and Remote applications
        },
      }),
    );
    return config;
  },
};

Here's a breakdown of the configuration options:

Option Description
name The name of your Host application
filename The filename for the remote entry
remotes The remote application that will be consumed
exposes The modules that will be exposed from the Host application
shared The shared dependencies between the Host and Remote applications

By configuring the NextFederationPlugin in your next.config.js file, you've enabled Module Federation in your Host application. In the next step, you'll set up the Remote module.

Step 3: Set up Remote Module

Creating a New NextJS Application for the Remote Module

Create a new NextJS application that will act as the remote module. This application will expose the desired modules that will be consumed by the Host application.

Create a New NextJS Application

Run the following command to create a new NextJS application:

npx create-next-app remote-app

Configure next.config.js in the Remote Application

Update the next.config.js file in the remote application to expose the desired modules.

Exposed Modules

Module Description
./ComponentA Exposed module from the remote application
./ComponentB Exposed module from the remote application

Shared Dependencies

Dependency Description
// Shared dependencies between the Host and Remote applications

Add the following code to the next.config.js file:

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

module.exports = withFederatedSidecar({
  name: 'remote',
  filename: 'static/chunks/remoteEntry.js',
  exposes: {
    './ComponentA': './components/ComponentA.js',
    './ComponentB': './components/ComponentB.js',
  },
  shared: {
    // Shared dependencies between the Host and Remote applications
  },
});

By following these steps, you've set up the remote module and exposed the desired modules. In the next step, you'll consume these remote modules in the Host application.

Step 4: Consume Remote Modules

Now that we have set up the remote module and exposed the desired modules, let's configure the Host application to consume these remote modules.

Configuring the Host Application

In the Host application, we need to update the next.config.js file to consume the remote modules. We'll use the NextFederationPlugin to configure the remotes and specify the modules we want to consume.

Add the following code to the next.config.js file:

const { NextFederationPlugin } = require('@module-federation/nextjs-mf');

module.exports = {
  webpack: (config, options) => {
    const { isServer } = options;
    config.plugins.push(
      new NextFederationPlugin({
        name: 'host',
        filename: 'static/chunks/remoteEntry.js',
        remotes: {
          remote: `remote@http://localhost:3001/_next/static/${isServer? 'ssr' : 'chunks'}/remoteEntry.js`,
        },
      })
    );
    return config;
  },
};

Dynamic Imports

To consume the remote modules, we'll use dynamic imports with next/dynamic. This allows us to import the remote modules only on the client-side, which is essential for Module Federation.

Create a new file components/RemoteComponent.js and add the following code:

import dynamic from 'next/dynamic';

const RemoteComponent = dynamic(() => import('remote/ComponentA'), {
  ssr: false,
});

export default RemoteComponent;

Using the Remote Module

Now that we've set up the dynamic import, let's use the remote module in our Host application. Create a new file pages/index.js and add the following code:

import RemoteComponent from '../components/RemoteComponent';

function HomePage() {
  return (
    <div>
      <h1>Home Page</h1>
      <RemoteComponent />
    </div>
  );
}

export default HomePage;

By following these steps, you've successfully consumed the remote module in your Host application. In the next step, we'll discuss managing shared dependencies between the Host and Remote applications.

sbb-itb-5683811

Step 5: Manage Shared Dependencies

When building a micro-frontend architecture using Next.js and Module Federation, managing shared dependencies is crucial to avoid code duplication and optimize performance. In this step, we'll explore best practices for configuring shared dependencies using the shared option in the NextFederationPlugin.

Understanding Shared Dependencies

In a micro-frontend architecture, multiple applications may share common dependencies, such as libraries or utilities. Without proper management, these shared dependencies can lead to code duplication, increased bundle sizes, and slower load times. Module Federation provides a solution to this problem by allowing you to declare shared dependencies in the NextFederationPlugin configuration.

Configuring Shared Dependencies

To configure shared dependencies, you need to specify the shared option in the NextFederationPlugin configuration. This option allows you to declare a list of modules that should be shared across different applications.

Here's an example:

const { NextFederationPlugin } = require('@module-federation/nextjs-mf');

module.exports = {
  webpack: (config, options) => {
    const { isServer } = options;
    config.plugins.push(
      new NextFederationPlugin({
        name: 'host',
        filename: 'static/chunks/remoteEntry.js',
        remotes: {
          remote: `remote@http://localhost:3001/_next/static/${isServer? 'ssr' : 'chunks'}/remoteEntry.js`,
        },
        shared: {
          '@emotion/': { eager: true, requiredVersion: false, singleton: true },
          '@chakra-ui/': { eager: true, requiredVersion: false, singleton: true },
          './utils': { eager: true, requiredVersion: false, singleton: true },
        },
      })
    );
    return config;
  },
};

In this example, we've configured the shared option to include the @emotion/, @chakra-ui/, and ./utils modules. These modules will be shared across both the Host and Remote applications, ensuring that only a single instance of each module is loaded.

Benefits of Shared Dependencies

Configuring shared dependencies using the shared option provides several benefits:

Benefit Description
Reduced code duplication Avoid duplicating code across different applications
Optimized performance Shared dependencies reduce the overall bundle size, leading to faster load times
Simplified maintenance With shared dependencies, you only need to maintain a single instance of each module

By following these best practices for managing shared dependencies, you can ensure a more efficient and scalable micro-frontend architecture using Next.js and Module Federation. In the next step, we'll discuss testing your Module Federation setup.

Step 6: Test Module Federation Setup

Before deploying your Module Federation setup to production, test it locally to ensure seamless integration. In this step, we'll guide you through the process of testing your Module Federation setup.

Local Testing

To test your Module Federation setup locally, follow these steps:

  1. Start both applications: Run npm start or yarn start in both the Host and Remote applications to start them in development mode.
  2. Verify remote module loading: Open the Host application in your browser and verify that the remote module is loaded correctly. You can use the browser's developer tools to inspect the network requests and ensure that the remote module is being fetched from the correct URL.
  3. Test module functionality: Test the functionality of the remote module to ensure it's working as expected. This includes verifying that the module is rendering correctly, handling events correctly, and interacting with other parts of the application as expected.

Troubleshooting Common Issues

During local testing, you may encounter some common issues. Here are some troubleshooting tips to help you resolve them:

Issue Solution
Module not found Verify that the module is correctly exposed in the Remote application's next.config.js file. Ensure that the Host application is correctly configured to consume the remote module.
Module loading errors Check the browser's console for error messages. This can help you identify issues with the module's code or dependencies.

By following these guidelines, you can ensure that your Module Federation setup is working correctly and is ready for deployment to production. In the next step, we'll discuss deploying your federated modules.

Step 7: Deploy Federated Modules

Now that you've successfully tested your Module Federation setup, it's time to deploy your federated modules to a live production environment. In this step, we'll guide you through the process of deploying your Module Federation setup.

Deployment Options

You have two primary options for deploying your Module Federation setup:

Deployment Option Description
Server-side rendering (SSR) Deploy your Host and Remote applications on a server, allowing for server-side rendering of remote modules.
Client-side rendering (CSR) Deploy your Host and Remote applications on a client-side platform, such as a CDN or a cloud provider.

Preparing for Deployment

Before deploying your Module Federation setup, make sure you've:

  1. Tested your setup: Verify that your Module Federation setup is working correctly in a local development environment.
  2. Optimized your code: Minify and compress your code to reduce file sizes and improve page load times.
  3. Configured your environment variables: Set up environment variables for your production environment, such as API keys and database connections.

Deploying Your Federated Modules

To deploy your federated modules, follow these steps:

  1. Build your applications: Run npm run build or yarn build in both the Host and Remote applications to generate production-ready builds.
  2. Upload to a CDN or cloud provider: Upload your built applications to a CDN or cloud provider, such as AWS S3 or Google Cloud Storage.
  3. Configure routing: Set up routing for your Host and Remote applications, ensuring that requests are routed correctly between the two.
  4. Monitor and debug: Monitor your deployment for errors and debug any issues that arise.

By following these guidelines, you can successfully deploy your Module Federation setup to a live production environment, providing a seamless and efficient experience for your users.

Troubleshooting Common Issues

Verifying Remote Module Availability

When troubleshooting Module Federation issues, one common problem is verifying that the remote module is available and can be accessed by the host application. To resolve this, ensure that the remote module's remoteEntry.js file is correctly configured and exposed.

Checklist:

Step Description
1 Verify that the remote module's remoteEntry.js file is generated correctly during the build process.
2 Check that the remoteEntry.js file is accessible via the specified URL.
3 Ensure that the host application is correctly configured to consume the remote module.

Fixing Module Resolution Errors

Module resolution errors can occur when the host application is unable to resolve the remote module. To fix this, review the module resolution configuration and ensure that it is correctly set up.

Checklist:

Step Description
1 Verify that the module resolution configuration is correctly set up in the host application.
2 Check that the remote module is correctly exposed and imported in the host application.
3 Ensure that the module resolution configuration is consistent across both the host and remote applications.

Handling Shared Dependency Issues

When using Module Federation, shared dependencies can sometimes cause issues. To resolve this, review the shared dependency configuration and ensure that it is correctly set up.

Checklist:

Step Description
1 Verify that shared dependencies are correctly configured and exposed in both the host and remote applications.
2 Check that the shared dependencies are correctly imported and used in both applications.
3 Ensure that the shared dependency configuration is consistent across both applications.

By following these troubleshooting tips, you can resolve common Module Federation issues and ensure a seamless experience for your users.

Summary

In this NextJS Module Federation Quickstart Guide, we've covered the essential steps to integrate Module Federation into your NextJS project. By following these steps, you can efficiently develop and deploy micro-frontends, making your development process more efficient and improving collaboration among teams.

Here's a recap of what we've covered:

  • Installing required packages
  • Configuring the host application
  • Setting up remote modules
  • Consuming remote modules
  • Managing shared dependencies
  • Testing and deploying federated modules

By using Module Federation, you can break down large applications into smaller, independent modules, making it easier to maintain and update your codebase. This approach enables faster development cycles, improved collaboration, and a more scalable architecture.

With this guide, you're now equipped to take advantage of Module Federation in your NextJS projects, making your development workflow more efficient.

Related posts

Read more

Built on Unicorn Platform