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
      Deprecated
      📝 Edit this page
      Previous pageFile UploadNext pageCode Splitting

      #Cross-Project Invocation

      Based on the BFF architecture, Modern.js provides cross-project invocation capabilities, allowing BFF functions created in one project to be invoked by other projects through integrated calls, enabling function sharing and feature reuse across projects. Cross-project invocation consists of producer and consumer sides. The producer is responsible for creating and providing BFF services while generating integrated invocation SDK, and the consumer initiates requests through these SDK.

      #BFF Producer

      Upgrade Modern.js dependencies to version x.64.4 or higher, then enable cross-project invocation via configuration. Projects with BFF capabilities enabled can act as BFF producers, or you can create standalone BFF applications. When executing dev or build, the following artifacts for consumers will be automatically generated:

      • API functions under the dist/client directory
      • Runtime configuration functions under the dist/runtime directory
      • Interface exports defined in exports field of package.json
      • File list for npm publication specified in files field of package.json

      #Existing BFF-enabled Projects

      1. Enable Cross-Project Invocation

      Ensure the current project has BFF enabled with API files defined under api/lambda. Add the following configuration:

      modern.config.ts
      export default defineConfig({
        bff: {
          crossProject: true,
        }
      });
      1. Generate SDK Type Files

      To provide type hints for the integrated invocation SDK, enable the declaration option in TypeScript configuration:

      tsconfig.json
      "compilerOptions": {
          "declaration": true,
      }

      #Create BFF Application

      1. run @modern-js/create command:
      npx @modern-js/create@latest myapi
      1. interactive Q & A interface to initialize the project based on the results, with initialization performed according to the default settings:
      ? Please select the programming language: TS
      ? Please select the package manager: pnpm
      1. Execute the new command,enable BFF:
      ? Please select the operation you want to perform Enable optional features
      ? Please select the feature to enable Enable "BFF"
      ? Please select BFF type Framework mode
      1. Execute【Existing BFF-enabled Projects】to turn on the cross-project call switch.

      Note: When a project serves solely as a BFF producer, its runtime does not depend on the /src source directory. Removing the /src directory can help optimize the project's build efficiency.

      #BFF Consumer

      Info

      You can initiate requests to BFF producers from projects using any framework via the SDK.

      #Intra-Monorepo Invocation

      When producer and consumer are in the same Monorepo, directly import the SDK. API functions reside under ${package_name}/api:

      src/routes/page.tsx
      import { useState, useEffect } from 'react';
      import { get as hello } from '${package_name}/api/hello';
      
      export default () => {
        const [text, setText] = useState('');
      
        useEffect(() => {
          hello().then(setText);
        }, []);
        return <div>{text}</div>;
      };

      #Cross-Project Invocation

      When producer and consumer are in separate repositories, publish the BFF producer as an npm package. The invocation method remains the same as intra-Monorepo.

      #Domain Configuration and Extensions

      For real-world scenarios requiring custom BFF service domains, use the configuration function:

      src/routes/page.tsx
      import { configure } from '${package_name}/runtime';
      
      configure({
        setDomain() {
          return 'https://your-bff-api.com';
        },
      });

      The configure function from ${package_name}/runtime supports domain configuration via setDomain, interceptors, and custom SDK. When extending both current project and cross-project SDK on the same page:

      src/routes/page.tsx
      import { configure } from '${package_name}/runtime';
      import { configure as innerConfigure } from '@modern-js/plugin-bff/client';
      import axios from 'axios';
      
      configure({
          setDomain() {
              return 'https://your-bff-api.com';
          },
      });
      
      innerConfigure({
        async request(...config: Parameters<typeof fetch>) {
          const [url, params] = config;
          const res = await axios({
            url: url as string,
            method: params?.method as Method,
            data: params?.body,
            headers: {
              'x-header': 'innerConfigure',
            },
          });
          return res.data;
        },
      });