Custom Web Server

Modern.js encapsulates most server-side capabilities required by projects, typically eliminating the need for server-side development. However, in certain scenarios such as user authentication, request preprocessing, or adding page skeletons, custom server-side logic may still be necessary.

Modern.js provides two types of APIs to extend the Web Server: Middleware and Lifecycle Hooks.

NOTE

Middleware and Hooks only take effect when users request page routes, and BFF routes won't pass through these APIs.

Enabling Custom Web Server

Developers can execute the pnpm run new command in the project root directory to enable the "Custom Web Server" feature:

? Select operation: Create project element
? Select element type: Create "Custom Web Server" source directory

After executing the command, register the @modern-js/plugin-server plugin in modern.config.ts:

modern.config.ts
import { serverPlugin } from '@modern-js/plugin-server';

export default defineConfig({
  plugins: [..., serverPlugin()],
});

Once enabled, a server/index.ts file will be automatically created in the project directory where custom logic can be implemented.

Custom Web Server Capabilities

Unstable Middleware

Modern.js supports adding rendering middleware to the Web Server, allowing custom logic execution before and after processing page routes.

server/index.ts
import {
  UnstableMiddleware,
  UnstableMiddlewareContext,
} from '@Modern.js/runtime/server';

const time: UnstableMiddleware = async (c: UnstableMiddlewareContext, next) => {
  const start = Date.now();

  await next();

  const end = Date.now();

  console.log(`dur=${end - start}`);
};

export const unstableMiddleware: UnstableMiddleware[] = [time];
INFO

For detailed API and more usage, see UnstableMiddleware.

Hooks

WARNING

We recommend using UnstableMiddleware instead of Hooks.

Modern.js provides Hooks to control specific logic in the Web Server. All page requests will pass through Hooks.

Currently, two types of Hooks are available: AfterMatch and AfterRender. Developers can implement them in server/index.ts as follows:

import type {
  AfterMatchHook,
  AfterRenderHook,
} from '@modern-js/runtime/server';

export const afterMatch: AfterMatchHook = (ctx, next) => {
  next();
};

export const afterRender: AfterRenderHook = (ctx, next) => {
  next();
};

Best practices when using Hooks:

  1. Perform authorization checks in afterMatch.
  2. Handle Rewrite and Redirect in afterMatch.
  3. Inject HTML content in afterRender.
INFO

For detailed API and more usage, see Hook.