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 pageStatic Site GenerationNext pageStyling

      #Render Preprocessing

      In certain scenarios, applications need to perform preprocessing operations before rendering. Modern.js recommends using Runtime Plugins to implement this type of logic.

      #Defining a Runtime Plugin

      import type { RuntimePlugin } from '@modern-js/runtime';
      
      const myRuntimePlugin = (): RuntimePlugin => ({
        name: 'my-runtime-plugin',
        setup: api => {
          api.onBeforeRender(context => {
            // Logic to execute before rendering
            console.log('Before rendering:', context);
          });
        },
      });
      
      export default myRuntimePlugin;

      #Registering the Plugin

      Register the plugin in your project's src/modern.runtime.ts file:

      import { defineRuntimeConfig } from '@modern-js/runtime';
      import myRuntimePlugin from './plugins/myRuntimePlugin';
      
      export default defineRuntimeConfig({
        plugins: [myRuntimePlugin()],
      });

      #Use Case -- Global Data Injection

      Through the context parameter of the onBeforeRender hook, you can inject global data into your application. Application components can access this data using the use(RuntimeContext) Hook.

      Info

      This feature is particularly useful in the following scenarios:

      • Applications requiring page-level preliminary data
      • Custom data injection workflows
      • Framework migration scenarios (e.g., migrating from Next.js)

      Defining a Data Injection Plugin

      import type { RuntimePlugin } from '@modern-js/runtime';
      
      const dataInjectionPlugin = (): RuntimePlugin => ({
        name: 'data-injection-plugin',
        setup: api => {
          api.onBeforeRender(context => {
            // Inject data into the context
            context.message = 'Hello World';
          });
        },
      });
      
      export default dataInjectionPlugin;

      Using Injected Data in Components

      import { use } from 'react';
      import { RuntimeContext } from '@modern-js/runtime';
      
      export default function MyComponent() {
        const context = use(RuntimeContext);
        const { message } = context;
      
        return <div>{message}</div>;
      }

      Using with SSR

      In SSR scenarios, the browser can access data injected via onBeforeRender during server-side rendering. Developers can decide whether to re-fetch data on the browser side to override server data based on their requirements.

      import type { RuntimePlugin } from '@modern-js/runtime';
      
      const dataInjectionPlugin = (): RuntimePlugin => ({
        name: 'data-injection-plugin',
        setup: api => {
          api.onBeforeRender(context => {
            if (process.env.MODERN_TARGET === 'node') {
              // Set data during server-side rendering
              context.message = 'Hello World By Server';
            } else {
              // Check data during client-side rendering
              if (!context.message) {
                // If server data is not available, set client data
                context.message = 'Hello World By Client';
              }
            }
          });
        },
      });
      
      export default dataInjectionPlugin;