logo
  • Guide
  • Config
  • Plugin
  • API
  • Examples
  • Community
  • Modern.js 2.x Docs
  • English
    • 简体中文
    • English
    • Start
      Introduction
      Quick Start
      Upgrading
      Glossary
      Tech Stack
      Core Concept
      Page Entry
      Build Engine
      Web Server
      Basic Features
      Routes
      Routing
      Config Routes
      Data Solution
      Data Fetching
      Data Writing
      Data Caching
      Rendering
      Server-Side Rendering
      Streaming SSR
      Rendering Cache
      Static Site Generation
      Render Preprocessing
      Styling
      Styling
      Use CSS Modules
      Using CSS-in-JS
      Using Tailwind CSS
      HTML Template
      Import Static Assets
      Import JSON Files
      Import SVG Assets
      Import Wasm Assets
      Debug
      Data Mocking
      Network Proxy
      Using Rsdoctor
      Using Storybook
      Testing
      Playwright
      Vitest
      Jest
      Cypress
      Path Alias
      Environment Variables
      Output Files
      Deploy Application
      Advanced Features
      Using Rspack
      Using BFF
      Basic Usage
      Runtime Framework
      Extend BFF Server
      Extend Request SDK
      File Upload
      Cross-Project Invocation
      Optimize Page Performance
      Code Splitting
      Inline Static Assets
      Bundle Size Optimization
      React Compiler
      Improve Build Performance
      Browser Compatibility
      Low-Level Tools
      Source Code Build Mode
      Server Monitor
      Monitors
      Logs Events
      Metrics Events
      Internationalization
      Basic Concepts
      Quick Start
      Configuration
      Locale Detection
      Resource Loading
      Routing Integration
      API Reference
      Advanced Usage
      Best Practices
      Custom Web Server
      Topic Detail
      Module Federation
      Introduction
      Getting Started
      Application-Level Modules
      Server-Side Rendering
      Deployment
      Integrating Internationalization
      FAQ
      Dependencies FAQ
      CLI FAQ
      Build FAQ
      HMR FAQ
      📝 Edit this page
      Previous pageApplication-Level ModulesNext pageDeployment

      #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

      Application-level modules (modules using createBridgeComponent and createRemoteAppComponent) do not support server-side rendering (SSR). If you need to use SSR functionality, please use component-level module export methods instead.

      #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 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>
        );
      };

      #Consuming Components

      Consumers must use createLazyComponent to load remote components and specify the export as the component name.

      src/routes/page.tsx
      import type { JSX } from 'react';
      import { getInstance } from '@module-federation/modern-js/runtime';
      import {
        ERROR_TYPE,
        lazyLoadComponentPlugin,
      } from '@module-federation/modern-js/react';
      
      const instance = getInstance();
      instance!.registerPlugins([lazyLoadComponentPlugin()]);
      
      const Button = instance!.createLazyComponent({
        loader: () => {
          return import('remote/Button');
        },
        loading: 'loading...',
        export: 'Button', // Configure this as the export name of the remote component
        fallback: ({ error, errorType, dataFetchMapKey }) => {
          console.error(error);
          if (errorType === ERROR_TYPE.LOAD_REMOTE) {
            return <div>load remote failed</div>;
          }
          if (errorType === ERROR_TYPE.DATA_FETCH) {
            return (
              <div>
                data fetch failed, the dataFetchMapKey key is: {dataFetchMapKey}
              </div>
            );
          }
          return <div>error type is unknown</div>;
        },
      });
      
      const Index = (): JSX.Element => {
        return (
          <div>
            <h1>Basic usage with data fetch</h1>
            <Button />
          </div>
        );
      };
      
      export default Index;