Server-Side Rendering

@module-federation/modern-js offers powerful capabilities, enabling developers to easily combine Module Federation with server-side rendering (SSR) in Modern.js applications.

Enable SSR

Using the application created in Using Module Federation as an example, you only need to add the server.ssr configuration to both the producer and the consumer:

modern.config.ts
import { appTools, defineConfig } from '@modern-js/app-tools';

export default defineConfig({
  server: {
    ssr: {
      mode: 'stream',
    },
  },
});

For better performance, we only support using this capability combination in Streaming SSR scenarios.

WARNING

Currently, @module-federation/bridge-react is not compatible with the Node environment. You must remove it from the dependencies to use Module Federation and server-side rendering correctly. This means Bridge cannot work with server-side rendering.

Data Fetching

TIP

Currently, this feature is experimental and has not been fully practiced. Please use it with caution.

Module Federation now supports data fetching capabilities. Each producer file can have a corresponding data fetching file, with the file name format of [name].data.ts.

In Modern.js, data fetching can be used with SSR. Using the example in the previous chapter, create a data fetching file:

src/components/Button.data.ts
import type { DataFetchParams } from '@module-federation/modern-js/react';

export type Data = {
  data: string;
};

export const fetchData = async (params: DataFetchParams): Promise<Data> => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        data: `data: ${new Date()}`,
      });
    }, 1000);
  });
};

In Button, we get the data from the Props:

src/components/Button.tsx
import React from 'react';
import './index.css';
import type { Data } from './Button.data';

export const Button = (props: { mfData: Data }) => {
  const { mfData } = props;
  return (
    <button type="button" className="test">
      Remote Button {mfData?.data}
    </button>
  );
};