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
      Rendering Mode Overview
      Server-Side Rendering
      Streaming Server-Side Rendering
      Rendering Cache
      Static Site Generation
      React Server Components (RSC)
      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
      Creating Extensible BFF Functions
      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
      Upgrade
      Overview
      Configuration Changes
      Entry Changes
      Custom Web Server Changes
      Tailwind Plugin Changes
      Other Important Changes
      📝 Edit this page
      Previous pageEntry ChangesNext pageTailwind Plugin Changes

      #Custom Web Server Changes

      This chapter covers upgrades for two types of legacy custom Server APIs:

      • unstableMiddleware
      • Hook

      These two approaches are mutually exclusive in the legacy version. When migrating, please choose the corresponding path based on the capabilities actually used in the project.

      #unstableMiddleware

      #Core Differences

      • File Structure: server/index.ts → server/modern.server.ts
      • Export Method: unstableMiddleware array → defineServerConfig
      • Context API: Modern.js Server Context → Hono Context (c.req/c.res)
      • Middleware Execution: Legacy version could skip calling next(), new version must call it for subsequent chain execution
      • Response Method: c.response.raw() → c.text() / c.json()

      #File and Export

      // Legacy - server/index.ts
      export const unstableMiddleware: UnstableMiddleware[] = [middleware1, middleware2];
      
      // New - server/modern.server.ts
      import { defineServerConfig } from '@modern-js/server-runtime';
      
      export default defineServerConfig({
        middlewares: [
          { name: 'middleware1', handler: middleware1 },
          { name: 'middleware2', handler: middleware2 },
        ],
      });

      #Type and next Call

      // Legacy
      import type { UnstableMiddleware, UnstableMiddlewareContext } from '@modern-js/server-runtime';
      const middleware: UnstableMiddleware = async (c: UnstableMiddlewareContext, next) => {
        return c.response.raw('response'); // Will continue rendering even without calling next
      };
      
      // New
      import { defineServerConfig, type MiddlewareHandler } from '@modern-js/server-runtime';
      const middleware: MiddlewareHandler = async (c, next) => {
        await next(); // Must call
        return c.text('response');
      };

      #Context API Comparison

      Legacy APINew APIDescription
      c.request.cookiegetCookie(c, 'key')Cookie reading
      c.req.cookie()getCookie(c, 'key')Hono v4 deprecated
      c.request.pathnamec.req.pathRequest path
      c.request.hostc.req.header('Host')Request host
      c.request.queryc.req.query()Query parameters
      c.request.headersc.req.header()Request headers
      c.response.statusc.status()Response status code
      c.response.setc.res.headers.setSet response headers
      c.response.rawc.text / c.jsonResponse body

      #afterRender Hook

      afterRender is only used for HTML processing after page rendering is complete.

      import { defineServerConfig, type MiddlewareHandler } from '@modern-js/server-runtime';
      
      const renderMiddleware: MiddlewareHandler = async (c, next) => {
        await next(); // Wait for page rendering first
        const { res } = c;
        const html = await res.text();
      
        const modified = html
          .replace('<head>', '<head><meta name="author" content="ByteDance">')
          .replace('<body>', '<body><div id="loading">Loading...</div>')
          .replace('</body>', '<script>console.log("Page loaded")</script></body>');
      
        c.res = c.body(modified, { status: res.status, headers: res.headers });
      };
      
      export default defineServerConfig({
        renderMiddlewares: [{ name: 'custom-content-injection', handler: renderMiddleware }],
      });