Plugin API
Modern.js's Server plugins allow you to extend and customize functionality during the server-side request processing phase, such as adding middleware, modifying request responses, etc.
Server plugins need to be configured via the plugins field in server/modern.server.ts.
Plugin Basic Structure
A typical Server plugin structure is as follows:
name: A unique identifier for the plugin.- The
setupfunction receives anapiobject, which provides all available Server plugin APIs.
Information Retrieval
api.getServerContext
Gets the context information of the Modern.js server.
- Returns: A
ServerContextobject containing the following fields:
- Example:
The context information returned by getServerContext is read-only. Use updateServerContext if you need to modify it.
api.getServerConfig
Gets the server configuration defined by the user in the server/modern.server.ts file.
- Returns: The user-defined server configuration object.
- Example:
api.getHooks
Gets all registered hook functions.
- Returns: An object containing all hook functions.
- Example:
In custom plugins, you can only manually call the hooks registered by the corresponding plugin and cannot call official hooks to avoid affecting the normal execution order of the application.
Context Modification
api.updateServerContext
Updates the server context information.
- Type:
api.updateServerContext(updateContext: DeepPartial<ServerContext>) - Parameters:
updateContext: The context object to update (partial update).
- Execution Phase: Can be used at any stage.
- Example:
Lifecycle Hooks
api.onPrepare
Adds additional logic during the server preparation phase.
- Type:
api.onPrepare(prepareFn: () => void | Promise<void>) - Parameters:
prepareFn: A preparation function, without parameters, can be asynchronous.
- Execution Phase: After the server completes configuration validation and before applying middleware.
- Example:
In the onPrepare hook, you can modify the context object returned by getServerContext() (such as middlewares, renderMiddlewares), and these modifications will take effect when the server starts.
api.onReset
Adds additional logic when the server resets.
- Type:
api.onReset(resetFn: (params: { event: ResetEvent }) => void | Promise<void>) - Parameters:
resetFn: A reset handler function that receives reset event parameters.event.type: Event type, possible values:'repack': Repack event'file-change': File change event
event.payload: Whentypeis'file-change', contains an array of file change information.
- Execution Phase: When files change or repack is needed.
- Example:
Other Notes
- Refer to Server Plugin Lifecycle to understand the execution order of plugin hooks.
- The execution order of middleware can be controlled through the
orderfield ('pre','default','post'), or through thebeforefield to specify execution before other middleware.