--- title: "Middleware & Components" description: "Use middleware for keyword replies and filtering, write mixed messages, buttons and cards in JSX, and see how they look on each platform" --- # Middleware & components For per-conversation preferences before rendering, see [Customize built-in presentation](./behavior-customization.md). - **Middleware** is an interceptor every message passes through — keyword replies, filters, moderation. - **Components** are reusable message cards written in JSX. Commands, middleware and components can all return JSX directly: the same content shows as an image on image-capable platforms and falls back to text elsewhere. ## Middleware ### Keyword replies ```ts // middlewares/keyword-reply/index.ts import { defineMiddleware } from 'zhin.js/middleware'; import type { Message } from 'zhin.js'; export default defineMiddleware({ handle({ input }, next) { if (input.content === 'status') return 'online'; return next(); }, }); ``` When a user sends "status" the bot replies "online"; everything else goes through `next()` to later middleware and commands. `input` is the incoming message — commonly `content` (text), `sender` and `$reply()`. ### What the return value does | Code | Result | | --- | --- | | `return 'online'` or `return online` | Stop here and reply with this content | | `return next()` | Pass it on and keep whatever reply comes back | | `await next()` with no return | Same as above | | `await next(); return OK` | Let later steps run, then **replace** their reply with yours | | No `next()` and no return | Swallow the message; no reply | - The bot **auto-replies once**, after the whole chain finishes. Manual `$reply()` calls can send several times and can't be taken back later. - Call `next()` at most once per middleware. Its return value is only for passing results back — it isn't a message you can modify. - A matched command that returns nothing still counts as handled and won't be passed to the AI. ### Control the order ```ts export default defineMiddleware({ phase: 'before-dispatch', // default; or 'after-dispatch' order: 10, // default 0; lower runs first handle({ input }, next) { /* ... */ }, }); ``` Sorting compares `phase` → `order` → plugin mount order → capability id. ### Only for some messages (`permit`) Inbound middleware can declare `permit`, with the same rules and evaluator as commands and Agent tools (the sender's zhin role, the sender's platform standing `platform:*`, the bot's own standing `bot:*`; see [Chat roles](../concepts/chat-roles.md)): ```ts export default defineMiddleware({ permit: ['group()', 'bot:admin'], // only in groups where the bot is an admin async handle({ input }, next) { /* recall offending messages… */ await next(); }, }); ``` When unmet, the message **skips** that middleware and the chain continues; no reply is sent. The check is light: the bot's own standing is read from the cache only (a missing entry is refreshed in the background), so no platform request is added per message, and an unknown standing leaves `bot:*` unmet. Outbound middleware does not accept `permit`. The middleware argument also has `config` (plugin config), `has(token)`, `use(token)` (plugin services), `session`, `signal`, `onAfterDispatch`, `owner` and `generation`. Declare `adapter` and `$client` gets that platform SDK's type. To give `config` a strong TypeScript type, use `defineMiddleware.withConfig()`: ```ts import { defineMiddleware } from 'zhin.js/middleware'; import { databaseHostToken } from 'zhin.js'; interface MyConfig { triggerWord: string; } export default defineMiddleware.withConfig()({ handle({ input, config, has, use }, next) { if (input.content === config.triggerWord) { const db = has(databaseHostToken) ? use(databaseHostToken) : undefined; return `Matched trigger word (DB: ${db ? 'connected' : 'none'})`; } return next(); }, }); ``` ### Rewrite or block outgoing messages With `target: 'outbound'`, the middleware handles messages **about to be sent**: ```tsx // middlewares/review/index.tsx import { defineMiddleware } from 'zhin.js/middleware'; import type { OutboundEnvelope } from 'zhin.js/core/runtime'; export default defineMiddleware({ target: 'outbound', async handle({ input }, next) { input.replace(Reviewed content); // rewrite the content await next(); // without next(), nothing is sent }, }); ``` Outbound middleware rewrites with `input.replace()` rather than a return value. `input.payload` is the content about to go to the platform — good for review and blocking; replaced content still goes through rendering and platform validation. ## Writing messages in JSX ### Setup In your project's `tsconfig.json`: ```json { "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "zhin.js" } } ``` Then save files as `.tsx`, e.g. `commands/card/index.tsx`. Projects from `npm create zhin-app` are already configured. This JSX is Zhin's own implementation and **has nothing to do with React**. ### Mixed content Lowercase tags are built-in message elements; no import needed: ```tsx // commands/hi/index.tsx import { defineCommand } from 'zhin.js/command'; export default defineCommand({ execute: () => <> hello , }); ``` One message containing, in order: text, an image, and a mention. Common tags include `text`, `image`, `mention`, `face`, `audio`, `video`, `file`, `reply`, `forward`, `link`, `qrcode`, `markdown`, `keyboard` and `tts`; full list in [Reference · Built-in tags](#built-in-tags). ### Buttons ```tsx ``` When the user clicks, `onClick` runs in the original conversation and its return value is sent as a reply. Platforms with native buttons show a button; others show a numbered option ("reply 1 to show result"). ::: details More button rules - Returning a string, segment or JSX from `onClick` replies once; `null`, `undefined` or booleans send nothing; the number `0` replies `0`. You can also call `message.$reply()` inside the callback. - Callbacks are valid only for the original conversation and current version: they expire after an hour, a plugin hot reload, or a process restart. - To restrict who may click, give the button a `permit` (the same rules and evaluator as commands, applied to the **clicker**): ` ), }); ``` Content inside `` is rendered as HTML. On platforms that can't show HTML directly it becomes an image when `@zhin.js/html-renderer` is installed, or text otherwise — see [How it looks on each platform](#how-it-looks-on-each-platform). The library needs neither React nor a screenshot engine. Set a theme once with `ThemeProvider` (colors, fonts, radius, shadows…) and override locally with `custom.style` / `custom.text`. Full component list: [components README](https://github.com/zhinjs/zhin/blob/main/packages/toolkit/components/README.md). ::: warning No CSS files Server-side TSX only transpiles JSX — **you can't `import './card.css'`**, and CSS Modules, Sass, Less and PostCSS aren't supported. Use inline `style` (object or string), themes, or the Tailwind utilities below. ::: ### Tables, Markdown and code blocks ```tsx import { Table, Checkbox, Switch, Button, MarkdownView, CodeBlock } from '@zhin.js/components'; const report = Release check, , , ], ]} />; const article = ; const snippet = plugin.ts} source={'const ready = true;\nconsole.log(ready);'} />; ``` - `Checkbox`, `Radio`, `Switch` and `Button` only **display** state and have no click events. For interaction use `